Meshmerizer.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. //#define SPAM
  28. using System;
  29. using System.Collections.Generic;
  30. using OpenSim.Framework;
  31. using OpenSim.Region.Physics.Manager;
  32. using OpenMetaverse;
  33. using OpenMetaverse.Imaging;
  34. using System.Drawing;
  35. using System.Drawing.Imaging;
  36. using PrimMesher;
  37. using log4net;
  38. using System.Reflection;
  39. using System.IO;
  40. namespace OpenSim.Region.Physics.Meshing
  41. {
  42. public class MeshmerizerPlugin : IMeshingPlugin
  43. {
  44. public MeshmerizerPlugin()
  45. {
  46. }
  47. public string GetName()
  48. {
  49. return "Meshmerizer";
  50. }
  51. public IMesher GetMesher()
  52. {
  53. return new Meshmerizer();
  54. }
  55. }
  56. public class Meshmerizer : IMesher
  57. {
  58. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. //private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  60. // Setting baseDir to a path will enable the dumping of raw files
  61. // raw files can be imported by blender so a visual inspection of the results can be done
  62. #if SPAM
  63. const string baseDir = "rawFiles";
  64. #else
  65. private const string baseDir = null; //"rawFiles";
  66. #endif
  67. private bool cacheSculptMaps = true;
  68. private string decodedScultMapPath = "j2kDecodeCache";
  69. private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
  70. /// <summary>
  71. /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
  72. /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
  73. /// for some reason
  74. /// </summary>
  75. /// <param name="minX"></param>
  76. /// <param name="maxX"></param>
  77. /// <param name="minY"></param>
  78. /// <param name="maxY"></param>
  79. /// <param name="minZ"></param>
  80. /// <param name="maxZ"></param>
  81. /// <returns></returns>
  82. private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
  83. {
  84. Mesh box = new Mesh();
  85. // bottom
  86. box.Add(new Vertex(minX, maxY, minZ));
  87. box.Add(new Vertex(maxX, maxY, minZ));
  88. box.Add(new Vertex(maxX, minY, minZ));
  89. box.Add(new Vertex(minX, minY, minZ));
  90. box.Add(new Triangle(box.vertices[0], box.vertices[1], box.vertices[2]));
  91. box.Add(new Triangle(box.vertices[0], box.vertices[2], box.vertices[3]));
  92. // top
  93. box.Add(new Vertex(maxX, maxY, maxZ));
  94. box.Add(new Vertex(minX, maxY, maxZ));
  95. box.Add(new Vertex(minX, minY, maxZ));
  96. box.Add(new Vertex(maxX, minY, maxZ));
  97. box.Add(new Triangle(box.vertices[4], box.vertices[5], box.vertices[6]));
  98. box.Add(new Triangle(box.vertices[4], box.vertices[6], box.vertices[7]));
  99. // sides
  100. box.Add(new Triangle(box.vertices[5], box.vertices[0], box.vertices[3]));
  101. box.Add(new Triangle(box.vertices[5], box.vertices[3], box.vertices[6]));
  102. box.Add(new Triangle(box.vertices[1], box.vertices[0], box.vertices[5]));
  103. box.Add(new Triangle(box.vertices[1], box.vertices[5], box.vertices[4]));
  104. box.Add(new Triangle(box.vertices[7], box.vertices[1], box.vertices[4]));
  105. box.Add(new Triangle(box.vertices[7], box.vertices[2], box.vertices[1]));
  106. box.Add(new Triangle(box.vertices[3], box.vertices[2], box.vertices[7]));
  107. box.Add(new Triangle(box.vertices[3], box.vertices[7], box.vertices[6]));
  108. return box;
  109. }
  110. /// <summary>
  111. /// Creates a simple bounding box mesh for a complex input mesh
  112. /// </summary>
  113. /// <param name="meshIn"></param>
  114. /// <returns></returns>
  115. private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
  116. {
  117. float minX = float.MaxValue;
  118. float maxX = float.MinValue;
  119. float minY = float.MaxValue;
  120. float maxY = float.MinValue;
  121. float minZ = float.MaxValue;
  122. float maxZ = float.MinValue;
  123. foreach (Vertex v in meshIn.vertices)
  124. {
  125. if (v != null)
  126. {
  127. if (v.X < minX) minX = v.X;
  128. if (v.Y < minY) minY = v.Y;
  129. if (v.Z < minZ) minZ = v.Z;
  130. if (v.X > maxX) maxX = v.X;
  131. if (v.Y > maxY) maxY = v.Y;
  132. if (v.Z > maxZ) maxZ = v.Z;
  133. }
  134. }
  135. return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
  136. }
  137. private void ReportPrimError(string message, string primName, PrimMesh primMesh)
  138. {
  139. m_log.Error(message);
  140. m_log.Error("\nPrim Name: " + primName);
  141. m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
  142. }
  143. public Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod)
  144. {
  145. Mesh mesh = new Mesh();
  146. PrimMesh primMesh;
  147. PrimMesher.SculptMesh sculptMesh;
  148. List<Coord> coords;
  149. List<Face> faces;
  150. Image idata = null;
  151. string decodedSculptFileName = "";
  152. if (primShape.SculptEntry)
  153. {
  154. if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
  155. {
  156. decodedSculptFileName = System.IO.Path.Combine(decodedScultMapPath, "smap_" + primShape.SculptTexture.ToString());
  157. try
  158. {
  159. if (File.Exists(decodedSculptFileName))
  160. {
  161. idata = Image.FromFile(decodedSculptFileName);
  162. }
  163. }
  164. catch (Exception e)
  165. {
  166. m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
  167. }
  168. //if (idata != null)
  169. // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
  170. }
  171. if (idata == null)
  172. {
  173. if (primShape.SculptData.Length == 0)
  174. return null;
  175. try
  176. {
  177. ManagedImage managedImage; // we never use this
  178. OpenJPEG.DecodeToImage(primShape.SculptData, out managedImage, out idata);
  179. if (cacheSculptMaps)
  180. {
  181. try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
  182. catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
  183. }
  184. }
  185. catch (DllNotFoundException)
  186. {
  187. m_log.Error("[PHYSICS]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed. Often times this is because of an old version of GLIBC. You must have version 2.4 or above!");
  188. return null;
  189. }
  190. catch (IndexOutOfRangeException)
  191. {
  192. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  193. return null;
  194. }
  195. catch (Exception)
  196. {
  197. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed!");
  198. return null;
  199. }
  200. }
  201. PrimMesher.SculptMesh.SculptType sculptType;
  202. switch ((OpenMetaverse.SculptType)primShape.SculptType)
  203. {
  204. case OpenMetaverse.SculptType.Cylinder:
  205. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  206. break;
  207. case OpenMetaverse.SculptType.Plane:
  208. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  209. break;
  210. case OpenMetaverse.SculptType.Torus:
  211. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  212. break;
  213. case OpenMetaverse.SculptType.Sphere:
  214. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  215. break;
  216. default:
  217. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  218. break;
  219. }
  220. bool mirror = ((primShape.SculptType & 128) != 0);
  221. bool invert = ((primShape.SculptType & 64) != 0);
  222. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
  223. idata.Dispose();
  224. sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  225. sculptMesh.Scale(size.X, size.Y, size.Z);
  226. coords = sculptMesh.coords;
  227. faces = sculptMesh.faces;
  228. }
  229. else
  230. {
  231. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  232. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  233. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  234. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  235. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  236. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  237. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  238. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  239. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  240. if (profileHollow > 0.95f)
  241. profileHollow = 0.95f;
  242. int sides = 4;
  243. if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  244. sides = 3;
  245. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  246. sides = 24;
  247. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  248. { // half circle, prim is a sphere
  249. sides = 24;
  250. profileBegin = 0.5f * profileBegin + 0.5f;
  251. profileEnd = 0.5f * profileEnd + 0.5f;
  252. }
  253. int hollowSides = sides;
  254. if (primShape.HollowShape == HollowShape.Circle)
  255. hollowSides = 24;
  256. else if (primShape.HollowShape == HollowShape.Square)
  257. hollowSides = 4;
  258. else if (primShape.HollowShape == HollowShape.Triangle)
  259. hollowSides = 3;
  260. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  261. if (primMesh.errorMessage != null)
  262. if (primMesh.errorMessage.Length > 0)
  263. m_log.Error("[ERROR] " + primMesh.errorMessage);
  264. primMesh.topShearX = pathShearX;
  265. primMesh.topShearY = pathShearY;
  266. primMesh.pathCutBegin = pathBegin;
  267. primMesh.pathCutEnd = pathEnd;
  268. if (primShape.PathCurve == (byte)Extrusion.Straight)
  269. {
  270. primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
  271. primMesh.twistEnd = primShape.PathTwist * 18 / 10;
  272. primMesh.taperX = pathScaleX;
  273. primMesh.taperY = pathScaleY;
  274. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  275. {
  276. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  277. if (profileBegin < 0.0f) profileBegin = 0.0f;
  278. if (profileEnd > 1.0f) profileEnd = 1.0f;
  279. }
  280. #if SPAM
  281. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  282. #endif
  283. try
  284. {
  285. primMesh.ExtrudeLinear();
  286. }
  287. catch (Exception ex)
  288. {
  289. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  290. return null;
  291. }
  292. }
  293. else
  294. {
  295. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  296. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  297. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  298. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  299. primMesh.skew = 0.01f * primShape.PathSkew;
  300. primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
  301. primMesh.twistEnd = primShape.PathTwist * 36 / 10;
  302. primMesh.taperX = primShape.PathTaperX * 0.01f;
  303. primMesh.taperY = primShape.PathTaperY * 0.01f;
  304. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  305. {
  306. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  307. if (profileBegin < 0.0f) profileBegin = 0.0f;
  308. if (profileEnd > 1.0f) profileEnd = 1.0f;
  309. }
  310. #if SPAM
  311. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  312. #endif
  313. try
  314. {
  315. primMesh.ExtrudeCircular();
  316. }
  317. catch (Exception ex)
  318. {
  319. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  320. return null;
  321. }
  322. }
  323. primMesh.DumpRaw(baseDir, primName, "primMesh");
  324. primMesh.Scale(size.X, size.Y, size.Z);
  325. coords = primMesh.coords;
  326. faces = primMesh.faces;
  327. mesh.primMesh = primMesh;
  328. }
  329. int numCoords = coords.Count;
  330. int numFaces = faces.Count;
  331. for (int i = 0; i < numCoords; i++)
  332. {
  333. Coord c = coords[i];
  334. mesh.vertices.Add(new Vertex(c.X, c.Y, c.Z));
  335. }
  336. List<Vertex> vertices = mesh.vertices;
  337. for (int i = 0; i < numFaces; i++)
  338. {
  339. Face f = faces[i];
  340. mesh.triangles.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
  341. }
  342. return mesh;
  343. }
  344. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod)
  345. {
  346. return CreateMesh(primName, primShape, size, lod, false);
  347. }
  348. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod, bool isPhysical)
  349. {
  350. Mesh mesh = null;
  351. if (size.X < 0.01f) size.X = 0.01f;
  352. if (size.Y < 0.01f) size.Y = 0.01f;
  353. if (size.Z < 0.01f) size.Z = 0.01f;
  354. mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
  355. if (mesh != null)
  356. {
  357. if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
  358. {
  359. #if SPAM
  360. m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
  361. minSizeForComplexMesh.ToString() + " - creating simple bounding box");
  362. #endif
  363. mesh = CreateBoundingBoxMesh(mesh);
  364. mesh.DumpRaw(baseDir, primName, "Z extruded");
  365. }
  366. // trim the vertex and triangle lists to free up memory
  367. mesh.vertices.TrimExcess();
  368. mesh.triangles.TrimExcess();
  369. }
  370. return mesh;
  371. }
  372. }
  373. }