Meshmerizer.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  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.Framework.Scenes;
  32. using OpenSim.Region.Framework.Interfaces;
  33. using OpenSim.Region.PhysicsModules.SharedBase;
  34. using OpenSim.Region.PhysicsModules.ConvexDecompositionDotNet;
  35. using OpenMetaverse;
  36. using OpenMetaverse.StructuredData;
  37. using System.Drawing;
  38. using System.Drawing.Imaging;
  39. using System.IO.Compression;
  40. using PrimMesher;
  41. using log4net;
  42. using Nini.Config;
  43. using System.Reflection;
  44. using System.IO;
  45. using System.Runtime.Serialization;
  46. using System.Runtime.Serialization.Formatters.Binary;
  47. using Mono.Addins;
  48. namespace OpenSim.Region.PhysicsModule.ubODEMeshing
  49. {
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ubODEMeshmerizer")]
  51. public class ubMeshmerizer : IMesher, INonSharedRegionModule
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. // Setting baseDir to a path will enable the dumping of raw files
  55. // raw files can be imported by blender so a visual inspection of the results can be done
  56. private bool m_Enabled = false;
  57. public static object diskLock = new object();
  58. public bool doMeshFileCache = true;
  59. public string cachePath = "MeshCache";
  60. public TimeSpan CacheExpire;
  61. public bool doCacheExpire = true;
  62. // const string baseDir = "rawFiles";
  63. private const string baseDir = null; //"rawFiles";
  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 Dictionary<AMeshKey, Mesh> m_uniqueMeshes = new Dictionary<AMeshKey, Mesh>();
  67. private Dictionary<AMeshKey, Mesh> m_uniqueReleasedMeshes = new Dictionary<AMeshKey, Mesh>();
  68. #region INonSharedRegionModule
  69. public string Name
  70. {
  71. get { return "ubODEMeshmerizer"; }
  72. }
  73. public Type ReplaceableInterface
  74. {
  75. get { return null; }
  76. }
  77. public void Initialise(IConfigSource config)
  78. {
  79. IConfig start_config = config.Configs["Startup"];
  80. string mesher = start_config.GetString("meshing", string.Empty);
  81. if (mesher == Name)
  82. {
  83. float fcache = 48.0f;
  84. // float fcache = 0.02f;
  85. IConfig mesh_config = config.Configs["Mesh"];
  86. if (mesh_config != null)
  87. {
  88. useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh);
  89. if (useMeshiesPhysicsMesh)
  90. {
  91. doMeshFileCache = mesh_config.GetBoolean("MeshFileCache", doMeshFileCache);
  92. cachePath = mesh_config.GetString("MeshFileCachePath", cachePath);
  93. fcache = mesh_config.GetFloat("MeshFileCacheExpireHours", fcache);
  94. doCacheExpire = mesh_config.GetBoolean("MeshFileCacheDoExpire", doCacheExpire);
  95. }
  96. else
  97. {
  98. doMeshFileCache = false;
  99. doCacheExpire = false;
  100. }
  101. m_Enabled = true;
  102. }
  103. CacheExpire = TimeSpan.FromHours(fcache);
  104. lock (diskLock)
  105. {
  106. if(doMeshFileCache && cachePath != "")
  107. {
  108. try
  109. {
  110. if (!Directory.Exists(cachePath))
  111. Directory.CreateDirectory(cachePath);
  112. }
  113. catch
  114. {
  115. doMeshFileCache = false;
  116. doCacheExpire = false;
  117. }
  118. }
  119. }
  120. }
  121. }
  122. public void Close()
  123. {
  124. }
  125. public void AddRegion(Scene scene)
  126. {
  127. if (!m_Enabled)
  128. return;
  129. scene.RegisterModuleInterface<IMesher>(this);
  130. }
  131. public void RemoveRegion(Scene scene)
  132. {
  133. if (!m_Enabled)
  134. return;
  135. scene.UnregisterModuleInterface<IMesher>(this);
  136. }
  137. public void RegionLoaded(Scene scene)
  138. {
  139. if (!m_Enabled)
  140. return;
  141. }
  142. #endregion
  143. /// <summary>
  144. /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
  145. /// be useful as a backup proxy when level of detail is not needed or when more complex meshes fail
  146. /// for some reason
  147. /// </summary>
  148. /// <param name="minX"></param>
  149. /// <param name="maxX"></param>
  150. /// <param name="minY"></param>
  151. /// <param name="maxY"></param>
  152. /// <param name="minZ"></param>
  153. /// <param name="maxZ"></param>
  154. /// <returns></returns>
  155. private static Mesh CreateSimpleBoxMesh(float minX, float maxX, float minY, float maxY, float minZ, float maxZ)
  156. {
  157. Mesh box = new Mesh();
  158. List<Vertex> vertices = new List<Vertex>();
  159. // bottom
  160. vertices.Add(new Vertex(minX, maxY, minZ));
  161. vertices.Add(new Vertex(maxX, maxY, minZ));
  162. vertices.Add(new Vertex(maxX, minY, minZ));
  163. vertices.Add(new Vertex(minX, minY, minZ));
  164. box.Add(new Triangle(vertices[0], vertices[1], vertices[2]));
  165. box.Add(new Triangle(vertices[0], vertices[2], vertices[3]));
  166. // top
  167. vertices.Add(new Vertex(maxX, maxY, maxZ));
  168. vertices.Add(new Vertex(minX, maxY, maxZ));
  169. vertices.Add(new Vertex(minX, minY, maxZ));
  170. vertices.Add(new Vertex(maxX, minY, maxZ));
  171. box.Add(new Triangle(vertices[4], vertices[5], vertices[6]));
  172. box.Add(new Triangle(vertices[4], vertices[6], vertices[7]));
  173. // sides
  174. box.Add(new Triangle(vertices[5], vertices[0], vertices[3]));
  175. box.Add(new Triangle(vertices[5], vertices[3], vertices[6]));
  176. box.Add(new Triangle(vertices[1], vertices[0], vertices[5]));
  177. box.Add(new Triangle(vertices[1], vertices[5], vertices[4]));
  178. box.Add(new Triangle(vertices[7], vertices[1], vertices[4]));
  179. box.Add(new Triangle(vertices[7], vertices[2], vertices[1]));
  180. box.Add(new Triangle(vertices[3], vertices[2], vertices[7]));
  181. box.Add(new Triangle(vertices[3], vertices[7], vertices[6]));
  182. return box;
  183. }
  184. /// <summary>
  185. /// Creates a simple bounding box mesh for a complex input mesh
  186. /// </summary>
  187. /// <param name="meshIn"></param>
  188. /// <returns></returns>
  189. private static Mesh CreateBoundingBoxMesh(Mesh meshIn)
  190. {
  191. float minX = float.MaxValue;
  192. float maxX = float.MinValue;
  193. float minY = float.MaxValue;
  194. float maxY = float.MinValue;
  195. float minZ = float.MaxValue;
  196. float maxZ = float.MinValue;
  197. foreach (Vector3 v in meshIn.getVertexList())
  198. {
  199. if (v.X < minX) minX = v.X;
  200. if (v.Y < minY) minY = v.Y;
  201. if (v.Z < minZ) minZ = v.Z;
  202. if (v.X > maxX) maxX = v.X;
  203. if (v.Y > maxY) maxY = v.Y;
  204. if (v.Z > maxZ) maxZ = v.Z;
  205. }
  206. return CreateSimpleBoxMesh(minX, maxX, minY, maxY, minZ, maxZ);
  207. }
  208. private void ReportPrimError(string message, string primName, PrimMesh primMesh)
  209. {
  210. m_log.Error(message);
  211. m_log.Error("\nPrim Name: " + primName);
  212. m_log.Error("****** PrimMesh Parameters ******\n" + primMesh.ParamsToDisplayString());
  213. }
  214. /// <summary>
  215. /// Add a submesh to an existing list of coords and faces.
  216. /// </summary>
  217. /// <param name="subMeshData"></param>
  218. /// <param name="size">Size of entire object</param>
  219. /// <param name="coords"></param>
  220. /// <param name="faces"></param>
  221. private void AddSubMesh(OSDMap subMeshData, List<Coord> coords, List<Face> faces)
  222. {
  223. // Console.WriteLine("subMeshMap for {0} - {1}", primName, Util.GetFormattedXml((OSD)subMeshMap));
  224. // As per http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format, some Mesh Level
  225. // of Detail Blocks (maps) contain just a NoGeometry key to signal there is no
  226. // geometry for this submesh.
  227. if (subMeshData.ContainsKey("NoGeometry") && ((OSDBoolean)subMeshData["NoGeometry"]))
  228. return;
  229. OpenMetaverse.Vector3 posMax;
  230. OpenMetaverse.Vector3 posMin;
  231. if (subMeshData.ContainsKey("PositionDomain"))
  232. {
  233. posMax = ((OSDMap)subMeshData["PositionDomain"])["Max"].AsVector3();
  234. posMin = ((OSDMap)subMeshData["PositionDomain"])["Min"].AsVector3();
  235. }
  236. else
  237. {
  238. posMax = new Vector3(0.5f, 0.5f, 0.5f);
  239. posMin = new Vector3(-0.5f, -0.5f, -0.5f);
  240. }
  241. ushort faceIndexOffset = (ushort)coords.Count;
  242. byte[] posBytes = subMeshData["Position"].AsBinary();
  243. for (int i = 0; i < posBytes.Length; i += 6)
  244. {
  245. ushort uX = Utils.BytesToUInt16(posBytes, i);
  246. ushort uY = Utils.BytesToUInt16(posBytes, i + 2);
  247. ushort uZ = Utils.BytesToUInt16(posBytes, i + 4);
  248. Coord c = new Coord(
  249. Utils.UInt16ToFloat(uX, posMin.X, posMax.X),
  250. Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y),
  251. Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z));
  252. coords.Add(c);
  253. }
  254. byte[] triangleBytes = subMeshData["TriangleList"].AsBinary();
  255. for (int i = 0; i < triangleBytes.Length; i += 6)
  256. {
  257. ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i) + faceIndexOffset);
  258. ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2) + faceIndexOffset);
  259. ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4) + faceIndexOffset);
  260. Face f = new Face(v1, v2, v3);
  261. faces.Add(f);
  262. }
  263. }
  264. /// <summary>
  265. /// Create a physics mesh from data that comes with the prim. The actual data used depends on the prim type.
  266. /// </summary>
  267. /// <param name="primName"></param>
  268. /// <param name="primShape"></param>
  269. /// <param name="size"></param>
  270. /// <param name="lod"></param>
  271. /// <returns></returns>
  272. private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, float lod, bool convex)
  273. {
  274. // m_log.DebugFormat(
  275. // "[MESH]: Creating physics proxy for {0}, shape {1}",
  276. // primName, (OpenMetaverse.SculptType)primShape.SculptType);
  277. List<Coord> coords;
  278. List<Face> faces;
  279. if (primShape.SculptEntry)
  280. {
  281. if (((OpenMetaverse.SculptType)primShape.SculptType) == SculptType.Mesh)
  282. {
  283. if (!useMeshiesPhysicsMesh)
  284. return null;
  285. if (!GenerateCoordsAndFacesFromPrimMeshData(primName, primShape, out coords, out faces, convex))
  286. return null;
  287. }
  288. else
  289. {
  290. if (!GenerateCoordsAndFacesFromPrimSculptData(primName, primShape, lod, out coords, out faces))
  291. return null;
  292. }
  293. }
  294. else
  295. {
  296. if (!GenerateCoordsAndFacesFromPrimShapeData(primName, primShape, lod, out coords, out faces))
  297. return null;
  298. }
  299. int numCoords = coords.Count;
  300. int numFaces = faces.Count;
  301. Mesh mesh = new Mesh();
  302. // Add the corresponding triangles to the mesh
  303. for (int i = 0; i < numFaces; i++)
  304. {
  305. Face f = faces[i];
  306. mesh.Add(new Triangle(coords[f.v1].X, coords[f.v1].Y, coords[f.v1].Z,
  307. coords[f.v2].X, coords[f.v2].Y, coords[f.v2].Z,
  308. coords[f.v3].X, coords[f.v3].Y, coords[f.v3].Z));
  309. }
  310. coords.Clear();
  311. faces.Clear();
  312. if(mesh.numberVertices() < 3 || mesh.numberTriangles() < 1)
  313. {
  314. m_log.ErrorFormat("[MESH]: invalid degenerated mesh for prim " + primName + " ignored");
  315. return null;
  316. }
  317. primShape.SculptData = Utils.EmptyBytes;
  318. return mesh;
  319. }
  320. /// <summary>
  321. /// Generate the co-ords and faces necessary to construct a mesh from the mesh data the accompanies a prim.
  322. /// </summary>
  323. /// <param name="primName"></param>
  324. /// <param name="primShape"></param>
  325. /// <param name="size"></param>
  326. /// <param name="coords">Coords are added to this list by the method.</param>
  327. /// <param name="faces">Faces are added to this list by the method.</param>
  328. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  329. private bool GenerateCoordsAndFacesFromPrimMeshData(
  330. string primName, PrimitiveBaseShape primShape, out List<Coord> coords, out List<Face> faces, bool convex)
  331. {
  332. // m_log.DebugFormat("[MESH]: experimental mesh proxy generation for {0}", primName);
  333. bool usemesh = false;
  334. coords = new List<Coord>();
  335. faces = new List<Face>();
  336. OSD meshOsd = null;
  337. if (primShape.SculptData.Length <= 0)
  338. {
  339. // m_log.InfoFormat("[MESH]: asset data for {0} is zero length", primName);
  340. return false;
  341. }
  342. long start = 0;
  343. using (MemoryStream data = new MemoryStream(primShape.SculptData))
  344. {
  345. try
  346. {
  347. OSD osd = OSDParser.DeserializeLLSDBinary(data);
  348. if (osd is OSDMap)
  349. meshOsd = (OSDMap)osd;
  350. else
  351. {
  352. m_log.WarnFormat("[Mesh}: unable to cast mesh asset to OSDMap prim: {0}",primName);
  353. return false;
  354. }
  355. }
  356. catch (Exception e)
  357. {
  358. m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
  359. }
  360. start = data.Position;
  361. }
  362. if (meshOsd is OSDMap)
  363. {
  364. OSDMap physicsParms = null;
  365. OSDMap map = (OSDMap)meshOsd;
  366. if (!convex)
  367. {
  368. if (map.ContainsKey("physics_shape"))
  369. physicsParms = (OSDMap)map["physics_shape"]; // old asset format
  370. else if (map.ContainsKey("physics_mesh"))
  371. physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
  372. if (physicsParms != null)
  373. usemesh = true;
  374. }
  375. if(!usemesh && (map.ContainsKey("physics_convex")))
  376. physicsParms = (OSDMap)map["physics_convex"];
  377. if (physicsParms == null)
  378. {
  379. m_log.WarnFormat("[MESH]: unknown mesh type for {0}",primName);
  380. return false;
  381. }
  382. int physOffset = physicsParms["offset"].AsInteger() + (int)start;
  383. int physSize = physicsParms["size"].AsInteger();
  384. if (physOffset < 0 || physSize == 0)
  385. return false; // no mesh data in asset
  386. OSD decodedMeshOsd = new OSD();
  387. byte[] meshBytes = new byte[physSize];
  388. System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
  389. try
  390. {
  391. using (MemoryStream inMs = new MemoryStream(meshBytes))
  392. {
  393. using (MemoryStream outMs = new MemoryStream())
  394. {
  395. using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
  396. {
  397. byte[] readBuffer = new byte[2048];
  398. inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header
  399. int readLen = 0;
  400. while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
  401. outMs.Write(readBuffer, 0, readLen);
  402. outMs.Flush();
  403. outMs.Seek(0, SeekOrigin.Begin);
  404. byte[] decompressedBuf = outMs.GetBuffer();
  405. decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
  406. }
  407. }
  408. }
  409. }
  410. catch (Exception e)
  411. {
  412. m_log.Error("[MESH]: exception decoding physical mesh prim " + primName +" : " + e.ToString());
  413. return false;
  414. }
  415. if (usemesh)
  416. {
  417. OSDArray decodedMeshOsdArray = null;
  418. // physics_shape is an array of OSDMaps, one for each submesh
  419. if (decodedMeshOsd is OSDArray)
  420. {
  421. // Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));
  422. decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
  423. foreach (OSD subMeshOsd in decodedMeshOsdArray)
  424. {
  425. if (subMeshOsd is OSDMap)
  426. AddSubMesh(subMeshOsd as OSDMap, coords, faces);
  427. }
  428. }
  429. }
  430. else
  431. {
  432. OSDMap cmap = (OSDMap)decodedMeshOsd;
  433. if (cmap == null)
  434. return false;
  435. byte[] data;
  436. List<float3> vs = new List<float3>();
  437. PHullResult hullr = new PHullResult();
  438. float3 f3;
  439. Coord c;
  440. Face f;
  441. Vector3 range;
  442. Vector3 min;
  443. const float invMaxU16 = 1.0f / 65535f;
  444. int t1;
  445. int t2;
  446. int t3;
  447. int i;
  448. int nverts;
  449. int nindexs;
  450. if (cmap.ContainsKey("Max"))
  451. range = cmap["Max"].AsVector3();
  452. else
  453. range = new Vector3(0.5f, 0.5f, 0.5f);
  454. if (cmap.ContainsKey("Min"))
  455. min = cmap["Min"].AsVector3();
  456. else
  457. min = new Vector3(-0.5f, -0.5f, -0.5f);
  458. range = range - min;
  459. range *= invMaxU16;
  460. if (!convex && cmap.ContainsKey("HullList") && cmap.ContainsKey("Positions"))
  461. {
  462. List<int> hsizes = new List<int>();
  463. int totalpoints = 0;
  464. data = cmap["HullList"].AsBinary();
  465. for (i = 0; i < data.Length; i++)
  466. {
  467. t1 = data[i];
  468. if (t1 == 0)
  469. t1 = 256;
  470. totalpoints += t1;
  471. hsizes.Add(t1);
  472. }
  473. data = cmap["Positions"].AsBinary();
  474. int ptr = 0;
  475. int vertsoffset = 0;
  476. if (totalpoints == data.Length / 6) // 2 bytes per coord, 3 coords per point
  477. {
  478. foreach (int hullsize in hsizes)
  479. {
  480. for (i = 0; i < hullsize; i++ )
  481. {
  482. t1 = data[ptr++];
  483. t1 += data[ptr++] << 8;
  484. t2 = data[ptr++];
  485. t2 += data[ptr++] << 8;
  486. t3 = data[ptr++];
  487. t3 += data[ptr++] << 8;
  488. f3 = new float3((t1 * range.X + min.X),
  489. (t2 * range.Y + min.Y),
  490. (t3 * range.Z + min.Z));
  491. vs.Add(f3);
  492. }
  493. if(hullsize <3)
  494. {
  495. vs.Clear();
  496. continue;
  497. }
  498. if (hullsize <5)
  499. {
  500. foreach (float3 point in vs)
  501. {
  502. c.X = point.x;
  503. c.Y = point.y;
  504. c.Z = point.z;
  505. coords.Add(c);
  506. }
  507. f = new Face(vertsoffset, vertsoffset + 1, vertsoffset + 2);
  508. faces.Add(f);
  509. if (hullsize == 4)
  510. {
  511. // not sure about orientation..
  512. f = new Face(vertsoffset, vertsoffset + 2, vertsoffset + 3);
  513. faces.Add(f);
  514. f = new Face(vertsoffset, vertsoffset + 3, vertsoffset + 1);
  515. faces.Add(f);
  516. f = new Face(vertsoffset + 3, vertsoffset + 2, vertsoffset + 1);
  517. faces.Add(f);
  518. }
  519. vertsoffset += vs.Count;
  520. vs.Clear();
  521. continue;
  522. }
  523. /*
  524. if (!HullUtils.ComputeHull(vs, ref hullr, 0, 0.0f))
  525. {
  526. vs.Clear();
  527. continue;
  528. }
  529. nverts = hullr.Vertices.Count;
  530. nindexs = hullr.Indices.Count;
  531. if (nindexs % 3 != 0)
  532. {
  533. vs.Clear();
  534. continue;
  535. }
  536. for (i = 0; i < nverts; i++)
  537. {
  538. c.X = hullr.Vertices[i].x;
  539. c.Y = hullr.Vertices[i].y;
  540. c.Z = hullr.Vertices[i].z;
  541. coords.Add(c);
  542. }
  543. for (i = 0; i < nindexs; i += 3)
  544. {
  545. t1 = hullr.Indices[i];
  546. if (t1 > nverts)
  547. break;
  548. t2 = hullr.Indices[i + 1];
  549. if (t2 > nverts)
  550. break;
  551. t3 = hullr.Indices[i + 2];
  552. if (t3 > nverts)
  553. break;
  554. f = new Face(vertsoffset + t1, vertsoffset + t2, vertsoffset + t3);
  555. faces.Add(f);
  556. }
  557. */
  558. List<int> indices;
  559. if (!HullUtils.ComputeHull(vs, out indices))
  560. {
  561. vs.Clear();
  562. continue;
  563. }
  564. nverts = vs.Count;
  565. nindexs = indices.Count;
  566. if (nindexs % 3 != 0)
  567. {
  568. vs.Clear();
  569. continue;
  570. }
  571. for (i = 0; i < nverts; i++)
  572. {
  573. c.X = vs[i].x;
  574. c.Y = vs[i].y;
  575. c.Z = vs[i].z;
  576. coords.Add(c);
  577. }
  578. for (i = 0; i < nindexs; i += 3)
  579. {
  580. t1 = indices[i];
  581. if (t1 > nverts)
  582. break;
  583. t2 = indices[i + 1];
  584. if (t2 > nverts)
  585. break;
  586. t3 = indices[i + 2];
  587. if (t3 > nverts)
  588. break;
  589. f = new Face(vertsoffset + t1, vertsoffset + t2, vertsoffset + t3);
  590. faces.Add(f);
  591. }
  592. vertsoffset += nverts;
  593. vs.Clear();
  594. }
  595. }
  596. if (coords.Count > 0 && faces.Count > 0)
  597. return true;
  598. }
  599. vs.Clear();
  600. if (cmap.ContainsKey("BoundingVerts"))
  601. {
  602. data = cmap["BoundingVerts"].AsBinary();
  603. for (i = 0; i < data.Length; )
  604. {
  605. t1 = data[i++];
  606. t1 += data[i++] << 8;
  607. t2 = data[i++];
  608. t2 += data[i++] << 8;
  609. t3 = data[i++];
  610. t3 += data[i++] << 8;
  611. f3 = new float3((t1 * range.X + min.X),
  612. (t2 * range.Y + min.Y),
  613. (t3 * range.Z + min.Z));
  614. vs.Add(f3);
  615. }
  616. nverts = vs.Count;
  617. if (nverts < 3)
  618. {
  619. vs.Clear();
  620. return false;
  621. }
  622. if (nverts < 5)
  623. {
  624. foreach (float3 point in vs)
  625. {
  626. c.X = point.x;
  627. c.Y = point.y;
  628. c.Z = point.z;
  629. coords.Add(c);
  630. }
  631. f = new Face(0, 1, 2);
  632. faces.Add(f);
  633. if (nverts == 4)
  634. {
  635. f = new Face(0, 2, 3);
  636. faces.Add(f);
  637. f = new Face(0, 3, 1);
  638. faces.Add(f);
  639. f = new Face( 3, 2, 1);
  640. faces.Add(f);
  641. }
  642. vs.Clear();
  643. return true;
  644. }
  645. /*
  646. if (!HullUtils.ComputeHull(vs, ref hullr, 0, 0.0f))
  647. return false;
  648. nverts = hullr.Vertices.Count;
  649. nindexs = hullr.Indices.Count;
  650. if (nindexs % 3 != 0)
  651. return false;
  652. for (i = 0; i < nverts; i++)
  653. {
  654. c.X = hullr.Vertices[i].x;
  655. c.Y = hullr.Vertices[i].y;
  656. c.Z = hullr.Vertices[i].z;
  657. coords.Add(c);
  658. }
  659. for (i = 0; i < nindexs; i += 3)
  660. {
  661. t1 = hullr.Indices[i];
  662. if (t1 > nverts)
  663. break;
  664. t2 = hullr.Indices[i + 1];
  665. if (t2 > nverts)
  666. break;
  667. t3 = hullr.Indices[i + 2];
  668. if (t3 > nverts)
  669. break;
  670. f = new Face(t1, t2, t3);
  671. faces.Add(f);
  672. }
  673. */
  674. List<int> indices;
  675. if (!HullUtils.ComputeHull(vs, out indices))
  676. return false;
  677. nindexs = indices.Count;
  678. if (nindexs % 3 != 0)
  679. return false;
  680. for (i = 0; i < nverts; i++)
  681. {
  682. c.X = vs[i].x;
  683. c.Y = vs[i].y;
  684. c.Z = vs[i].z;
  685. coords.Add(c);
  686. }
  687. for (i = 0; i < nindexs; i += 3)
  688. {
  689. t1 = indices[i];
  690. if (t1 > nverts)
  691. break;
  692. t2 = indices[i + 1];
  693. if (t2 > nverts)
  694. break;
  695. t3 = indices[i + 2];
  696. if (t3 > nverts)
  697. break;
  698. f = new Face(t1, t2, t3);
  699. faces.Add(f);
  700. }
  701. vs.Clear();
  702. if (coords.Count > 0 && faces.Count > 0)
  703. return true;
  704. }
  705. else
  706. return false;
  707. }
  708. }
  709. return true;
  710. }
  711. /// <summary>
  712. /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
  713. /// </summary>
  714. /// <param name="primName"></param>
  715. /// <param name="primShape"></param>
  716. /// <param name="size"></param>
  717. /// <param name="lod"></param>
  718. /// <param name="coords">Coords are added to this list by the method.</param>
  719. /// <param name="faces">Faces are added to this list by the method.</param>
  720. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  721. private bool GenerateCoordsAndFacesFromPrimSculptData(
  722. string primName, PrimitiveBaseShape primShape, float lod, out List<Coord> coords, out List<Face> faces)
  723. {
  724. coords = new List<Coord>();
  725. faces = new List<Face>();
  726. PrimMesher.SculptMesh sculptMesh;
  727. Image idata = null;
  728. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  729. return false;
  730. try
  731. {
  732. OpenMetaverse.Imaging.ManagedImage unusedData;
  733. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
  734. unusedData = null;
  735. if (idata == null)
  736. {
  737. // In some cases it seems that the decode can return a null bitmap without throwing
  738. // an exception
  739. m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
  740. return false;
  741. }
  742. }
  743. catch (DllNotFoundException)
  744. {
  745. 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!");
  746. return false;
  747. }
  748. catch (IndexOutOfRangeException)
  749. {
  750. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  751. return false;
  752. }
  753. catch (Exception ex)
  754. {
  755. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  756. return false;
  757. }
  758. PrimMesher.SculptMesh.SculptType sculptType;
  759. // remove mirror and invert bits
  760. OpenMetaverse.SculptType pbsSculptType = ((OpenMetaverse.SculptType)(primShape.SculptType & 0x3f));
  761. switch (pbsSculptType)
  762. {
  763. case OpenMetaverse.SculptType.Cylinder:
  764. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  765. break;
  766. case OpenMetaverse.SculptType.Plane:
  767. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  768. break;
  769. case OpenMetaverse.SculptType.Torus:
  770. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  771. break;
  772. case OpenMetaverse.SculptType.Sphere:
  773. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  774. break;
  775. default:
  776. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  777. break;
  778. }
  779. bool mirror = ((primShape.SculptType & 128) != 0);
  780. bool invert = ((primShape.SculptType & 64) != 0);
  781. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, mirror, invert);
  782. idata.Dispose();
  783. // sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  784. coords = sculptMesh.coords;
  785. faces = sculptMesh.faces;
  786. return true;
  787. }
  788. /// <summary>
  789. /// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
  790. /// </summary>
  791. /// <param name="primName"></param>
  792. /// <param name="primShape"></param>
  793. /// <param name="size"></param>
  794. /// <param name="coords">Coords are added to this list by the method.</param>
  795. /// <param name="faces">Faces are added to this list by the method.</param>
  796. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  797. private bool GenerateCoordsAndFacesFromPrimShapeData(
  798. string primName, PrimitiveBaseShape primShape, float lod, out List<Coord> coords, out List<Face> faces)
  799. {
  800. PrimMesh primMesh;
  801. coords = new List<Coord>();
  802. faces = new List<Face>();
  803. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  804. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  805. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  806. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  807. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  808. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  809. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  810. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  811. if (profileBegin < 0.0f)
  812. profileBegin = 0.0f;
  813. if (profileEnd < 0.02f)
  814. profileEnd = 0.02f;
  815. else if (profileEnd > 1.0f)
  816. profileEnd = 1.0f;
  817. if (profileBegin >= profileEnd)
  818. profileBegin = profileEnd - 0.02f;
  819. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  820. if (profileHollow > 0.95f)
  821. profileHollow = 0.95f;
  822. int sides = 4;
  823. LevelOfDetail iLOD = (LevelOfDetail)lod;
  824. byte profshape = (byte)(primShape.ProfileCurve & 0x07);
  825. if (profshape == (byte)ProfileShape.EquilateralTriangle
  826. || profshape == (byte)ProfileShape.IsometricTriangle
  827. || profshape == (byte)ProfileShape.RightTriangle)
  828. sides = 3;
  829. else if (profshape == (byte)ProfileShape.Circle)
  830. {
  831. switch (iLOD)
  832. {
  833. case LevelOfDetail.High: sides = 24; break;
  834. case LevelOfDetail.Medium: sides = 12; break;
  835. case LevelOfDetail.Low: sides = 6; break;
  836. case LevelOfDetail.VeryLow: sides = 3; break;
  837. default: sides = 24; break;
  838. }
  839. }
  840. else if (profshape == (byte)ProfileShape.HalfCircle)
  841. { // half circle, prim is a sphere
  842. switch (iLOD)
  843. {
  844. case LevelOfDetail.High: sides = 24; break;
  845. case LevelOfDetail.Medium: sides = 12; break;
  846. case LevelOfDetail.Low: sides = 6; break;
  847. case LevelOfDetail.VeryLow: sides = 3; break;
  848. default: sides = 24; break;
  849. }
  850. profileBegin = 0.5f * profileBegin + 0.5f;
  851. profileEnd = 0.5f * profileEnd + 0.5f;
  852. }
  853. int hollowSides = sides;
  854. if (primShape.HollowShape == HollowShape.Circle)
  855. {
  856. switch (iLOD)
  857. {
  858. case LevelOfDetail.High: hollowSides = 24; break;
  859. case LevelOfDetail.Medium: hollowSides = 12; break;
  860. case LevelOfDetail.Low: hollowSides = 6; break;
  861. case LevelOfDetail.VeryLow: hollowSides = 3; break;
  862. default: hollowSides = 24; break;
  863. }
  864. }
  865. else if (primShape.HollowShape == HollowShape.Square)
  866. hollowSides = 4;
  867. else if (primShape.HollowShape == HollowShape.Triangle)
  868. {
  869. if (profshape == (byte)ProfileShape.HalfCircle)
  870. hollowSides = 6;
  871. else
  872. hollowSides = 3;
  873. }
  874. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  875. if (primMesh.errorMessage != null)
  876. if (primMesh.errorMessage.Length > 0)
  877. m_log.Error("[ERROR] " + primMesh.errorMessage);
  878. primMesh.topShearX = pathShearX;
  879. primMesh.topShearY = pathShearY;
  880. primMesh.pathCutBegin = pathBegin;
  881. primMesh.pathCutEnd = pathEnd;
  882. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  883. {
  884. primMesh.twistBegin = (primShape.PathTwistBegin * 18) / 10;
  885. primMesh.twistEnd = (primShape.PathTwist * 18) / 10;
  886. primMesh.taperX = pathScaleX;
  887. primMesh.taperY = pathScaleY;
  888. #if SPAM
  889. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  890. #endif
  891. try
  892. {
  893. primMesh.ExtrudeLinear();
  894. }
  895. catch (Exception ex)
  896. {
  897. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  898. return false;
  899. }
  900. }
  901. else
  902. {
  903. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  904. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  905. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  906. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  907. primMesh.skew = 0.01f * primShape.PathSkew;
  908. primMesh.twistBegin = (primShape.PathTwistBegin * 36) / 10;
  909. primMesh.twistEnd = (primShape.PathTwist * 36) / 10;
  910. primMesh.taperX = primShape.PathTaperX * 0.01f;
  911. primMesh.taperY = primShape.PathTaperY * 0.01f;
  912. if(profshape == (byte)ProfileShape.HalfCircle)
  913. {
  914. if(primMesh.holeSizeY < 0.01f)
  915. primMesh.holeSizeY = 0.01f;
  916. else if(primMesh.holeSizeY > 1.0f)
  917. primMesh.holeSizeY = 1.0f;
  918. }
  919. #if SPAM
  920. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  921. #endif
  922. try
  923. {
  924. primMesh.ExtrudeCircular();
  925. }
  926. catch (Exception ex)
  927. {
  928. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  929. return false;
  930. }
  931. }
  932. // primMesh.DumpRaw(baseDir, primName, "primMesh");
  933. coords = primMesh.coords;
  934. faces = primMesh.faces;
  935. return true;
  936. }
  937. public AMeshKey GetMeshUniqueKey(PrimitiveBaseShape primShape, Vector3 size, byte lod, bool convex)
  938. {
  939. AMeshKey key = new AMeshKey();
  940. Byte[] someBytes;
  941. key.hashB = 5181;
  942. key.hashC = 5181;
  943. ulong hash = 5381;
  944. if (primShape.SculptEntry)
  945. {
  946. key.uuid = primShape.SculptTexture;
  947. key.hashC = mdjb2(key.hashC, primShape.SculptType);
  948. key.hashC = mdjb2(key.hashC, primShape.PCode);
  949. }
  950. else
  951. {
  952. hash = mdjb2(hash, primShape.PathCurve);
  953. hash = mdjb2(hash, (byte)primShape.HollowShape);
  954. hash = mdjb2(hash, (byte)primShape.ProfileShape);
  955. hash = mdjb2(hash, primShape.PathBegin);
  956. hash = mdjb2(hash, primShape.PathEnd);
  957. hash = mdjb2(hash, primShape.PathScaleX);
  958. hash = mdjb2(hash, primShape.PathScaleY);
  959. hash = mdjb2(hash, primShape.PathShearX);
  960. key.hashA = hash;
  961. hash = key.hashB;
  962. hash = mdjb2(hash, primShape.PathShearY);
  963. hash = mdjb2(hash, (byte)primShape.PathTwist);
  964. hash = mdjb2(hash, (byte)primShape.PathTwistBegin);
  965. hash = mdjb2(hash, (byte)primShape.PathRadiusOffset);
  966. hash = mdjb2(hash, (byte)primShape.PathTaperX);
  967. hash = mdjb2(hash, (byte)primShape.PathTaperY);
  968. hash = mdjb2(hash, primShape.PathRevolutions);
  969. hash = mdjb2(hash, (byte)primShape.PathSkew);
  970. hash = mdjb2(hash, primShape.ProfileBegin);
  971. hash = mdjb2(hash, primShape.ProfileEnd);
  972. hash = mdjb2(hash, primShape.ProfileHollow);
  973. hash = mdjb2(hash, primShape.PCode);
  974. key.hashB = hash;
  975. }
  976. hash = key.hashC;
  977. hash = mdjb2(hash, lod);
  978. if (size == m_MeshUnitSize)
  979. {
  980. hash = hash << 8;
  981. hash |= 8;
  982. }
  983. else
  984. {
  985. someBytes = size.GetBytes();
  986. for (int i = 0; i < someBytes.Length; i++)
  987. hash = mdjb2(hash, someBytes[i]);
  988. hash = hash << 8;
  989. }
  990. if (convex)
  991. hash |= 4;
  992. if (primShape.SculptEntry)
  993. {
  994. hash |= 1;
  995. if (primShape.SculptType == (byte)SculptType.Mesh)
  996. hash |= 2;
  997. }
  998. key.hashC = hash;
  999. return key;
  1000. }
  1001. private ulong mdjb2(ulong hash, byte c)
  1002. {
  1003. return ((hash << 5) + hash) + (ulong)c;
  1004. }
  1005. private ulong mdjb2(ulong hash, ushort c)
  1006. {
  1007. hash = ((hash << 5) + hash) + (ulong)((byte)c);
  1008. return ((hash << 5) + hash) + (ulong)(c >> 8);
  1009. }
  1010. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  1011. {
  1012. return CreateMesh(primName, primShape, size, lod, false,false,false);
  1013. }
  1014. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  1015. {
  1016. return CreateMesh(primName, primShape, size, lod, false,false,false);
  1017. }
  1018. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache, bool convex, bool forOde)
  1019. {
  1020. return CreateMesh(primName, primShape, size, lod, false, false, false);
  1021. }
  1022. public IMesh GetMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex)
  1023. {
  1024. Mesh mesh = null;
  1025. if (size.X < 0.01f) size.X = 0.01f;
  1026. if (size.Y < 0.01f) size.Y = 0.01f;
  1027. if (size.Z < 0.01f) size.Z = 0.01f;
  1028. AMeshKey key = GetMeshUniqueKey(primShape, size, (byte)lod, convex);
  1029. lock (m_uniqueMeshes)
  1030. {
  1031. m_uniqueMeshes.TryGetValue(key, out mesh);
  1032. if (mesh != null)
  1033. {
  1034. mesh.RefCount++;
  1035. return mesh;
  1036. }
  1037. // try to find a identical mesh on meshs recently released
  1038. lock (m_uniqueReleasedMeshes)
  1039. {
  1040. m_uniqueReleasedMeshes.TryGetValue(key, out mesh);
  1041. if (mesh != null)
  1042. {
  1043. m_uniqueReleasedMeshes.Remove(key);
  1044. try
  1045. {
  1046. m_uniqueMeshes.Add(key, mesh);
  1047. }
  1048. catch { }
  1049. mesh.RefCount = 1;
  1050. return mesh;
  1051. }
  1052. }
  1053. }
  1054. return null;
  1055. }
  1056. private static Vector3 m_MeshUnitSize = new Vector3(1.0f, 1.0f, 1.0f);
  1057. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex, bool forOde)
  1058. {
  1059. #if SPAM
  1060. m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
  1061. #endif
  1062. Mesh mesh = null;
  1063. if (size.X < 0.01f) size.X = 0.01f;
  1064. if (size.Y < 0.01f) size.Y = 0.01f;
  1065. if (size.Z < 0.01f) size.Z = 0.01f;
  1066. // try to find a identical mesh on meshs in use
  1067. AMeshKey key = GetMeshUniqueKey(primShape,size,(byte)lod, convex);
  1068. lock (m_uniqueMeshes)
  1069. {
  1070. m_uniqueMeshes.TryGetValue(key, out mesh);
  1071. if (mesh != null)
  1072. {
  1073. mesh.RefCount++;
  1074. return mesh;
  1075. }
  1076. // try to find a identical mesh on meshs recently released
  1077. lock (m_uniqueReleasedMeshes)
  1078. {
  1079. m_uniqueReleasedMeshes.TryGetValue(key, out mesh);
  1080. if (mesh != null)
  1081. {
  1082. m_uniqueReleasedMeshes.Remove(key);
  1083. try
  1084. {
  1085. m_uniqueMeshes.Add(key, mesh);
  1086. }
  1087. catch { }
  1088. mesh.RefCount = 1;
  1089. return mesh;
  1090. }
  1091. }
  1092. }
  1093. Mesh UnitMesh = null;
  1094. AMeshKey unitKey = GetMeshUniqueKey(primShape, m_MeshUnitSize, (byte)lod, convex);
  1095. lock (m_uniqueReleasedMeshes)
  1096. {
  1097. m_uniqueReleasedMeshes.TryGetValue(unitKey, out UnitMesh);
  1098. if (UnitMesh != null)
  1099. {
  1100. UnitMesh.RefCount = 1;
  1101. }
  1102. }
  1103. if (UnitMesh == null && primShape.SculptEntry && doMeshFileCache)
  1104. UnitMesh = GetFromFileCache(unitKey);
  1105. if (UnitMesh == null)
  1106. {
  1107. UnitMesh = CreateMeshFromPrimMesher(primName, primShape, lod, convex);
  1108. if (UnitMesh == null)
  1109. return null;
  1110. UnitMesh.DumpRaw(baseDir, unitKey.ToString(), "Z");
  1111. if (forOde)
  1112. {
  1113. // force pinned mem allocation
  1114. UnitMesh.PrepForOde();
  1115. }
  1116. else
  1117. UnitMesh.TrimExcess();
  1118. UnitMesh.Key = unitKey;
  1119. UnitMesh.RefCount = 1;
  1120. if (doMeshFileCache && primShape.SculptEntry)
  1121. StoreToFileCache(unitKey, UnitMesh);
  1122. lock (m_uniqueReleasedMeshes)
  1123. {
  1124. try
  1125. {
  1126. m_uniqueReleasedMeshes.Add(unitKey, UnitMesh);
  1127. }
  1128. catch { }
  1129. }
  1130. }
  1131. mesh = UnitMesh.Scale(size);
  1132. mesh.Key = key;
  1133. mesh.RefCount = 1;
  1134. lock (m_uniqueMeshes)
  1135. {
  1136. try
  1137. {
  1138. m_uniqueMeshes.Add(key, mesh);
  1139. }
  1140. catch { }
  1141. }
  1142. return mesh;
  1143. }
  1144. public void ReleaseMesh(IMesh imesh)
  1145. {
  1146. if (imesh == null)
  1147. return;
  1148. Mesh mesh = (Mesh)imesh;
  1149. lock (m_uniqueMeshes)
  1150. {
  1151. int curRefCount = mesh.RefCount;
  1152. curRefCount--;
  1153. if (curRefCount > 0)
  1154. {
  1155. mesh.RefCount = curRefCount;
  1156. return;
  1157. }
  1158. mesh.RefCount = 0;
  1159. m_uniqueMeshes.Remove(mesh.Key);
  1160. lock (m_uniqueReleasedMeshes)
  1161. {
  1162. try
  1163. {
  1164. m_uniqueReleasedMeshes.Add(mesh.Key, mesh);
  1165. }
  1166. catch { }
  1167. }
  1168. }
  1169. }
  1170. public void ExpireReleaseMeshs()
  1171. {
  1172. if (m_uniqueReleasedMeshes.Count == 0)
  1173. return;
  1174. List<Mesh> meshstodelete = new List<Mesh>();
  1175. int refcntr;
  1176. lock (m_uniqueReleasedMeshes)
  1177. {
  1178. foreach (Mesh m in m_uniqueReleasedMeshes.Values)
  1179. {
  1180. refcntr = m.RefCount;
  1181. refcntr--;
  1182. if (refcntr > -6)
  1183. m.RefCount = refcntr;
  1184. else
  1185. meshstodelete.Add(m);
  1186. }
  1187. foreach (Mesh m in meshstodelete)
  1188. {
  1189. m_uniqueReleasedMeshes.Remove(m.Key);
  1190. m.releaseBuildingMeshData();
  1191. m.releasePinned();
  1192. }
  1193. }
  1194. }
  1195. public void FileNames(AMeshKey key, out string dir,out string fullFileName)
  1196. {
  1197. string id = key.ToString();
  1198. string init = id.Substring(0, 1);
  1199. dir = System.IO.Path.Combine(cachePath, init);
  1200. fullFileName = System.IO.Path.Combine(dir, id);
  1201. }
  1202. public string FullFileName(AMeshKey key)
  1203. {
  1204. string id = key.ToString();
  1205. string init = id.Substring(0,1);
  1206. id = System.IO.Path.Combine(init, id);
  1207. id = System.IO.Path.Combine(cachePath, id);
  1208. return id;
  1209. }
  1210. private Mesh GetFromFileCache(AMeshKey key)
  1211. {
  1212. Mesh mesh = null;
  1213. string filename = FullFileName(key);
  1214. bool ok = true;
  1215. lock (diskLock)
  1216. {
  1217. if (File.Exists(filename))
  1218. {
  1219. try
  1220. {
  1221. using(FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  1222. {
  1223. // BinaryFormatter bformatter = new BinaryFormatter();
  1224. mesh = Mesh.FromStream(stream,key);
  1225. }
  1226. }
  1227. catch (Exception e)
  1228. {
  1229. ok = false;
  1230. m_log.ErrorFormat(
  1231. "[MESH CACHE]: Failed to get file {0}. Exception {1} {2}",
  1232. filename, e.Message, e.StackTrace);
  1233. }
  1234. try
  1235. {
  1236. if (mesh == null || !ok)
  1237. File.Delete(filename);
  1238. else
  1239. File.SetLastAccessTimeUtc(filename, DateTime.UtcNow);
  1240. }
  1241. catch
  1242. {
  1243. }
  1244. }
  1245. }
  1246. return mesh;
  1247. }
  1248. private void StoreToFileCache(AMeshKey key, Mesh mesh)
  1249. {
  1250. bool ok = false;
  1251. // Make sure the target cache directory exists
  1252. string dir = String.Empty;
  1253. string filename = String.Empty;
  1254. FileNames(key, out dir, out filename);
  1255. lock (diskLock)
  1256. {
  1257. try
  1258. {
  1259. if (!Directory.Exists(dir))
  1260. {
  1261. Directory.CreateDirectory(dir);
  1262. }
  1263. using(Stream stream = File.Open(filename, FileMode.Create))
  1264. ok = mesh.ToStream(stream);
  1265. }
  1266. catch (IOException e)
  1267. {
  1268. m_log.ErrorFormat(
  1269. "[MESH CACHE]: Failed to write file {0}. Exception {1} {2}.",
  1270. filename, e.Message, e.StackTrace);
  1271. ok = false;
  1272. }
  1273. if (!ok && File.Exists(filename))
  1274. {
  1275. try
  1276. {
  1277. File.Delete(filename);
  1278. }
  1279. catch (IOException e)
  1280. {
  1281. m_log.ErrorFormat(
  1282. "[MESH CACHE]: Failed to delete file {0}",filename);
  1283. }
  1284. }
  1285. }
  1286. }
  1287. public void ExpireFileCache()
  1288. {
  1289. if (!doCacheExpire)
  1290. return;
  1291. string controlfile = System.IO.Path.Combine(cachePath, "cntr");
  1292. lock (diskLock)
  1293. {
  1294. try
  1295. {
  1296. if (File.Exists(controlfile))
  1297. {
  1298. int ndeleted = 0;
  1299. int totalfiles = 0;
  1300. int ndirs = 0;
  1301. DateTime OlderTime = File.GetLastAccessTimeUtc(controlfile) - CacheExpire;
  1302. File.SetLastAccessTimeUtc(controlfile, DateTime.UtcNow);
  1303. foreach (string dir in Directory.GetDirectories(cachePath))
  1304. {
  1305. try
  1306. {
  1307. foreach (string file in Directory.GetFiles(dir))
  1308. {
  1309. try
  1310. {
  1311. if (File.GetLastAccessTimeUtc(file) < OlderTime)
  1312. {
  1313. File.Delete(file);
  1314. ndeleted++;
  1315. }
  1316. }
  1317. catch { }
  1318. totalfiles++;
  1319. }
  1320. }
  1321. catch { }
  1322. ndirs++;
  1323. }
  1324. if (ndeleted == 0)
  1325. m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, no expires",
  1326. totalfiles,ndirs);
  1327. else
  1328. m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, expired {2} files accessed before {3}",
  1329. totalfiles,ndirs, ndeleted, OlderTime.ToString());
  1330. }
  1331. else
  1332. {
  1333. m_log.Info("[MESH CACHE]: Expire delayed to next startup");
  1334. FileStream fs = File.Create(controlfile,4096,FileOptions.WriteThrough);
  1335. fs.Close();
  1336. }
  1337. }
  1338. catch { }
  1339. }
  1340. }
  1341. }
  1342. }