Meshmerizer.cs 61 KB

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