Meshmerizer.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 System.Drawing;
  34. using System.Drawing.Imaging;
  35. using PrimMesher;
  36. using log4net;
  37. using System.Reflection;
  38. using System.IO;
  39. namespace OpenSim.Region.Physics.Meshing
  40. {
  41. public class MeshmerizerPlugin : IMeshingPlugin
  42. {
  43. public MeshmerizerPlugin()
  44. {
  45. }
  46. public string GetName()
  47. {
  48. return "Meshmerizer";
  49. }
  50. public IMesher GetMesher()
  51. {
  52. return new Meshmerizer();
  53. }
  54. }
  55. public class Meshmerizer : IMesher
  56. {
  57. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  58. // Setting baseDir to a path will enable the dumping of raw files
  59. // raw files can be imported by blender so a visual inspection of the results can be done
  60. #if SPAM
  61. const string baseDir = "rawFiles";
  62. #else
  63. private const string baseDir = null; //"rawFiles";
  64. #endif
  65. private bool cacheSculptMaps = true;
  66. private string decodedScultMapPath = "j2kDecodeCache";
  67. private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
  68. private Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>();
  69. public Meshmerizer()
  70. {
  71. try
  72. {
  73. if (!Directory.Exists(decodedScultMapPath))
  74. Directory.CreateDirectory(decodedScultMapPath);
  75. }
  76. catch (Exception e)
  77. {
  78. m_log.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedScultMapPath, e.Message);
  79. }
  80. }
  81. /// <summary>
  82. /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
  83. /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
  84. /// for some reason
  85. /// </summary>
  86. /// <param name="minX"></param>
  87. /// <param name="maxX"></param>
  88. /// <param name="minY"></param>
  89. /// <param name="maxY"></param>
  90. /// <param name="minZ"></param>
  91. /// <param name="maxZ"></param>
  92. /// <returns></returns>
  93. private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
  94. {
  95. Mesh box = new Mesh();
  96. List<Vertex> vertices = new List<Vertex>();
  97. // bottom
  98. vertices.Add(new Vertex(minX, maxY, minZ));
  99. vertices.Add(new Vertex(maxX, maxY, minZ));
  100. vertices.Add(new Vertex(maxX, minY, minZ));
  101. vertices.Add(new Vertex(minX, minY, minZ));
  102. box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
  103. box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
  104. // top
  105. vertices.Add(new Vertex(maxX, maxY, maxZ));
  106. vertices.Add(new Vertex(minX, maxY, maxZ));
  107. vertices.Add(new Vertex(minX, minY, maxZ));
  108. vertices.Add(new Vertex(maxX, minY, maxZ));
  109. box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
  110. box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
  111. // sides
  112. box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
  113. box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
  114. box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
  115. box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
  116. box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
  117. box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
  118. box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
  119. box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
  120. return box;
  121. }
  122. /// <summary>
  123. /// Creates a simple bounding box mesh for a complex input mesh
  124. /// </summary>
  125. /// <param name="meshIn"></param>
  126. /// <returns></returns>
  127. private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
  128. {
  129. float minX = float.MaxValue;
  130. float maxX = float.MinValue;
  131. float minY = float.MaxValue;
  132. float maxY = float.MinValue;
  133. float minZ = float.MaxValue;
  134. float maxZ = float.MinValue;
  135. foreach (Vector3 v in meshIn.getVertexList())
  136. {
  137. if (v != null)
  138. {
  139. if (v.X < minX) minX = v.X;
  140. if (v.Y < minY) minY = v.Y;
  141. if (v.Z < minZ) minZ = v.Z;
  142. if (v.X > maxX) maxX = v.X;
  143. if (v.Y > maxY) maxY = v.Y;
  144. if (v.Z > maxZ) maxZ = v.Z;
  145. }
  146. }
  147. return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
  148. }
  149. private void ReportPrimError(string message, string primName, PrimMesh primMesh)
  150. {
  151. m_log.Error(message);
  152. m_log.Error("\nPrim Name: " + primName);
  153. m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
  154. }
  155. private ulong GetMeshKey(PrimitiveBaseShape pbs, Vector3 size, float lod)
  156. {
  157. ulong hash = 5381;
  158. hash = djb2(hash, pbs.PathCurve);
  159. hash = djb2(hash, (byte)((byte)pbs.HollowShape | (byte)pbs.ProfileShape));
  160. hash = djb2(hash, pbs.PathBegin);
  161. hash = djb2(hash, pbs.PathEnd);
  162. hash = djb2(hash, pbs.PathScaleX);
  163. hash = djb2(hash, pbs.PathScaleY);
  164. hash = djb2(hash, pbs.PathShearX);
  165. hash = djb2(hash, pbs.PathShearY);
  166. hash = djb2(hash, (byte)pbs.PathTwist);
  167. hash = djb2(hash, (byte)pbs.PathTwistBegin);
  168. hash = djb2(hash, (byte)pbs.PathRadiusOffset);
  169. hash = djb2(hash, (byte)pbs.PathTaperX);
  170. hash = djb2(hash, (byte)pbs.PathTaperY);
  171. hash = djb2(hash, pbs.PathRevolutions);
  172. hash = djb2(hash, (byte)pbs.PathSkew);
  173. hash = djb2(hash, pbs.ProfileBegin);
  174. hash = djb2(hash, pbs.ProfileEnd);
  175. hash = djb2(hash, pbs.ProfileHollow);
  176. // TODO: Separate scale out from the primitive shape data (after
  177. // scaling is supported at the physics engine level)
  178. byte[] scaleBytes = size.GetBytes();
  179. for (int i = 0; i < scaleBytes.Length; i++)
  180. hash = djb2(hash, scaleBytes[i]);
  181. // Include LOD in hash, accounting for endianness
  182. byte[] lodBytes = new byte[4];
  183. Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
  184. if (!BitConverter.IsLittleEndian)
  185. {
  186. Array.Reverse(lodBytes, 0, 4);
  187. }
  188. for (int i = 0; i < lodBytes.Length; i++)
  189. hash = djb2(hash, lodBytes[i]);
  190. // include sculpt UUID
  191. if (pbs.SculptEntry)
  192. {
  193. scaleBytes = pbs.SculptTexture.GetBytes();
  194. for (int i = 0; i < scaleBytes.Length; i++)
  195. hash = djb2(hash, scaleBytes[i]);
  196. }
  197. return hash;
  198. }
  199. private ulong djb2(ulong hash, byte c)
  200. {
  201. return ((hash << 5) + hash) + (ulong)c;
  202. }
  203. private ulong djb2(ulong hash, ushort c)
  204. {
  205. hash = ((hash << 5) + hash) + (ulong)((byte)c);
  206. return ((hash << 5) + hash) + (ulong)(c >> 8);
  207. }
  208. private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  209. {
  210. PrimMesh primMesh;
  211. PrimMesher.SculptMesh sculptMesh;
  212. List<Coord> coords;
  213. List<Face> faces;
  214. Image idata = null;
  215. string decodedSculptFileName = "";
  216. if (primShape.SculptEntry)
  217. {
  218. if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
  219. {
  220. decodedSculptFileName = System.IO.Path.Combine(decodedScultMapPath, "smap_" + primShape.SculptTexture.ToString());
  221. try
  222. {
  223. if (File.Exists(decodedSculptFileName))
  224. {
  225. idata = Image.FromFile(decodedSculptFileName);
  226. }
  227. }
  228. catch (Exception e)
  229. {
  230. m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
  231. }
  232. //if (idata != null)
  233. // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
  234. }
  235. if (idata == null)
  236. {
  237. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  238. return null;
  239. try
  240. {
  241. OpenMetaverse.Imaging.ManagedImage unusedData;
  242. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
  243. unusedData = null;
  244. //idata = CSJ2K.J2kImage.FromBytes(primShape.SculptData);
  245. if (cacheSculptMaps && idata != null)
  246. {
  247. try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
  248. catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
  249. }
  250. }
  251. catch (DllNotFoundException)
  252. {
  253. 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!");
  254. return null;
  255. }
  256. catch (IndexOutOfRangeException)
  257. {
  258. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  259. return null;
  260. }
  261. catch (Exception ex)
  262. {
  263. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  264. return null;
  265. }
  266. }
  267. PrimMesher.SculptMesh.SculptType sculptType;
  268. switch ((OpenMetaverse.SculptType)primShape.SculptType)
  269. {
  270. case OpenMetaverse.SculptType.Cylinder:
  271. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  272. break;
  273. case OpenMetaverse.SculptType.Plane:
  274. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  275. break;
  276. case OpenMetaverse.SculptType.Torus:
  277. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  278. break;
  279. case OpenMetaverse.SculptType.Sphere:
  280. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  281. break;
  282. default:
  283. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  284. break;
  285. }
  286. bool mirror = ((primShape.SculptType & 128) != 0);
  287. bool invert = ((primShape.SculptType & 64) != 0);
  288. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
  289. idata.Dispose();
  290. sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  291. sculptMesh.Scale(size.X, size.Y, size.Z);
  292. coords = sculptMesh.coords;
  293. faces = sculptMesh.faces;
  294. }
  295. else
  296. {
  297. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  298. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  299. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  300. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  301. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  302. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  303. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  304. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  305. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  306. if (profileHollow > 0.95f)
  307. profileHollow = 0.95f;
  308. int sides = 4;
  309. if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  310. sides = 3;
  311. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  312. sides = 24;
  313. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  314. { // half circle, prim is a sphere
  315. sides = 24;
  316. profileBegin = 0.5f * profileBegin + 0.5f;
  317. profileEnd = 0.5f * profileEnd + 0.5f;
  318. }
  319. int hollowSides = sides;
  320. if (primShape.HollowShape == HollowShape.Circle)
  321. hollowSides = 24;
  322. else if (primShape.HollowShape == HollowShape.Square)
  323. hollowSides = 4;
  324. else if (primShape.HollowShape == HollowShape.Triangle)
  325. hollowSides = 3;
  326. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  327. if (primMesh.errorMessage != null)
  328. if (primMesh.errorMessage.Length > 0)
  329. m_log.Error("[ERROR] " + primMesh.errorMessage);
  330. primMesh.topShearX = pathShearX;
  331. primMesh.topShearY = pathShearY;
  332. primMesh.pathCutBegin = pathBegin;
  333. primMesh.pathCutEnd = pathEnd;
  334. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  335. {
  336. primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
  337. primMesh.twistEnd = primShape.PathTwist * 18 / 10;
  338. primMesh.taperX = pathScaleX;
  339. primMesh.taperY = pathScaleY;
  340. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  341. {
  342. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  343. if (profileBegin < 0.0f) profileBegin = 0.0f;
  344. if (profileEnd > 1.0f) profileEnd = 1.0f;
  345. }
  346. #if SPAM
  347. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  348. #endif
  349. try
  350. {
  351. primMesh.ExtrudeLinear();
  352. }
  353. catch (Exception ex)
  354. {
  355. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  356. return null;
  357. }
  358. }
  359. else
  360. {
  361. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  362. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  363. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  364. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  365. primMesh.skew = 0.01f * primShape.PathSkew;
  366. primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
  367. primMesh.twistEnd = primShape.PathTwist * 36 / 10;
  368. primMesh.taperX = primShape.PathTaperX * 0.01f;
  369. primMesh.taperY = primShape.PathTaperY * 0.01f;
  370. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  371. {
  372. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  373. if (profileBegin < 0.0f) profileBegin = 0.0f;
  374. if (profileEnd > 1.0f) profileEnd = 1.0f;
  375. }
  376. #if SPAM
  377. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  378. #endif
  379. try
  380. {
  381. primMesh.ExtrudeCircular();
  382. }
  383. catch (Exception ex)
  384. {
  385. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  386. return null;
  387. }
  388. }
  389. primMesh.DumpRaw(baseDir, primName, "primMesh");
  390. primMesh.Scale(size.X, size.Y, size.Z);
  391. coords = primMesh.coords;
  392. faces = primMesh.faces;
  393. }
  394. // Remove the reference to any JPEG2000 sculpt data so it can be GCed
  395. primShape.SculptData = Utils.EmptyBytes;
  396. int numCoords = coords.Count;
  397. int numFaces = faces.Count;
  398. // Create the list of vertices
  399. List<Vertex> vertices = new List<Vertex>();
  400. for (int i = 0; i < numCoords; i++)
  401. {
  402. Coord c = coords[i];
  403. vertices.Add(new Vertex(c.X, c.Y, c.Z));
  404. }
  405. Mesh mesh = new Mesh();
  406. // Add the corresponding triangles to the mesh
  407. for (int i = 0; i < numFaces; i++)
  408. {
  409. Face f = faces[i];
  410. mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
  411. }
  412. return mesh;
  413. }
  414. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  415. {
  416. return CreateMesh(primName, primShape, size, lod, false);
  417. }
  418. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  419. {
  420. Mesh mesh = null;
  421. ulong key = 0;
  422. // If this mesh has been created already, return it instead of creating another copy
  423. // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
  424. key = GetMeshKey(primShape, size, lod);
  425. if (m_uniqueMeshes.TryGetValue(key, out mesh))
  426. return mesh;
  427. if (size.X < 0.01f) size.X = 0.01f;
  428. if (size.Y < 0.01f) size.Y = 0.01f;
  429. if (size.Z < 0.01f) size.Z = 0.01f;
  430. mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
  431. if (mesh != null)
  432. {
  433. if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
  434. {
  435. #if SPAM
  436. m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
  437. minSizeForComplexMesh.ToString() + " - creating simple bounding box");
  438. #endif
  439. mesh = CreateBoundingBoxMesh(mesh);
  440. mesh.DumpRaw(baseDir, primName, "Z extruded");
  441. }
  442. // trim the vertex and triangle lists to free up memory
  443. mesh.TrimExcess();
  444. m_uniqueMeshes.Add(key, mesh);
  445. }
  446. return mesh;
  447. }
  448. }
  449. }