Meshmerizer.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 System.Reflection;
  31. using System.IO;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Framework.Scenes;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using OpenSim.Region.PhysicsModules.SharedBase;
  36. using OpenMetaverse;
  37. using OpenMetaverse.StructuredData;
  38. using System.Drawing;
  39. using System.Drawing.Imaging;
  40. using System.IO.Compression;
  41. using PrimMesher;
  42. using log4net;
  43. using Nini.Config;
  44. using Mono.Addins;
  45. namespace OpenSim.Region.PhysicsModules.Meshing
  46. {
  47. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Meshmerizer")]
  48. public class Meshmerizer : IMesher, INonSharedRegionModule
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. private static string LogHeader = "[MESH]";
  52. // Setting baseDir to a path will enable the dumping of raw files
  53. // raw files can be imported by blender so a visual inspection of the results can be done
  54. #if SPAM
  55. const string baseDir = "rawFiles";
  56. #else
  57. private const string baseDir = null; //"rawFiles";
  58. #endif
  59. private bool m_Enabled = false;
  60. // If 'true', lots of DEBUG logging of asset parsing details
  61. private bool debugDetail = false;
  62. private bool cacheSculptMaps = true;
  63. private string decodedSculptMapPath = null;
  64. private bool useMeshiesPhysicsMesh = false;
  65. private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
  66. private List<List<Vector3>> mConvexHulls = null;
  67. private List<Vector3> mBoundingHull = null;
  68. // Mesh cache. Static so it can be shared across instances of this class
  69. private static Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>();
  70. #region INonSharedRegionModule
  71. public string Name
  72. {
  73. get { return "Meshmerizer"; }
  74. }
  75. public Type ReplaceableInterface
  76. {
  77. get { return null; }
  78. }
  79. public void Initialise(IConfigSource source)
  80. {
  81. IConfig config = source.Configs["Startup"];
  82. if (config != null)
  83. {
  84. string mesher = config.GetString("meshing", string.Empty);
  85. if (mesher == Name)
  86. {
  87. m_Enabled = true;
  88. IConfig mesh_config = source.Configs["Mesh"];
  89. decodedSculptMapPath = config.GetString("DecodedSculptMapPath", "j2kDecodeCache");
  90. cacheSculptMaps = config.GetBoolean("CacheSculptMaps", cacheSculptMaps);
  91. if (mesh_config != null)
  92. {
  93. useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
  94. debugDetail = mesh_config.GetBoolean("LogMeshDetails", debugDetail);
  95. }
  96. try
  97. {
  98. if (!Directory.Exists(decodedSculptMapPath))
  99. Directory.CreateDirectory(decodedSculptMapPath);
  100. }
  101. catch (Exception e)
  102. {
  103. m_log.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedSculptMapPath, e.Message);
  104. }
  105. }
  106. }
  107. }
  108. public void Close()
  109. {
  110. }
  111. public void AddRegion(Scene scene)
  112. {
  113. if (!m_Enabled)
  114. return;
  115. scene.RegisterModuleInterface<IMesher>(this);
  116. }
  117. public void RemoveRegion(Scene scene)
  118. {
  119. if (!m_Enabled)
  120. return;
  121. scene.UnregisterModuleInterface<IMesher>(this);
  122. }
  123. public void RegionLoaded(Scene scene)
  124. {
  125. if (!m_Enabled)
  126. return;
  127. }
  128. #endregion
  129. /// <summary>
  130. /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
  131. /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
  132. /// for some reason
  133. /// </summary>
  134. /// <param name="minX"></param>
  135. /// <param name="maxX"></param>
  136. /// <param name="minY"></param>
  137. /// <param name="maxY"></param>
  138. /// <param name="minZ"></param>
  139. /// <param name="maxZ"></param>
  140. /// <returns></returns>
  141. private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
  142. {
  143. Mesh box = new Mesh();
  144. List<Vertex> vertices = new List<Vertex>();
  145. // bottom
  146. vertices.Add(new Vertex(minX, maxY, minZ));
  147. vertices.Add(new Vertex(maxX, maxY, minZ));
  148. vertices.Add(new Vertex(maxX, minY, minZ));
  149. vertices.Add(new Vertex(minX, minY, minZ));
  150. box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
  151. box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
  152. // top
  153. vertices.Add(new Vertex(maxX, maxY, maxZ));
  154. vertices.Add(new Vertex(minX, maxY, maxZ));
  155. vertices.Add(new Vertex(minX, minY, maxZ));
  156. vertices.Add(new Vertex(maxX, minY, maxZ));
  157. box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
  158. box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
  159. // sides
  160. box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
  161. box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
  162. box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
  163. box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
  164. box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
  165. box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
  166. box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
  167. box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
  168. return box;
  169. }
  170. /// <summary>
  171. /// Creates a simple bounding box mesh for a complex input mesh
  172. /// </summary>
  173. /// <param name="meshIn"></param>
  174. /// <returns></returns>
  175. private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
  176. {
  177. float minX = float.MaxValue;
  178. float maxX = float.MinValue;
  179. float minY = float.MaxValue;
  180. float maxY = float.MinValue;
  181. float minZ = float.MaxValue;
  182. float maxZ = float.MinValue;
  183. foreach (Vector3 v in meshIn.getVertexList())
  184. {
  185. if (v.X < minX) minX = v.X;
  186. if (v.Y < minY) minY = v.Y;
  187. if (v.Z < minZ) minZ = v.Z;
  188. if (v.X > maxX) maxX = v.X;
  189. if (v.Y > maxY) maxY = v.Y;
  190. if (v.Z > maxZ) maxZ = v.Z;
  191. }
  192. return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
  193. }
  194. private void ReportPrimError(string message, string primName, PrimMesh primMesh)
  195. {
  196. m_log.Error(message);
  197. m_log.Error("\nPrim Name: " + primName);
  198. m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
  199. }
  200. /// <summary>
  201. /// Add a submesh to an existing list of coords and faces.
  202. /// </summary>
  203. /// <param name="subMeshData"></param>
  204. /// <param name="size">Size of entire object</param>
  205. /// <param name="coords"></param>
  206. /// <param name="faces"></param>
  207. private void AddSubMesh(OSDMap subMeshData, Vector3 size, List<Coord> coords, List<Face> faces)
  208. {
  209. // Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
  210. // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
  211. // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
  212. // geometry for this submesh.
  213. if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
  214. return;
  215. OpenMetaverse.Vector3 posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
  216. OpenMetaverse.Vector3 posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
  217. ushort faceIndexOffset = (ushort)coords.Count;
  218. byte[] posBytes = subMeshData["Position"].AsBinary();
  219. for (int i = 0; i < posBytes.Length; i += 6)
  220. {
  221. ushort uX = Utils.BytesToUInt16(posBytes, i);
  222. ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
  223. ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
  224. Coord c = new Coord(
  225. Utils.UInt16ToFloat(uX, posMin.X, posMax.X) * size.X,
  226. Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y) * size.Y,
  227. Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z) * size.Z);
  228. coords.Add(c);
  229. }
  230. byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
  231. for (int i = 0; i < triangleBytes.Length; i += 6)
  232. {
  233. ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
  234. ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
  235. ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
  236. Face f = new Face(v1, v2, v3);
  237. faces.Add(f);
  238. }
  239. }
  240. /// <summary>
  241. /// Create a physics mesh from data that comes with the prim. The actual data used depends on the prim type.
  242. /// </summary>
  243. /// <param name="primName"></param>
  244. /// <param name="primShape"></param>
  245. /// <param name="size"></param>
  246. /// <param name="lod"></param>
  247. /// <returns></returns>
  248. private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  249. {
  250. // m_log.DebugFormat(
  251. // "[MESH]: Creating physics proxy for {0}, shape {1}",
  252. // primName, (OpenMetaverse.SculptType)primShape.SculptType);
  253. List<Coord> coords;
  254. List<Face> faces;
  255. if (primShape.SculptEntry)
  256. {
  257. if (((OpenMetaverse.SculptType)primShape.SculptType) == SculptType.Mesh)
  258. {
  259. if (!useMeshiesPhysicsMesh)
  260. return null;
  261. if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, size, out coords, out faces))
  262. return null;
  263. }
  264. else
  265. {
  266. if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, size, lod, out coords, out faces))
  267. return null;
  268. }
  269. }
  270. else
  271. {
  272. if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, size, lod, out coords, out faces))
  273. return null;
  274. }
  275. // Remove the reference to any JPEG2000 sculpt data so it can be GCed
  276. primShape.SculptData = Utils.EmptyBytes;
  277. int numCoords = coords.Count;
  278. int numFaces = faces.Count;
  279. // Create the list of vertices
  280. List<Vertex> vertices = new List<Vertex>();
  281. for (int i = 0; i < numCoords; i++)
  282. {
  283. Coord c = coords[i];
  284. vertices.Add(new Vertex(c.X, c.Y, c.Z));
  285. }
  286. Mesh mesh = new Mesh();
  287. // Add the corresponding triangles to the mesh
  288. for (int i = 0; i < numFaces; i++)
  289. {
  290. Face f = faces[i];
  291. mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
  292. }
  293. return mesh;
  294. }
  295. /// <summary>
  296. /// Generate the co-ords and faces necessary to construct a mesh from the mesh data the accompanies a prim.
  297. /// </summary>
  298. /// <param name="primName"></param>
  299. /// <param name="primShape"></param>
  300. /// <param name="size"></param>
  301. /// <param name="coords">Coords are added to this list by the method.</param>
  302. /// <param name="faces">Faces are added to this list by the method.</param>
  303. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  304. private bool GenerateCoordsAndFacesFromPrimMeshData(
  305. string primName, PrimitiveBaseShape primShape, Vector3 size, out List<Coord> coords, out List<Face> faces)
  306. {
  307. // m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName);
  308. coords = new List<Coord>();
  309. faces = new List<Face>();
  310. OSD meshOsd = null;
  311. mConvexHulls = null;
  312. mBoundingHull = null;
  313. if (primShape.SculptData.Length <= 0)
  314. {
  315. // XXX: At the moment we can not log here since ODEPrim, for instance, ends up triggering this
  316. // method twice - once before it has loaded sculpt data from the asset service and once afterwards.
  317. // The first time will always call with unloaded SculptData if this needs to be uploaded.
  318. // m_log.ErrorFormat("[MESH]: asset data for {0} is zero length", primName);
  319. return false;
  320. }
  321. long start = 0;
  322. using (MemoryStream data = new MemoryStream(primShape.SculptData))
  323. {
  324. try
  325. {
  326. OSD osd = OSDParser.DeserializeLLSDBinary(data);
  327. if (osd is OSDMap)
  328. meshOsd = (OSDMap)osd;
  329. else
  330. {
  331. m_log.Warn("[Mesh}: unable to cast mesh asset to OSDMap");
  332. return false;
  333. }
  334. }
  335. catch (Exception e)
  336. {
  337. m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
  338. }
  339. start = data.Position;
  340. }
  341. if (meshOsd is OSDMap)
  342. {
  343. OSDMap physicsParms = null;
  344. OSDMap map = (OSDMap)meshOsd;
  345. if (map.ContainsKey("physics_shape"))
  346. {
  347. physicsParms = (OSDMap)map["physics_shape"]; // old asset format
  348. if (debugDetail) m_log.DebugFormat("{0} prim='{1}': using 'physics_shape' mesh data", LogHeader, primName);
  349. }
  350. else if (map.ContainsKey("physics_mesh"))
  351. {
  352. physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
  353. if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'physics_mesh' mesh data", LogHeader, primName);
  354. }
  355. else if (map.ContainsKey("medium_lod"))
  356. {
  357. physicsParms = (OSDMap)map["medium_lod"]; // if no physics mesh, try to fall back to medium LOD display mesh
  358. if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'medium_lod' mesh data", LogHeader, primName);
  359. }
  360. else if (map.ContainsKey("high_lod"))
  361. {
  362. physicsParms = (OSDMap)map["high_lod"]; // if all else fails, use highest LOD display mesh and hope it works :)
  363. if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'high_lod' mesh data", LogHeader, primName);
  364. }
  365. if (map.ContainsKey("physics_convex"))
  366. { // pull this out also in case physics engine can use it
  367. OSD convexBlockOsd = null;
  368. try
  369. {
  370. OSDMap convexBlock = (OSDMap)map["physics_convex"];
  371. {
  372. int convexOffset = convexBlock["offset"].AsInteger() + (int)start;
  373. int convexSize = convexBlock["size"].AsInteger();
  374. byte[] convexBytes = new byte[convexSize];
  375. System.Buffer.BlockCopy(primShape.SculptData, convexOffset, convexBytes, 0, convexSize);
  376. try
  377. {
  378. convexBlockOsd = DecompressOsd(convexBytes);
  379. }
  380. catch (Exception e)
  381. {
  382. m_log.ErrorFormat("{0} prim='{1}': exception decoding convex block: {2}", LogHeader, primName, e);
  383. //return false;
  384. }
  385. }
  386. if (convexBlockOsd != null && convexBlockOsd is OSDMap)
  387. {
  388. convexBlock = convexBlockOsd as OSDMap;
  389. if (debugDetail)
  390. {
  391. string keys = LogHeader + " keys found in convexBlock: ";
  392. foreach (KeyValuePair<string, OSD> kvp in convexBlock)
  393. keys += "'" + kvp.Key + "' ";
  394. m_log.Debug(keys);
  395. }
  396. Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f);
  397. if (convexBlock.ContainsKey("Min")) min = convexBlock["Min"].AsVector3();
  398. Vector3 max = new Vector3(0.5f, 0.5f, 0.5f);
  399. if (convexBlock.ContainsKey("Max")) max = convexBlock["Max"].AsVector3();
  400. List<Vector3> boundingHull = null;
  401. if (convexBlock.ContainsKey("BoundingVerts"))
  402. {
  403. byte[] boundingVertsBytes = convexBlock["BoundingVerts"].AsBinary();
  404. boundingHull = new List<Vector3>();
  405. for (int i = 0; i < boundingVertsBytes.Length; )
  406. {
  407. ushort uX = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2;
  408. ushort uY = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2;
  409. ushort uZ = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2;
  410. Vector3 pos = new Vector3(
  411. Utils.UInt16ToFloat(uX, min.X, max.X),
  412. Utils.UInt16ToFloat(uY, min.Y, max.Y),
  413. Utils.UInt16ToFloat(uZ, min.Z, max.Z)
  414. );
  415. boundingHull.Add(pos);
  416. }
  417. mBoundingHull = boundingHull;
  418. if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed bounding hull. nVerts={2}", LogHeader, primName, mBoundingHull.Count);
  419. }
  420. if (convexBlock.ContainsKey("HullList"))
  421. {
  422. byte[] hullList = convexBlock["HullList"].AsBinary();
  423. byte[] posBytes = convexBlock["Positions"].AsBinary();
  424. List<List<Vector3>> hulls = new List<List<Vector3>>();
  425. int posNdx = 0;
  426. foreach (byte cnt in hullList)
  427. {
  428. int count = cnt == 0 ? 256 : cnt;
  429. List<Vector3> hull = new List<Vector3>();
  430. for (int i = 0; i < count; i++)
  431. {
  432. ushort uX = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2;
  433. ushort uY = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2;
  434. ushort uZ = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2;
  435. Vector3 pos = new Vector3(
  436. Utils.UInt16ToFloat(uX, min.X, max.X),
  437. Utils.UInt16ToFloat(uY, min.Y, max.Y),
  438. Utils.UInt16ToFloat(uZ, min.Z, max.Z)
  439. );
  440. hull.Add(pos);
  441. }
  442. hulls.Add(hull);
  443. }
  444. mConvexHulls = hulls;
  445. if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed hulls. nHulls={2}", LogHeader, primName, mConvexHulls.Count);
  446. }
  447. else
  448. {
  449. if (debugDetail) m_log.DebugFormat("{0} prim='{1}' has physics_convex but no HullList", LogHeader, primName);
  450. }
  451. }
  452. }
  453. catch (Exception e)
  454. {
  455. m_log.WarnFormat("{0} exception decoding convex block: {1}", LogHeader, e);
  456. }
  457. }
  458. if (physicsParms == null)
  459. {
  460. m_log.WarnFormat("[MESH]: No recognized physics mesh found in mesh asset for {0}", primName);
  461. return false;
  462. }
  463. int physOffset = physicsParms["offset"].AsInteger() + (int)start;
  464. int physSize = physicsParms["size"].AsInteger();
  465. if (physOffset < 0 || physSize == 0)
  466. return false; // no mesh data in asset
  467. OSD decodedMeshOsd = new OSD();
  468. byte[] meshBytes = new byte[physSize];
  469. System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
  470. // byte[] decompressed = new byte[physSize * 5];
  471. try
  472. {
  473. decodedMeshOsd = DecompressOsd(meshBytes);
  474. }
  475. catch (Exception e)
  476. {
  477. m_log.ErrorFormat("{0} prim='{1}': exception decoding physical mesh: {2}", LogHeader, primName, e);
  478. return false;
  479. }
  480. OSDArray decodedMeshOsdArray = null;
  481. // physics_shape is an array of OSDMaps, one for each submesh
  482. if (decodedMeshOsd is OSDArray)
  483. {
  484. // Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));
  485. decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
  486. foreach (OSD subMeshOsd in decodedMeshOsdArray)
  487. {
  488. if (subMeshOsd is OSDMap)
  489. AddSubMesh(subMeshOsd as OSDMap, size, coords, faces);
  490. }
  491. if (debugDetail)
  492. m_log.DebugFormat("{0} {1}: mesh decoded. offset={2}, size={3}, nCoords={4}, nFaces={5}",
  493. LogHeader, primName, physOffset, physSize, coords.Count, faces.Count);
  494. }
  495. }
  496. return true;
  497. }
  498. /// <summary>
  499. /// decompresses a gzipped OSD object
  500. /// </summary>
  501. /// <param name="decodedOsd"></param> the OSD object
  502. /// <param name="meshBytes"></param>
  503. /// <returns></returns>
  504. private static OSD DecompressOsd(byte[] meshBytes)
  505. {
  506. OSD decodedOsd = null;
  507. using (MemoryStream inMs = new MemoryStream(meshBytes))
  508. {
  509. using (MemoryStream outMs = new MemoryStream())
  510. {
  511. using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
  512. {
  513. byte[] readBuffer = new byte[2048];
  514. inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header
  515. int readLen = 0;
  516. while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
  517. outMs.Write(readBuffer, 0, readLen);
  518. outMs.Flush();
  519. outMs.Seek(0, SeekOrigin.Begin);
  520. byte[] decompressedBuf = outMs.GetBuffer();
  521. decodedOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
  522. }
  523. }
  524. }
  525. return decodedOsd;
  526. }
  527. /// <summary>
  528. /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
  529. /// </summary>
  530. /// <param name="primName"></param>
  531. /// <param name="primShape"></param>
  532. /// <param name="size"></param>
  533. /// <param name="lod"></param>
  534. /// <param name="coords">Coords are added to this list by the method.</param>
  535. /// <param name="faces">Faces are added to this list by the method.</param>
  536. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  537. private bool GenerateCoordsAndFacesFromPrimSculptData(
  538. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  539. {
  540. coords = new List<Coord>();
  541. faces = new List<Face>();
  542. PrimMesher.SculptMesh sculptMesh;
  543. Image idata = null;
  544. string decodedSculptFileName = "";
  545. if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero)
  546. {
  547. decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture.ToString());
  548. try
  549. {
  550. if (File.Exists(decodedSculptFileName))
  551. {
  552. idata = Image.FromFile(decodedSculptFileName);
  553. }
  554. }
  555. catch (Exception e)
  556. {
  557. m_log.Error("[SCULPT]: unable to load cached sculpt map " + decodedSculptFileName + " " + e.Message);
  558. }
  559. //if (idata != null)
  560. // m_log.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString());
  561. }
  562. if (idata == null)
  563. {
  564. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  565. return false;
  566. try
  567. {
  568. OpenMetaverse.Imaging.ManagedImage managedImage;
  569. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out managedImage);
  570. if (managedImage == null)
  571. {
  572. // In some cases it seems that the decode can return a null bitmap without throwing
  573. // an exception
  574. m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
  575. return false;
  576. }
  577. if ((managedImage.Channels & OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha) != 0)
  578. managedImage.ConvertChannels(managedImage.Channels & ~OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha);
  579. Bitmap imgData = OpenMetaverse.Imaging.LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA()));
  580. idata = (Image)imgData;
  581. managedImage = null;
  582. if (cacheSculptMaps)
  583. {
  584. try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); }
  585. catch (Exception e) { m_log.Error("[SCULPT]: unable to cache sculpt map " + decodedSculptFileName + " " + e.Message); }
  586. }
  587. }
  588. catch (DllNotFoundException)
  589. {
  590. 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!");
  591. return false;
  592. }
  593. catch (IndexOutOfRangeException)
  594. {
  595. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  596. return false;
  597. }
  598. catch (Exception ex)
  599. {
  600. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  601. return false;
  602. }
  603. }
  604. PrimMesher.SculptMesh.SculptType sculptType;
  605. switch ((OpenMetaverse.SculptType)primShape.SculptType)
  606. {
  607. case OpenMetaverse.SculptType.Cylinder:
  608. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  609. break;
  610. case OpenMetaverse.SculptType.Plane:
  611. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  612. break;
  613. case OpenMetaverse.SculptType.Torus:
  614. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  615. break;
  616. case OpenMetaverse.SculptType.Sphere:
  617. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  618. break;
  619. default:
  620. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  621. break;
  622. }
  623. bool mirror = ((primShape.SculptType & 128) != 0);
  624. bool invert = ((primShape.SculptType & 64) != 0);
  625. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert);
  626. idata.Dispose();
  627. sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  628. sculptMesh.Scale(size.X, size.Y, size.Z);
  629. coords = sculptMesh.coords;
  630. faces = sculptMesh.faces;
  631. return true;
  632. }
  633. /// <summary>
  634. /// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
  635. /// </summary>
  636. /// <param name="primName"></param>
  637. /// <param name="primShape"></param>
  638. /// <param name="size"></param>
  639. /// <param name="coords">Coords are added to this list by the method.</param>
  640. /// <param name="faces">Faces are added to this list by the method.</param>
  641. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  642. private bool GenerateCoordsAndFacesFromPrimShapeData(
  643. string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, out List<Coord> coords, out List<Face> faces)
  644. {
  645. PrimMesh primMesh;
  646. coords = new List<Coord>();
  647. faces = new List<Face>();
  648. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  649. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  650. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  651. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  652. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  653. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  654. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  655. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  656. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  657. if (profileHollow > 0.95f)
  658. profileHollow = 0.95f;
  659. int sides = 4;
  660. LevelOfDetail iLOD = (LevelOfDetail)lod;
  661. if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
  662. sides = 3;
  663. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
  664. {
  665. switch (iLOD)
  666. {
  667. case LevelOfDetail.High: sides = 24; break;
  668. case LevelOfDetail.Medium: sides = 12; break;
  669. case LevelOfDetail.Low: sides = 6; break;
  670. case LevelOfDetail.VeryLow: sides = 3; break;
  671. default: sides = 24; break;
  672. }
  673. }
  674. else if ((primShape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
  675. { // half circle, prim is a sphere
  676. switch (iLOD)
  677. {
  678. case LevelOfDetail.High: sides = 24; break;
  679. case LevelOfDetail.Medium: sides = 12; break;
  680. case LevelOfDetail.Low: sides = 6; break;
  681. case LevelOfDetail.VeryLow: sides = 3; break;
  682. default: sides = 24; break;
  683. }
  684. profileBegin = 0.5f * profileBegin + 0.5f;
  685. profileEnd = 0.5f * profileEnd + 0.5f;
  686. }
  687. int hollowSides = sides;
  688. if (primShape.HollowShape == HollowShape.Circle)
  689. {
  690. switch (iLOD)
  691. {
  692. case LevelOfDetail.High: hollowSides = 24; break;
  693. case LevelOfDetail.Medium: hollowSides = 12; break;
  694. case LevelOfDetail.Low: hollowSides = 6; break;
  695. case LevelOfDetail.VeryLow: hollowSides = 3; break;
  696. default: hollowSides = 24; break;
  697. }
  698. }
  699. else if (primShape.HollowShape == HollowShape.Square)
  700. hollowSides = 4;
  701. else if (primShape.HollowShape == HollowShape.Triangle)
  702. hollowSides = 3;
  703. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  704. if (primMesh.errorMessage != null)
  705. if (primMesh.errorMessage.Length > 0)
  706. m_log.Error("[ERROR] " + primMesh.errorMessage);
  707. primMesh.topShearX = pathShearX;
  708. primMesh.topShearY = pathShearY;
  709. primMesh.pathCutBegin = pathBegin;
  710. primMesh.pathCutEnd = pathEnd;
  711. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  712. {
  713. primMesh.twistBegin = primShape.PathTwistBegin * 18 / 10;
  714. primMesh.twistEnd = primShape.PathTwist * 18 / 10;
  715. primMesh.taperX = pathScaleX;
  716. primMesh.taperY = pathScaleY;
  717. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  718. {
  719. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  720. if (profileBegin < 0.0f) profileBegin = 0.0f;
  721. if (profileEnd > 1.0f) profileEnd = 1.0f;
  722. }
  723. #if SPAM
  724. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  725. #endif
  726. try
  727. {
  728. primMesh.ExtrudeLinear();
  729. }
  730. catch (Exception ex)
  731. {
  732. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  733. return false;
  734. }
  735. }
  736. else
  737. {
  738. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  739. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  740. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  741. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  742. primMesh.skew = 0.01f * primShape.PathSkew;
  743. primMesh.twistBegin = primShape.PathTwistBegin * 36 / 10;
  744. primMesh.twistEnd = primShape.PathTwist * 36 / 10;
  745. primMesh.taperX = primShape.PathTaperX * 0.01f;
  746. primMesh.taperY = primShape.PathTaperY * 0.01f;
  747. if (profileBegin < 0.0f || profileBegin >= profileEnd || profileEnd > 1.0f)
  748. {
  749. ReportPrimError("*** CORRUPT PRIM!! ***", primName, primMesh);
  750. if (profileBegin < 0.0f) profileBegin = 0.0f;
  751. if (profileEnd > 1.0f) profileEnd = 1.0f;
  752. }
  753. #if SPAM
  754. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  755. #endif
  756. try
  757. {
  758. primMesh.ExtrudeCircular();
  759. }
  760. catch (Exception ex)
  761. {
  762. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  763. return false;
  764. }
  765. }
  766. primMesh.DumpRaw(baseDir, primName, "primMesh");
  767. primMesh.Scale(size.X, size.Y, size.Z);
  768. coords = primMesh.coords;
  769. faces = primMesh.faces;
  770. return true;
  771. }
  772. /// <summary>
  773. /// temporary prototype code - please do not use until the interface has been finalized!
  774. /// </summary>
  775. /// <param name="size">value to scale the hull points by</param>
  776. /// <returns>a list of vertices in the bounding hull if it exists and has been successfully decoded, otherwise null</returns>
  777. public List<Vector3> GetBoundingHull(Vector3 size)
  778. {
  779. if (mBoundingHull == null)
  780. return null;
  781. List<Vector3> verts = new List<Vector3>();
  782. foreach (var vert in mBoundingHull)
  783. verts.Add(vert * size);
  784. return verts;
  785. }
  786. /// <summary>
  787. /// temporary prototype code - please do not use until the interface has been finalized!
  788. /// </summary>
  789. /// <param name="size">value to scale the hull points by</param>
  790. /// <returns>a list of hulls if they exist and have been successfully decoded, otherwise null</returns>
  791. public List<List<Vector3>> GetConvexHulls(Vector3 size)
  792. {
  793. if (mConvexHulls == null)
  794. return null;
  795. List<List<Vector3>> hulls = new List<List<Vector3>>();
  796. foreach (var hull in mConvexHulls)
  797. {
  798. List<Vector3> verts = new List<Vector3>();
  799. foreach (var vert in hull)
  800. verts.Add(vert * size);
  801. hulls.Add(verts);
  802. }
  803. return hulls;
  804. }
  805. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  806. {
  807. return CreateMesh(primName, primShape, size, lod, false, true);
  808. }
  809. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  810. {
  811. return CreateMesh(primName, primShape, size, lod, isPhysical, true);
  812. }
  813. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache)
  814. {
  815. #if SPAM
  816. m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
  817. #endif
  818. Mesh mesh = null;
  819. ulong key = 0;
  820. // If this mesh has been created already, return it instead of creating another copy
  821. // For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
  822. if (shouldCache)
  823. {
  824. key = primShape.GetMeshKey(size, lod);
  825. lock (m_uniqueMeshes)
  826. {
  827. if (m_uniqueMeshes.TryGetValue(key, out mesh))
  828. return mesh;
  829. }
  830. }
  831. if (size.X < 0.01f) size.X = 0.01f;
  832. if (size.Y < 0.01f) size.Y = 0.01f;
  833. if (size.Z < 0.01f) size.Z = 0.01f;
  834. mesh = CreateMeshFromPrimMesher(primName, primShape, size, lod);
  835. if (mesh != null)
  836. {
  837. if ((!isPhysical) && size.X < minSizeForComplexMesh && size.Y < minSizeForComplexMesh && size.Z < minSizeForComplexMesh)
  838. {
  839. #if SPAM
  840. m_log.Debug("Meshmerizer: prim " + primName + " has a size of " + size.ToString() + " which is below threshold of " +
  841. minSizeForComplexMesh.ToString() + " - creating simple bounding box");
  842. #endif
  843. mesh = CreateBoundingBoxMesh(mesh);
  844. mesh.DumpRaw(baseDir, primName, "Z extruded");
  845. }
  846. // trim the vertex and triangle lists to free up memory
  847. mesh.TrimExcess();
  848. if (shouldCache)
  849. {
  850. lock (m_uniqueMeshes)
  851. {
  852. m_uniqueMeshes.Add(key, mesh);
  853. }
  854. }
  855. }
  856. return mesh;
  857. }
  858. }
  859. }