Meshmerizer.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  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(true);
  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, convex, out coords, out faces))
  297. return null;
  298. }
  299. int numCoords = coords.Count;
  300. int numFaces = faces.Count;
  301. Mesh mesh = new Mesh(true);
  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. // for ubOde we have a diferent mesh use priority
  334. // priority is to use full mesh then decomposition
  335. // SL does the oposite
  336. bool usemesh = false;
  337. coords = new List<Coord>();
  338. faces = new List<Face>();
  339. OSD meshOsd = null;
  340. if (primShape.SculptData.Length <= 0)
  341. {
  342. // m_log.InfoFormat("[MESH]: asset data for {0} is zero length", primName);
  343. return false;
  344. }
  345. long start = 0;
  346. using (MemoryStream data = new MemoryStream(primShape.SculptData))
  347. {
  348. try
  349. {
  350. OSD osd = OSDParser.DeserializeLLSDBinary(data);
  351. if (osd is OSDMap)
  352. meshOsd = (OSDMap)osd;
  353. else
  354. {
  355. m_log.WarnFormat("[Mesh}: unable to cast mesh asset to OSDMap prim: {0}",primName);
  356. return false;
  357. }
  358. }
  359. catch (Exception e)
  360. {
  361. m_log.Error("[MESH]: Exception deserializing mesh asset header:" + e.ToString());
  362. }
  363. start = data.Position;
  364. }
  365. if (meshOsd is OSDMap)
  366. {
  367. OSDMap physicsParms = null;
  368. OSDMap map = (OSDMap)meshOsd;
  369. if (!convex)
  370. {
  371. if (map.ContainsKey("physics_shape"))
  372. physicsParms = (OSDMap)map["physics_shape"]; // old asset format
  373. else if (map.ContainsKey("physics_mesh"))
  374. physicsParms = (OSDMap)map["physics_mesh"]; // new asset format
  375. if (physicsParms != null)
  376. usemesh = true;
  377. }
  378. if(!usemesh && (map.ContainsKey("physics_convex")))
  379. physicsParms = (OSDMap)map["physics_convex"];
  380. if (physicsParms == null)
  381. {
  382. //m_log.WarnFormat("[MESH]: unknown mesh type for prim {0}",primName);
  383. return false;
  384. }
  385. int physOffset = physicsParms["offset"].AsInteger() + (int)start;
  386. int physSize = physicsParms["size"].AsInteger();
  387. if (physOffset < 0 || physSize == 0)
  388. return false; // no mesh data in asset
  389. OSD decodedMeshOsd = new OSD();
  390. byte[] meshBytes = new byte[physSize];
  391. System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize);
  392. try
  393. {
  394. using (MemoryStream inMs = new MemoryStream(meshBytes))
  395. {
  396. using (MemoryStream outMs = new MemoryStream())
  397. {
  398. using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress))
  399. {
  400. byte[] readBuffer = new byte[2048];
  401. inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header
  402. int readLen = 0;
  403. while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
  404. outMs.Write(readBuffer, 0, readLen);
  405. outMs.Flush();
  406. outMs.Seek(0, SeekOrigin.Begin);
  407. byte[] decompressedBuf = outMs.GetBuffer();
  408. decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf);
  409. }
  410. }
  411. }
  412. }
  413. catch (Exception e)
  414. {
  415. m_log.Error("[MESH]: exception decoding physical mesh prim " + primName +" : " + e.ToString());
  416. return false;
  417. }
  418. if (usemesh)
  419. {
  420. OSDArray decodedMeshOsdArray = null;
  421. // physics_shape is an array of OSDMaps, one for each submesh
  422. if (decodedMeshOsd is OSDArray)
  423. {
  424. // Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd));
  425. decodedMeshOsdArray = (OSDArray)decodedMeshOsd;
  426. foreach (OSD subMeshOsd in decodedMeshOsdArray)
  427. {
  428. if (subMeshOsd is OSDMap)
  429. AddSubMesh(subMeshOsd as OSDMap, coords, faces);
  430. }
  431. }
  432. }
  433. else
  434. {
  435. OSDMap cmap = (OSDMap)decodedMeshOsd;
  436. if (cmap == null)
  437. return false;
  438. byte[] data;
  439. List<float3> vs = new List<float3>();
  440. PHullResult hullr = new PHullResult();
  441. float3 f3;
  442. Coord c;
  443. Face f;
  444. Vector3 range;
  445. Vector3 min;
  446. const float invMaxU16 = 1.0f / 65535f;
  447. int t1;
  448. int t2;
  449. int t3;
  450. int i;
  451. int nverts;
  452. int nindexs;
  453. if (cmap.ContainsKey("Max"))
  454. range = cmap["Max"].AsVector3();
  455. else
  456. range = new Vector3(0.5f, 0.5f, 0.5f);
  457. if (cmap.ContainsKey("Min"))
  458. min = cmap["Min"].AsVector3();
  459. else
  460. min = new Vector3(-0.5f, -0.5f, -0.5f);
  461. range = range - min;
  462. range *= invMaxU16;
  463. if(!convex)
  464. {
  465. // if mesh data not present and not convex then we need convex decomposition data
  466. if (cmap.ContainsKey("HullList") && cmap.ContainsKey("Positions"))
  467. {
  468. List<int> hsizes = new List<int>();
  469. int totalpoints = 0;
  470. data = cmap["HullList"].AsBinary();
  471. for (i = 0; i < data.Length; i++)
  472. {
  473. t1 = data[i];
  474. if (t1 == 0)
  475. t1 = 256;
  476. totalpoints += t1;
  477. hsizes.Add(t1);
  478. }
  479. data = cmap["Positions"].AsBinary();
  480. int ptr = 0;
  481. int vertsoffset = 0;
  482. if (totalpoints == data.Length / 6) // 2 bytes per coord, 3 coords per point
  483. {
  484. foreach (int hullsize in hsizes)
  485. {
  486. for (i = 0; i < hullsize; i++ )
  487. {
  488. t1 = data[ptr++];
  489. t1 += data[ptr++] << 8;
  490. t2 = data[ptr++];
  491. t2 += data[ptr++] << 8;
  492. t3 = data[ptr++];
  493. t3 += data[ptr++] << 8;
  494. f3 = new float3((t1 * range.X + min.X),
  495. (t2 * range.Y + min.Y),
  496. (t3 * range.Z + min.Z));
  497. vs.Add(f3);
  498. }
  499. if(hullsize <3)
  500. {
  501. vs.Clear();
  502. continue;
  503. }
  504. if (hullsize <5)
  505. {
  506. foreach (float3 point in vs)
  507. {
  508. c.X = point.x;
  509. c.Y = point.y;
  510. c.Z = point.z;
  511. coords.Add(c);
  512. }
  513. f = new Face(vertsoffset, vertsoffset + 1, vertsoffset + 2);
  514. faces.Add(f);
  515. if (hullsize == 4)
  516. {
  517. // not sure about orientation..
  518. f = new Face(vertsoffset, vertsoffset + 2, vertsoffset + 3);
  519. faces.Add(f);
  520. f = new Face(vertsoffset, vertsoffset + 3, vertsoffset + 1);
  521. faces.Add(f);
  522. f = new Face(vertsoffset + 3, vertsoffset + 2, vertsoffset + 1);
  523. faces.Add(f);
  524. }
  525. vertsoffset += vs.Count;
  526. vs.Clear();
  527. continue;
  528. }
  529. /*
  530. if (!HullUtils.ComputeHull(vs, ref hullr, 0, 0.0f))
  531. {
  532. vs.Clear();
  533. continue;
  534. }
  535. nverts = hullr.Vertices.Count;
  536. nindexs = hullr.Indices.Count;
  537. if (nindexs % 3 != 0)
  538. {
  539. vs.Clear();
  540. continue;
  541. }
  542. for (i = 0; i < nverts; i++)
  543. {
  544. c.X = hullr.Vertices[i].x;
  545. c.Y = hullr.Vertices[i].y;
  546. c.Z = hullr.Vertices[i].z;
  547. coords.Add(c);
  548. }
  549. for (i = 0; i < nindexs; i += 3)
  550. {
  551. t1 = hullr.Indices[i];
  552. if (t1 > nverts)
  553. break;
  554. t2 = hullr.Indices[i + 1];
  555. if (t2 > nverts)
  556. break;
  557. t3 = hullr.Indices[i + 2];
  558. if (t3 > nverts)
  559. break;
  560. f = new Face(vertsoffset + t1, vertsoffset + t2, vertsoffset + t3);
  561. faces.Add(f);
  562. }
  563. */
  564. List<int> indices;
  565. if (!HullUtils.ComputeHull(vs, out indices))
  566. {
  567. vs.Clear();
  568. continue;
  569. }
  570. nverts = vs.Count;
  571. nindexs = indices.Count;
  572. if (nindexs % 3 != 0)
  573. {
  574. vs.Clear();
  575. continue;
  576. }
  577. for (i = 0; i < nverts; i++)
  578. {
  579. c.X = vs[i].x;
  580. c.Y = vs[i].y;
  581. c.Z = vs[i].z;
  582. coords.Add(c);
  583. }
  584. for (i = 0; i < nindexs; i += 3)
  585. {
  586. t1 = indices[i];
  587. if (t1 > nverts)
  588. break;
  589. t2 = indices[i + 1];
  590. if (t2 > nverts)
  591. break;
  592. t3 = indices[i + 2];
  593. if (t3 > nverts)
  594. break;
  595. f = new Face(vertsoffset + t1, vertsoffset + t2, vertsoffset + t3);
  596. faces.Add(f);
  597. }
  598. vertsoffset += nverts;
  599. vs.Clear();
  600. }
  601. }
  602. if (coords.Count > 0 && faces.Count > 0)
  603. return true;
  604. }
  605. else
  606. {
  607. // if neither mesh or decomposition present, warn and use convex
  608. //m_log.WarnFormat("[MESH]: Data for PRIM shape type ( mesh or decomposition) not found for prim {0}",primName);
  609. }
  610. }
  611. vs.Clear();
  612. if (cmap.ContainsKey("BoundingVerts"))
  613. {
  614. data = cmap["BoundingVerts"].AsBinary();
  615. for (i = 0; i < data.Length; )
  616. {
  617. t1 = data[i++];
  618. t1 += data[i++] << 8;
  619. t2 = data[i++];
  620. t2 += data[i++] << 8;
  621. t3 = data[i++];
  622. t3 += data[i++] << 8;
  623. f3 = new float3((t1 * range.X + min.X),
  624. (t2 * range.Y + min.Y),
  625. (t3 * range.Z + min.Z));
  626. vs.Add(f3);
  627. }
  628. nverts = vs.Count;
  629. if (nverts < 3)
  630. {
  631. vs.Clear();
  632. return false;
  633. }
  634. if (nverts < 5)
  635. {
  636. foreach (float3 point in vs)
  637. {
  638. c.X = point.x;
  639. c.Y = point.y;
  640. c.Z = point.z;
  641. coords.Add(c);
  642. }
  643. f = new Face(0, 1, 2);
  644. faces.Add(f);
  645. if (nverts == 4)
  646. {
  647. f = new Face(0, 2, 3);
  648. faces.Add(f);
  649. f = new Face(0, 3, 1);
  650. faces.Add(f);
  651. f = new Face( 3, 2, 1);
  652. faces.Add(f);
  653. }
  654. vs.Clear();
  655. return true;
  656. }
  657. /*
  658. if (!HullUtils.ComputeHull(vs, ref hullr, 0, 0.0f))
  659. return false;
  660. nverts = hullr.Vertices.Count;
  661. nindexs = hullr.Indices.Count;
  662. if (nindexs % 3 != 0)
  663. return false;
  664. for (i = 0; i < nverts; i++)
  665. {
  666. c.X = hullr.Vertices[i].x;
  667. c.Y = hullr.Vertices[i].y;
  668. c.Z = hullr.Vertices[i].z;
  669. coords.Add(c);
  670. }
  671. for (i = 0; i < nindexs; i += 3)
  672. {
  673. t1 = hullr.Indices[i];
  674. if (t1 > nverts)
  675. break;
  676. t2 = hullr.Indices[i + 1];
  677. if (t2 > nverts)
  678. break;
  679. t3 = hullr.Indices[i + 2];
  680. if (t3 > nverts)
  681. break;
  682. f = new Face(t1, t2, t3);
  683. faces.Add(f);
  684. }
  685. */
  686. List<int> indices;
  687. if (!HullUtils.ComputeHull(vs, out indices))
  688. return false;
  689. nindexs = indices.Count;
  690. if (nindexs % 3 != 0)
  691. return false;
  692. for (i = 0; i < nverts; i++)
  693. {
  694. c.X = vs[i].x;
  695. c.Y = vs[i].y;
  696. c.Z = vs[i].z;
  697. coords.Add(c);
  698. }
  699. for (i = 0; i < nindexs; i += 3)
  700. {
  701. t1 = indices[i];
  702. if (t1 > nverts)
  703. break;
  704. t2 = indices[i + 1];
  705. if (t2 > nverts)
  706. break;
  707. t3 = indices[i + 2];
  708. if (t3 > nverts)
  709. break;
  710. f = new Face(t1, t2, t3);
  711. faces.Add(f);
  712. }
  713. vs.Clear();
  714. if (coords.Count > 0 && faces.Count > 0)
  715. return true;
  716. }
  717. else
  718. return false;
  719. }
  720. }
  721. return true;
  722. }
  723. /// <summary>
  724. /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim.
  725. /// </summary>
  726. /// <param name="primName"></param>
  727. /// <param name="primShape"></param>
  728. /// <param name="size"></param>
  729. /// <param name="lod"></param>
  730. /// <param name="coords">Coords are added to this list by the method.</param>
  731. /// <param name="faces">Faces are added to this list by the method.</param>
  732. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  733. private bool GenerateCoordsAndFacesFromPrimSculptData(
  734. string primName, PrimitiveBaseShape primShape, float lod, out List<Coord> coords, out List<Face> faces)
  735. {
  736. coords = new List<Coord>();
  737. faces = new List<Face>();
  738. PrimMesher.SculptMesh sculptMesh;
  739. Image idata = null;
  740. if (primShape.SculptData == null || primShape.SculptData.Length == 0)
  741. return false;
  742. try
  743. {
  744. OpenMetaverse.Imaging.ManagedImage unusedData;
  745. OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata);
  746. unusedData = null;
  747. if (idata == null)
  748. {
  749. // In some cases it seems that the decode can return a null bitmap without throwing
  750. // an exception
  751. m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName);
  752. return false;
  753. }
  754. }
  755. catch (DllNotFoundException)
  756. {
  757. 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!");
  758. return false;
  759. }
  760. catch (IndexOutOfRangeException)
  761. {
  762. m_log.Error("[PHYSICS]: OpenJpeg was unable to decode this. Physics Proxy generation failed");
  763. return false;
  764. }
  765. catch (Exception ex)
  766. {
  767. m_log.Error("[PHYSICS]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex.Message);
  768. return false;
  769. }
  770. PrimMesher.SculptMesh.SculptType sculptType;
  771. // remove mirror and invert bits
  772. OpenMetaverse.SculptType pbsSculptType = ((OpenMetaverse.SculptType)(primShape.SculptType & 0x3f));
  773. switch (pbsSculptType)
  774. {
  775. case OpenMetaverse.SculptType.Cylinder:
  776. sculptType = PrimMesher.SculptMesh.SculptType.cylinder;
  777. break;
  778. case OpenMetaverse.SculptType.Plane:
  779. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  780. break;
  781. case OpenMetaverse.SculptType.Torus:
  782. sculptType = PrimMesher.SculptMesh.SculptType.torus;
  783. break;
  784. case OpenMetaverse.SculptType.Sphere:
  785. sculptType = PrimMesher.SculptMesh.SculptType.sphere;
  786. break;
  787. default:
  788. sculptType = PrimMesher.SculptMesh.SculptType.plane;
  789. break;
  790. }
  791. bool mirror = ((primShape.SculptType & 128) != 0);
  792. bool invert = ((primShape.SculptType & 64) != 0);
  793. sculptMesh = new PrimMesher.SculptMesh((Bitmap)idata, sculptType, (int)lod, mirror, invert);
  794. idata.Dispose();
  795. // sculptMesh.DumpRaw(baseDir, primName, "primMesh");
  796. coords = sculptMesh.coords;
  797. faces = sculptMesh.faces;
  798. return true;
  799. }
  800. /// <summary>
  801. /// Generate the co-ords and faces necessary to construct a mesh from the shape data the accompanies a prim.
  802. /// </summary>
  803. /// <param name="primName"></param>
  804. /// <param name="primShape"></param>
  805. /// <param name="size"></param>
  806. /// <param name="coords">Coords are added to this list by the method.</param>
  807. /// <param name="faces">Faces are added to this list by the method.</param>
  808. /// <returns>true if coords and faces were successfully generated, false if not</returns>
  809. private bool GenerateCoordsAndFacesFromPrimShapeData(
  810. string primName, PrimitiveBaseShape primShape, float lod, bool convex,
  811. out List<Coord> coords, out List<Face> faces)
  812. {
  813. PrimMesh primMesh;
  814. coords = new List<Coord>();
  815. faces = new List<Face>();
  816. float pathShearX = primShape.PathShearX < 128 ? (float)primShape.PathShearX * 0.01f : (float)(primShape.PathShearX - 256) * 0.01f;
  817. float pathShearY = primShape.PathShearY < 128 ? (float)primShape.PathShearY * 0.01f : (float)(primShape.PathShearY - 256) * 0.01f;
  818. float pathBegin = (float)primShape.PathBegin * 2.0e-5f;
  819. float pathEnd = 1.0f - (float)primShape.PathEnd * 2.0e-5f;
  820. float pathScaleX = (float)(primShape.PathScaleX - 100) * 0.01f;
  821. float pathScaleY = (float)(primShape.PathScaleY - 100) * 0.01f;
  822. float profileBegin = (float)primShape.ProfileBegin * 2.0e-5f;
  823. float profileEnd = 1.0f - (float)primShape.ProfileEnd * 2.0e-5f;
  824. if (profileBegin < 0.0f)
  825. profileBegin = 0.0f;
  826. if (profileEnd < 0.02f)
  827. profileEnd = 0.02f;
  828. else if (profileEnd > 1.0f)
  829. profileEnd = 1.0f;
  830. if (profileBegin >= profileEnd)
  831. profileBegin = profileEnd - 0.02f;
  832. float profileHollow = (float)primShape.ProfileHollow * 2.0e-5f;
  833. if(convex)
  834. profileHollow = 0.0f;
  835. else if (profileHollow > 0.95f)
  836. profileHollow = 0.95f;
  837. int sides = 4;
  838. LevelOfDetail iLOD = (LevelOfDetail)lod;
  839. byte profshape = (byte)(primShape.ProfileCurve & 0x07);
  840. if (profshape == (byte)ProfileShape.EquilateralTriangle
  841. || profshape == (byte)ProfileShape.IsometricTriangle
  842. || profshape == (byte)ProfileShape.RightTriangle)
  843. sides = 3;
  844. else if (profshape == (byte)ProfileShape.Circle)
  845. {
  846. switch (iLOD)
  847. {
  848. case LevelOfDetail.High: sides = 24; break;
  849. case LevelOfDetail.Medium: sides = 12; break;
  850. case LevelOfDetail.Low: sides = 6; break;
  851. case LevelOfDetail.VeryLow: sides = 3; break;
  852. default: sides = 24; break;
  853. }
  854. }
  855. else if (profshape == (byte)ProfileShape.HalfCircle)
  856. { // half circle, prim is a sphere
  857. switch (iLOD)
  858. {
  859. case LevelOfDetail.High: sides = 24; break;
  860. case LevelOfDetail.Medium: sides = 12; break;
  861. case LevelOfDetail.Low: sides = 6; break;
  862. case LevelOfDetail.VeryLow: sides = 3; break;
  863. default: sides = 24; break;
  864. }
  865. profileBegin = 0.5f * profileBegin + 0.5f;
  866. profileEnd = 0.5f * profileEnd + 0.5f;
  867. }
  868. int hollowSides = sides;
  869. if (primShape.HollowShape == HollowShape.Circle)
  870. {
  871. switch (iLOD)
  872. {
  873. case LevelOfDetail.High: hollowSides = 24; break;
  874. case LevelOfDetail.Medium: hollowSides = 12; break;
  875. case LevelOfDetail.Low: hollowSides = 6; break;
  876. case LevelOfDetail.VeryLow: hollowSides = 3; break;
  877. default: hollowSides = 24; break;
  878. }
  879. }
  880. else if (primShape.HollowShape == HollowShape.Square)
  881. hollowSides = 4;
  882. else if (primShape.HollowShape == HollowShape.Triangle)
  883. {
  884. if (profshape == (byte)ProfileShape.HalfCircle)
  885. hollowSides = 6;
  886. else
  887. hollowSides = 3;
  888. }
  889. primMesh = new PrimMesh(sides, profileBegin, profileEnd, profileHollow, hollowSides);
  890. if (primMesh.errorMessage != null)
  891. if (primMesh.errorMessage.Length > 0)
  892. m_log.Error("[ERROR] " + primMesh.errorMessage);
  893. primMesh.topShearX = pathShearX;
  894. primMesh.topShearY = pathShearY;
  895. primMesh.pathCutBegin = pathBegin;
  896. primMesh.pathCutEnd = pathEnd;
  897. if (primShape.PathCurve == (byte)Extrusion.Straight || primShape.PathCurve == (byte) Extrusion.Flexible)
  898. {
  899. primMesh.twistBegin = (primShape.PathTwistBegin * 18) / 10;
  900. primMesh.twistEnd = (primShape.PathTwist * 18) / 10;
  901. primMesh.taperX = pathScaleX;
  902. primMesh.taperY = pathScaleY;
  903. #if SPAM
  904. m_log.Debug("****** PrimMesh Parameters (Linear) ******\n" + primMesh.ParamsToDisplayString());
  905. #endif
  906. try
  907. {
  908. primMesh.ExtrudeLinear();
  909. }
  910. catch (Exception ex)
  911. {
  912. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  913. return false;
  914. }
  915. }
  916. else
  917. {
  918. primMesh.holeSizeX = (200 - primShape.PathScaleX) * 0.01f;
  919. primMesh.holeSizeY = (200 - primShape.PathScaleY) * 0.01f;
  920. primMesh.radius = 0.01f * primShape.PathRadiusOffset;
  921. primMesh.revolutions = 1.0f + 0.015f * primShape.PathRevolutions;
  922. primMesh.skew = 0.01f * primShape.PathSkew;
  923. primMesh.twistBegin = (primShape.PathTwistBegin * 36) / 10;
  924. primMesh.twistEnd = (primShape.PathTwist * 36) / 10;
  925. primMesh.taperX = primShape.PathTaperX * 0.01f;
  926. primMesh.taperY = primShape.PathTaperY * 0.01f;
  927. if(profshape == (byte)ProfileShape.HalfCircle)
  928. {
  929. if(primMesh.holeSizeY < 0.01f)
  930. primMesh.holeSizeY = 0.01f;
  931. else if(primMesh.holeSizeY > 1.0f)
  932. primMesh.holeSizeY = 1.0f;
  933. }
  934. #if SPAM
  935. m_log.Debug("****** PrimMesh Parameters (Circular) ******\n" + primMesh.ParamsToDisplayString());
  936. #endif
  937. try
  938. {
  939. primMesh.ExtrudeCircular();
  940. }
  941. catch (Exception ex)
  942. {
  943. ReportPrimError("Extrusion failure: exception: " + ex.ToString(), primName, primMesh);
  944. return false;
  945. }
  946. }
  947. // primMesh.DumpRaw(baseDir, primName, "primMesh");
  948. coords = primMesh.coords;
  949. faces = primMesh.faces;
  950. return true;
  951. }
  952. public AMeshKey GetMeshUniqueKey(PrimitiveBaseShape primShape, Vector3 size, byte lod, bool convex)
  953. {
  954. AMeshKey key = new AMeshKey();
  955. Byte[] someBytes;
  956. key.hashB = 5181;
  957. key.hashC = 5181;
  958. ulong hash = 5381;
  959. if (primShape.SculptEntry)
  960. {
  961. key.uuid = primShape.SculptTexture;
  962. key.hashC = mdjb2(key.hashC, primShape.SculptType);
  963. key.hashC = mdjb2(key.hashC, primShape.PCode);
  964. }
  965. else
  966. {
  967. hash = mdjb2(hash, primShape.PathCurve);
  968. hash = mdjb2(hash, (byte)primShape.HollowShape);
  969. hash = mdjb2(hash, (byte)primShape.ProfileShape);
  970. hash = mdjb2(hash, primShape.PathBegin);
  971. hash = mdjb2(hash, primShape.PathEnd);
  972. hash = mdjb2(hash, primShape.PathScaleX);
  973. hash = mdjb2(hash, primShape.PathScaleY);
  974. hash = mdjb2(hash, primShape.PathShearX);
  975. key.hashA = hash;
  976. hash = key.hashB;
  977. hash = mdjb2(hash, primShape.PathShearY);
  978. hash = mdjb2(hash, (byte)primShape.PathTwist);
  979. hash = mdjb2(hash, (byte)primShape.PathTwistBegin);
  980. hash = mdjb2(hash, (byte)primShape.PathRadiusOffset);
  981. hash = mdjb2(hash, (byte)primShape.PathTaperX);
  982. hash = mdjb2(hash, (byte)primShape.PathTaperY);
  983. hash = mdjb2(hash, primShape.PathRevolutions);
  984. hash = mdjb2(hash, (byte)primShape.PathSkew);
  985. hash = mdjb2(hash, primShape.ProfileBegin);
  986. hash = mdjb2(hash, primShape.ProfileEnd);
  987. hash = mdjb2(hash, primShape.ProfileHollow);
  988. hash = mdjb2(hash, primShape.PCode);
  989. key.hashB = hash;
  990. }
  991. hash = key.hashC;
  992. hash = mdjb2(hash, lod);
  993. if (size == m_MeshUnitSize)
  994. {
  995. hash = hash << 8;
  996. hash |= 8;
  997. }
  998. else
  999. {
  1000. someBytes = size.GetBytes();
  1001. for (int i = 0; i < someBytes.Length; i++)
  1002. hash = mdjb2(hash, someBytes[i]);
  1003. hash = hash << 8;
  1004. }
  1005. if (convex)
  1006. hash |= 4;
  1007. if (primShape.SculptEntry)
  1008. {
  1009. hash |= 1;
  1010. if (primShape.SculptType == (byte)SculptType.Mesh)
  1011. hash |= 2;
  1012. }
  1013. key.hashC = hash;
  1014. return key;
  1015. }
  1016. private ulong mdjb2(ulong hash, byte c)
  1017. {
  1018. return ((hash << 5) + hash) + (ulong)c;
  1019. }
  1020. private ulong mdjb2(ulong hash, ushort c)
  1021. {
  1022. hash = ((hash << 5) + hash) + (ulong)((byte)c);
  1023. return ((hash << 5) + hash) + (ulong)(c >> 8);
  1024. }
  1025. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod)
  1026. {
  1027. return CreateMesh(primName, primShape, size, lod, false,false,false);
  1028. }
  1029. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical)
  1030. {
  1031. return CreateMesh(primName, primShape, size, lod, false,false,false);
  1032. }
  1033. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool shouldCache, bool convex, bool forOde)
  1034. {
  1035. return CreateMesh(primName, primShape, size, lod, false, false, false);
  1036. }
  1037. public IMesh GetMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex)
  1038. {
  1039. Mesh mesh = null;
  1040. if (size.X < 0.01f) size.X = 0.01f;
  1041. if (size.Y < 0.01f) size.Y = 0.01f;
  1042. if (size.Z < 0.01f) size.Z = 0.01f;
  1043. AMeshKey key = GetMeshUniqueKey(primShape, size, (byte)lod, convex);
  1044. lock (m_uniqueMeshes)
  1045. {
  1046. m_uniqueMeshes.TryGetValue(key, out mesh);
  1047. if (mesh != null)
  1048. {
  1049. mesh.RefCount++;
  1050. return mesh;
  1051. }
  1052. // try to find a identical mesh on meshs recently released
  1053. lock (m_uniqueReleasedMeshes)
  1054. {
  1055. m_uniqueReleasedMeshes.TryGetValue(key, out mesh);
  1056. if (mesh != null)
  1057. {
  1058. m_uniqueReleasedMeshes.Remove(key);
  1059. try
  1060. {
  1061. m_uniqueMeshes.Add(key, mesh);
  1062. }
  1063. catch { }
  1064. mesh.RefCount = 1;
  1065. return mesh;
  1066. }
  1067. }
  1068. }
  1069. return null;
  1070. }
  1071. private static Vector3 m_MeshUnitSize = new Vector3(1.0f, 1.0f, 1.0f);
  1072. public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod, bool isPhysical, bool convex, bool forOde)
  1073. {
  1074. #if SPAM
  1075. m_log.DebugFormat("[MESH]: Creating mesh for {0}", primName);
  1076. #endif
  1077. Mesh mesh = null;
  1078. if (size.X < 0.01f) size.X = 0.01f;
  1079. if (size.Y < 0.01f) size.Y = 0.01f;
  1080. if (size.Z < 0.01f) size.Z = 0.01f;
  1081. // try to find a identical mesh on meshs in use
  1082. AMeshKey key = GetMeshUniqueKey(primShape,size,(byte)lod, convex);
  1083. lock (m_uniqueMeshes)
  1084. {
  1085. m_uniqueMeshes.TryGetValue(key, out mesh);
  1086. if (mesh != null)
  1087. {
  1088. mesh.RefCount++;
  1089. return mesh;
  1090. }
  1091. // try to find a identical mesh on meshs recently released
  1092. lock (m_uniqueReleasedMeshes)
  1093. {
  1094. m_uniqueReleasedMeshes.TryGetValue(key, out mesh);
  1095. if (mesh != null)
  1096. {
  1097. m_uniqueReleasedMeshes.Remove(key);
  1098. try
  1099. {
  1100. m_uniqueMeshes.Add(key, mesh);
  1101. }
  1102. catch { }
  1103. mesh.RefCount = 1;
  1104. return mesh;
  1105. }
  1106. }
  1107. }
  1108. Mesh UnitMesh = null;
  1109. AMeshKey unitKey = GetMeshUniqueKey(primShape, m_MeshUnitSize, (byte)lod, convex);
  1110. lock (m_uniqueReleasedMeshes)
  1111. {
  1112. m_uniqueReleasedMeshes.TryGetValue(unitKey, out UnitMesh);
  1113. if (UnitMesh != null)
  1114. {
  1115. UnitMesh.RefCount = 1;
  1116. }
  1117. }
  1118. if (UnitMesh == null && primShape.SculptEntry && doMeshFileCache)
  1119. UnitMesh = GetFromFileCache(unitKey);
  1120. if (UnitMesh == null)
  1121. {
  1122. UnitMesh = CreateMeshFromPrimMesher(primName, primShape, lod, convex);
  1123. if (UnitMesh == null)
  1124. return null;
  1125. UnitMesh.DumpRaw(baseDir, unitKey.ToString(), "Z");
  1126. if (forOde)
  1127. {
  1128. // force pinned mem allocation
  1129. UnitMesh.PrepForOde();
  1130. }
  1131. else
  1132. UnitMesh.TrimExcess();
  1133. UnitMesh.Key = unitKey;
  1134. UnitMesh.RefCount = 1;
  1135. if (doMeshFileCache && primShape.SculptEntry)
  1136. StoreToFileCache(unitKey, UnitMesh);
  1137. lock (m_uniqueReleasedMeshes)
  1138. {
  1139. try
  1140. {
  1141. m_uniqueReleasedMeshes.Add(unitKey, UnitMesh);
  1142. }
  1143. catch { }
  1144. }
  1145. }
  1146. mesh = UnitMesh.Scale(size);
  1147. mesh.Key = key;
  1148. mesh.RefCount = 1;
  1149. lock (m_uniqueMeshes)
  1150. {
  1151. try
  1152. {
  1153. m_uniqueMeshes.Add(key, mesh);
  1154. }
  1155. catch { }
  1156. }
  1157. return mesh;
  1158. }
  1159. public void ReleaseMesh(IMesh imesh)
  1160. {
  1161. if (imesh == null)
  1162. return;
  1163. Mesh mesh = (Mesh)imesh;
  1164. lock (m_uniqueMeshes)
  1165. {
  1166. int curRefCount = mesh.RefCount;
  1167. curRefCount--;
  1168. if (curRefCount > 0)
  1169. {
  1170. mesh.RefCount = curRefCount;
  1171. return;
  1172. }
  1173. mesh.RefCount = 0;
  1174. m_uniqueMeshes.Remove(mesh.Key);
  1175. lock (m_uniqueReleasedMeshes)
  1176. {
  1177. try
  1178. {
  1179. m_uniqueReleasedMeshes.Add(mesh.Key, mesh);
  1180. }
  1181. catch { }
  1182. }
  1183. }
  1184. }
  1185. public void ExpireReleaseMeshs()
  1186. {
  1187. if (m_uniqueReleasedMeshes.Count == 0)
  1188. return;
  1189. List<Mesh> meshstodelete = new List<Mesh>();
  1190. int refcntr;
  1191. lock (m_uniqueReleasedMeshes)
  1192. {
  1193. foreach (Mesh m in m_uniqueReleasedMeshes.Values)
  1194. {
  1195. refcntr = m.RefCount;
  1196. refcntr--;
  1197. if (refcntr > -6)
  1198. m.RefCount = refcntr;
  1199. else
  1200. meshstodelete.Add(m);
  1201. }
  1202. foreach (Mesh m in meshstodelete)
  1203. {
  1204. m_uniqueReleasedMeshes.Remove(m.Key);
  1205. m.releaseBuildingMeshData();
  1206. m.releasePinned();
  1207. }
  1208. }
  1209. }
  1210. public void FileNames(AMeshKey key, out string dir,out string fullFileName)
  1211. {
  1212. string id = key.ToString();
  1213. string init = id.Substring(0, 1);
  1214. dir = System.IO.Path.Combine(cachePath, init);
  1215. fullFileName = System.IO.Path.Combine(dir, id);
  1216. }
  1217. public string FullFileName(AMeshKey key)
  1218. {
  1219. string id = key.ToString();
  1220. string init = id.Substring(0,1);
  1221. id = System.IO.Path.Combine(init, id);
  1222. id = System.IO.Path.Combine(cachePath, id);
  1223. return id;
  1224. }
  1225. private Mesh GetFromFileCache(AMeshKey key)
  1226. {
  1227. Mesh mesh = null;
  1228. string filename = FullFileName(key);
  1229. bool ok = true;
  1230. lock (diskLock)
  1231. {
  1232. if (File.Exists(filename))
  1233. {
  1234. try
  1235. {
  1236. using(FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  1237. {
  1238. // BinaryFormatter bformatter = new BinaryFormatter();
  1239. mesh = Mesh.FromStream(stream,key);
  1240. }
  1241. }
  1242. catch (Exception e)
  1243. {
  1244. ok = false;
  1245. m_log.ErrorFormat(
  1246. "[MESH CACHE]: Failed to get file {0}. Exception {1} {2}",
  1247. filename, e.Message, e.StackTrace);
  1248. }
  1249. try
  1250. {
  1251. if (mesh == null || !ok)
  1252. File.Delete(filename);
  1253. else
  1254. File.SetLastAccessTimeUtc(filename, DateTime.UtcNow);
  1255. }
  1256. catch
  1257. {
  1258. }
  1259. }
  1260. }
  1261. return mesh;
  1262. }
  1263. private void StoreToFileCache(AMeshKey key, Mesh mesh)
  1264. {
  1265. bool ok = false;
  1266. // Make sure the target cache directory exists
  1267. string dir = String.Empty;
  1268. string filename = String.Empty;
  1269. FileNames(key, out dir, out filename);
  1270. lock (diskLock)
  1271. {
  1272. Stream stream = null;
  1273. try
  1274. {
  1275. if (!Directory.Exists(dir))
  1276. {
  1277. Directory.CreateDirectory(dir);
  1278. }
  1279. stream = File.Open(filename, FileMode.Create);
  1280. ok = mesh.ToStream(stream);
  1281. }
  1282. catch (IOException e)
  1283. {
  1284. m_log.ErrorFormat(
  1285. "[MESH CACHE]: Failed to write file {0}. Exception {1} {2}.",
  1286. filename, e.Message, e.StackTrace);
  1287. ok = false;
  1288. }
  1289. finally
  1290. {
  1291. if(stream != null)
  1292. stream.Dispose();
  1293. }
  1294. if (!ok && File.Exists(filename))
  1295. {
  1296. try
  1297. {
  1298. File.Delete(filename);
  1299. }
  1300. catch (IOException e)
  1301. {
  1302. m_log.ErrorFormat(
  1303. "[MESH CACHE]: Failed to delete file {0}",filename);
  1304. }
  1305. }
  1306. }
  1307. }
  1308. public void ExpireFileCache()
  1309. {
  1310. if (!doCacheExpire)
  1311. return;
  1312. string controlfile = System.IO.Path.Combine(cachePath, "cntr");
  1313. lock (diskLock)
  1314. {
  1315. try
  1316. {
  1317. if (File.Exists(controlfile))
  1318. {
  1319. int ndeleted = 0;
  1320. int totalfiles = 0;
  1321. int ndirs = 0;
  1322. DateTime OlderTime = File.GetLastAccessTimeUtc(controlfile) - CacheExpire;
  1323. File.SetLastAccessTimeUtc(controlfile, DateTime.UtcNow);
  1324. foreach (string dir in Directory.GetDirectories(cachePath))
  1325. {
  1326. try
  1327. {
  1328. foreach (string file in Directory.GetFiles(dir))
  1329. {
  1330. try
  1331. {
  1332. if (File.GetLastAccessTimeUtc(file) < OlderTime)
  1333. {
  1334. File.Delete(file);
  1335. ndeleted++;
  1336. }
  1337. }
  1338. catch { }
  1339. totalfiles++;
  1340. }
  1341. }
  1342. catch { }
  1343. ndirs++;
  1344. }
  1345. if (ndeleted == 0)
  1346. m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, no expires",
  1347. totalfiles,ndirs);
  1348. else
  1349. m_log.InfoFormat("[MESH CACHE]: {0} Files in {1} cache folders, expired {2} files accessed before {3}",
  1350. totalfiles,ndirs, ndeleted, OlderTime.ToString());
  1351. }
  1352. else
  1353. {
  1354. m_log.Info("[MESH CACHE]: Expire delayed to next startup");
  1355. FileStream fs = File.Create(controlfile,4096,FileOptions.WriteThrough);
  1356. fs.Close();
  1357. }
  1358. }
  1359. catch { }
  1360. }
  1361. }
  1362. }
  1363. }