Mesh.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. using System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Runtime.InteropServices;
  31. using OpenSim.Region.PhysicsModules.SharedBase;
  32. using PrimMesher;
  33. using OpenMetaverse;
  34. using System.Runtime.Serialization;
  35. using System.Runtime.Serialization.Formatters.Binary;
  36. namespace OpenSim.Region.PhysicsModule.ubODEMeshing
  37. {
  38. public class MeshBuildingData
  39. {
  40. public Dictionary<Vertex, int> m_vertices;
  41. public List<Triangle> m_triangles;
  42. public float m_obbXmin;
  43. public float m_obbXmax;
  44. public float m_obbYmin;
  45. public float m_obbYmax;
  46. public float m_obbZmin;
  47. public float m_obbZmax;
  48. public Vector3 m_centroid;
  49. public int m_centroidDiv;
  50. }
  51. [Serializable()]
  52. public class Mesh : IMesh
  53. {
  54. float[] vertices;
  55. int[] indexes;
  56. Vector3 m_obb;
  57. Vector3 m_obboffset;
  58. [NonSerialized()]
  59. MeshBuildingData m_bdata;
  60. [NonSerialized()]
  61. GCHandle vhandler;
  62. [NonSerialized()]
  63. GCHandle ihandler;
  64. [NonSerialized()]
  65. IntPtr m_verticesPtr = IntPtr.Zero;
  66. [NonSerialized()]
  67. IntPtr m_indicesPtr = IntPtr.Zero;
  68. [NonSerialized()]
  69. int m_vertexCount = 0;
  70. [NonSerialized()]
  71. int m_indexCount = 0;
  72. public int RefCount { get; set; }
  73. public AMeshKey Key { get; set; }
  74. private class vertexcomp : IEqualityComparer<Vertex>
  75. {
  76. public bool Equals(Vertex v1, Vertex v2)
  77. {
  78. if (v1.X == v2.X && v1.Y == v2.Y && v1.Z == v2.Z)
  79. return true;
  80. else
  81. return false;
  82. }
  83. public int GetHashCode(Vertex v)
  84. {
  85. int a = v.X.GetHashCode();
  86. int b = v.Y.GetHashCode();
  87. int c = v.Z.GetHashCode();
  88. return (a << 16) ^ (b << 8) ^ c;
  89. }
  90. }
  91. public Mesh()
  92. {
  93. vertexcomp vcomp = new vertexcomp();
  94. m_bdata = new MeshBuildingData();
  95. m_bdata.m_vertices = new Dictionary<Vertex, int>(vcomp);
  96. m_bdata.m_triangles = new List<Triangle>();
  97. m_bdata.m_centroid = Vector3.Zero;
  98. m_bdata.m_centroidDiv = 0;
  99. m_bdata.m_obbXmin = float.MaxValue;
  100. m_bdata.m_obbXmax = float.MinValue;
  101. m_bdata.m_obbYmin = float.MaxValue;
  102. m_bdata.m_obbYmax = float.MinValue;
  103. m_bdata.m_obbZmin = float.MaxValue;
  104. m_bdata.m_obbZmax = float.MinValue;
  105. m_obb = new Vector3(0.5f, 0.5f, 0.5f);
  106. m_obboffset = Vector3.Zero;
  107. }
  108. public Mesh Scale(Vector3 scale)
  109. {
  110. if (m_verticesPtr == null || m_indicesPtr == null)
  111. return null;
  112. Mesh result = new Mesh();
  113. float x = scale.X;
  114. float y = scale.Y;
  115. float z = scale.Z;
  116. result.m_obb.X = m_obb.X * x;
  117. result.m_obb.Y = m_obb.Y * y;
  118. result.m_obb.Z = m_obb.Z * z;
  119. result.m_obboffset.X = m_obboffset.X * x;
  120. result.m_obboffset.Y = m_obboffset.Y * y;
  121. result.m_obboffset.Z = m_obboffset.Z * z;
  122. result.vertices = new float[vertices.Length];
  123. int j = 0;
  124. for (int i = 0; i < m_vertexCount; i++)
  125. {
  126. result.vertices[j] = vertices[j] * x;
  127. j++;
  128. result.vertices[j] = vertices[j] * y;
  129. j++;
  130. result.vertices[j] = vertices[j] * z;
  131. j++;
  132. }
  133. result.indexes = new int[indexes.Length];
  134. indexes.CopyTo(result.indexes,0);
  135. result.pinMemory();
  136. return result;
  137. }
  138. public Mesh Clone()
  139. {
  140. Mesh result = new Mesh();
  141. if (m_bdata != null)
  142. {
  143. result.m_bdata = new MeshBuildingData();
  144. foreach (Triangle t in m_bdata.m_triangles)
  145. {
  146. result.Add(new Triangle(t.v1.Clone(), t.v2.Clone(), t.v3.Clone()));
  147. }
  148. result.m_bdata.m_centroid = m_bdata.m_centroid;
  149. result.m_bdata.m_centroidDiv = m_bdata.m_centroidDiv;
  150. result.m_bdata.m_obbXmin = m_bdata.m_obbXmin;
  151. result.m_bdata.m_obbXmax = m_bdata.m_obbXmax;
  152. result.m_bdata.m_obbYmin = m_bdata.m_obbYmin;
  153. result.m_bdata.m_obbYmax = m_bdata.m_obbYmax;
  154. result.m_bdata.m_obbZmin = m_bdata.m_obbZmin;
  155. result.m_bdata.m_obbZmax = m_bdata.m_obbZmax;
  156. }
  157. result.m_obb = m_obb;
  158. result.m_obboffset = m_obboffset;
  159. return result;
  160. }
  161. public void addVertexLStats(Vertex v)
  162. {
  163. float x = v.X;
  164. float y = v.Y;
  165. float z = v.Z;
  166. m_bdata.m_centroid.X += x;
  167. m_bdata.m_centroid.Y += y;
  168. m_bdata.m_centroid.Z += z;
  169. m_bdata.m_centroidDiv++;
  170. if (x > m_bdata.m_obbXmax)
  171. m_bdata.m_obbXmax = x;
  172. else if (x < m_bdata.m_obbXmin)
  173. m_bdata.m_obbXmin = x;
  174. if (y > m_bdata.m_obbYmax)
  175. m_bdata.m_obbYmax = y;
  176. else if (y < m_bdata.m_obbYmin)
  177. m_bdata.m_obbYmin = y;
  178. if (z > m_bdata.m_obbZmax)
  179. m_bdata.m_obbZmax = z;
  180. else if (z < m_bdata.m_obbZmin)
  181. m_bdata.m_obbZmin = z;
  182. }
  183. public void Add(Triangle triangle)
  184. {
  185. if (m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero)
  186. throw new NotSupportedException("Attempt to Add to a pinned Mesh");
  187. triangle.v1.X = (float)Math.Round(triangle.v1.X, 6);
  188. triangle.v1.Y = (float)Math.Round(triangle.v1.Y, 6);
  189. triangle.v1.Z = (float)Math.Round(triangle.v1.Z, 6);
  190. triangle.v2.X = (float)Math.Round(triangle.v2.X, 6);
  191. triangle.v2.Y = (float)Math.Round(triangle.v2.Y, 6);
  192. triangle.v2.Z = (float)Math.Round(triangle.v2.Z, 6);
  193. triangle.v3.X = (float)Math.Round(triangle.v3.X, 6);
  194. triangle.v3.Y = (float)Math.Round(triangle.v3.Y, 6);
  195. triangle.v3.Z = (float)Math.Round(triangle.v3.Z, 6);
  196. if ((triangle.v1.X == triangle.v2.X && triangle.v1.Y == triangle.v2.Y && triangle.v1.Z == triangle.v2.Z)
  197. || (triangle.v1.X == triangle.v3.X && triangle.v1.Y == triangle.v3.Y && triangle.v1.Z == triangle.v3.Z)
  198. || (triangle.v2.X == triangle.v3.X && triangle.v2.Y == triangle.v3.Y && triangle.v2.Z == triangle.v3.Z)
  199. )
  200. {
  201. return;
  202. }
  203. if (m_bdata.m_vertices.Count == 0)
  204. {
  205. m_bdata.m_centroidDiv = 0;
  206. m_bdata.m_centroid = Vector3.Zero;
  207. }
  208. if (!m_bdata.m_vertices.ContainsKey(triangle.v1))
  209. {
  210. m_bdata.m_vertices[triangle.v1] = m_bdata.m_vertices.Count;
  211. addVertexLStats(triangle.v1);
  212. }
  213. if (!m_bdata.m_vertices.ContainsKey(triangle.v2))
  214. {
  215. m_bdata.m_vertices[triangle.v2] = m_bdata.m_vertices.Count;
  216. addVertexLStats(triangle.v2);
  217. }
  218. if (!m_bdata.m_vertices.ContainsKey(triangle.v3))
  219. {
  220. m_bdata.m_vertices[triangle.v3] = m_bdata.m_vertices.Count;
  221. addVertexLStats(triangle.v3);
  222. }
  223. m_bdata.m_triangles.Add(triangle);
  224. }
  225. public Vector3 GetCentroid()
  226. {
  227. return m_obboffset;
  228. }
  229. public Vector3 GetOBB()
  230. {
  231. return m_obb;
  232. float x, y, z;
  233. if (m_bdata.m_centroidDiv > 0)
  234. {
  235. x = (m_bdata.m_obbXmax - m_bdata.m_obbXmin) * 0.5f;
  236. y = (m_bdata.m_obbYmax - m_bdata.m_obbYmin) * 0.5f;
  237. z = (m_bdata.m_obbZmax - m_bdata.m_obbZmin) * 0.5f;
  238. }
  239. else // ??
  240. {
  241. x = 0.5f;
  242. y = 0.5f;
  243. z = 0.5f;
  244. }
  245. return new Vector3(x, y, z);
  246. }
  247. public List<Vector3> getVertexList()
  248. {
  249. List<Vector3> result = new List<Vector3>();
  250. foreach (Vertex v in m_bdata.m_vertices.Keys)
  251. {
  252. result.Add(new Vector3(v.X, v.Y, v.Z));
  253. }
  254. return result;
  255. }
  256. public float[] getVertexListAsFloat()
  257. {
  258. if (m_bdata.m_vertices == null)
  259. throw new NotSupportedException();
  260. float[] result = new float[m_bdata.m_vertices.Count * 3];
  261. foreach (KeyValuePair<Vertex, int> kvp in m_bdata.m_vertices)
  262. {
  263. Vertex v = kvp.Key;
  264. int i = kvp.Value;
  265. result[3 * i + 0] = v.X;
  266. result[3 * i + 1] = v.Y;
  267. result[3 * i + 2] = v.Z;
  268. }
  269. return result;
  270. }
  271. public float[] getVertexListAsFloatLocked()
  272. {
  273. return null;
  274. }
  275. public void getVertexListAsPtrToFloatArray(out IntPtr _vertices, out int vertexStride, out int vertexCount)
  276. {
  277. // A vertex is 3 floats
  278. vertexStride = 3 * sizeof(float);
  279. // If there isn't an unmanaged array allocated yet, do it now
  280. if (m_verticesPtr == IntPtr.Zero && m_bdata != null)
  281. {
  282. vertices = getVertexListAsFloat();
  283. // Each vertex is 3 elements (floats)
  284. m_vertexCount = vertices.Length / 3;
  285. vhandler = GCHandle.Alloc(vertices, GCHandleType.Pinned);
  286. m_verticesPtr = vhandler.AddrOfPinnedObject();
  287. GC.AddMemoryPressure(Buffer.ByteLength(vertices));
  288. }
  289. _vertices = m_verticesPtr;
  290. vertexCount = m_vertexCount;
  291. }
  292. public int[] getIndexListAsInt()
  293. {
  294. if (m_bdata.m_triangles == null)
  295. throw new NotSupportedException();
  296. int[] result = new int[m_bdata.m_triangles.Count * 3];
  297. for (int i = 0; i < m_bdata.m_triangles.Count; i++)
  298. {
  299. Triangle t = m_bdata.m_triangles[i];
  300. result[3 * i + 0] = m_bdata.m_vertices[t.v1];
  301. result[3 * i + 1] = m_bdata.m_vertices[t.v2];
  302. result[3 * i + 2] = m_bdata.m_vertices[t.v3];
  303. }
  304. return result;
  305. }
  306. /// <summary>
  307. /// creates a list of index values that defines triangle faces. THIS METHOD FREES ALL NON-PINNED MESH DATA
  308. /// </summary>
  309. /// <returns></returns>
  310. public int[] getIndexListAsIntLocked()
  311. {
  312. return null;
  313. }
  314. public void getIndexListAsPtrToIntArray(out IntPtr indices, out int triStride, out int indexCount)
  315. {
  316. // If there isn't an unmanaged array allocated yet, do it now
  317. if (m_indicesPtr == IntPtr.Zero && m_bdata != null)
  318. {
  319. indexes = getIndexListAsInt();
  320. m_indexCount = indexes.Length;
  321. ihandler = GCHandle.Alloc(indexes, GCHandleType.Pinned);
  322. m_indicesPtr = ihandler.AddrOfPinnedObject();
  323. GC.AddMemoryPressure(Buffer.ByteLength(indexes));
  324. }
  325. // A triangle is 3 ints (indices)
  326. triStride = 3 * sizeof(int);
  327. indices = m_indicesPtr;
  328. indexCount = m_indexCount;
  329. }
  330. public void releasePinned()
  331. {
  332. if (m_verticesPtr != IntPtr.Zero)
  333. {
  334. vhandler.Free();
  335. vertices = null;
  336. m_verticesPtr = IntPtr.Zero;
  337. }
  338. if (m_indicesPtr != IntPtr.Zero)
  339. {
  340. ihandler.Free();
  341. indexes = null;
  342. m_indicesPtr = IntPtr.Zero;
  343. }
  344. }
  345. /// <summary>
  346. /// frees up the source mesh data to minimize memory - call this method after calling get*Locked() functions
  347. /// </summary>
  348. public void releaseSourceMeshData()
  349. {
  350. if (m_bdata != null)
  351. {
  352. m_bdata.m_triangles = null;
  353. m_bdata.m_vertices = null;
  354. }
  355. }
  356. public void releaseBuildingMeshData()
  357. {
  358. if (m_bdata != null)
  359. {
  360. m_bdata.m_triangles = null;
  361. m_bdata.m_vertices = null;
  362. m_bdata = null;
  363. }
  364. }
  365. public void Append(IMesh newMesh)
  366. {
  367. if (m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero)
  368. throw new NotSupportedException("Attempt to Append to a pinned Mesh");
  369. if (!(newMesh is Mesh))
  370. return;
  371. foreach (Triangle t in ((Mesh)newMesh).m_bdata.m_triangles)
  372. Add(t);
  373. }
  374. // Do a linear transformation of mesh.
  375. public void TransformLinear(float[,] matrix, float[] offset)
  376. {
  377. if (m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero)
  378. throw new NotSupportedException("Attempt to TransformLinear a pinned Mesh");
  379. foreach (Vertex v in m_bdata.m_vertices.Keys)
  380. {
  381. if (v == null)
  382. continue;
  383. float x, y, z;
  384. x = v.X*matrix[0, 0] + v.Y*matrix[1, 0] + v.Z*matrix[2, 0];
  385. y = v.X*matrix[0, 1] + v.Y*matrix[1, 1] + v.Z*matrix[2, 1];
  386. z = v.X*matrix[0, 2] + v.Y*matrix[1, 2] + v.Z*matrix[2, 2];
  387. v.X = x + offset[0];
  388. v.Y = y + offset[1];
  389. v.Z = z + offset[2];
  390. }
  391. }
  392. public void DumpRaw(String path, String name, String title)
  393. {
  394. if (path == null)
  395. return;
  396. if (m_bdata == null)
  397. return;
  398. String fileName = name + "_" + title + ".raw";
  399. String completePath = System.IO.Path.Combine(path, fileName);
  400. StreamWriter sw = new StreamWriter(completePath);
  401. foreach (Triangle t in m_bdata.m_triangles)
  402. {
  403. String s = t.ToStringRaw();
  404. sw.WriteLine(s);
  405. }
  406. sw.Close();
  407. }
  408. public void TrimExcess()
  409. {
  410. m_bdata.m_triangles.TrimExcess();
  411. }
  412. public void pinMemory()
  413. {
  414. m_vertexCount = vertices.Length / 3;
  415. vhandler = GCHandle.Alloc(vertices, GCHandleType.Pinned);
  416. m_verticesPtr = vhandler.AddrOfPinnedObject();
  417. GC.AddMemoryPressure(Buffer.ByteLength(vertices));
  418. m_indexCount = indexes.Length;
  419. ihandler = GCHandle.Alloc(indexes, GCHandleType.Pinned);
  420. m_indicesPtr = ihandler.AddrOfPinnedObject();
  421. GC.AddMemoryPressure(Buffer.ByteLength(indexes));
  422. }
  423. public void PrepForOde()
  424. {
  425. // If there isn't an unmanaged array allocated yet, do it now
  426. if (m_verticesPtr == IntPtr.Zero)
  427. vertices = getVertexListAsFloat();
  428. // If there isn't an unmanaged array allocated yet, do it now
  429. if (m_indicesPtr == IntPtr.Zero)
  430. indexes = getIndexListAsInt();
  431. pinMemory();
  432. float x, y, z;
  433. if (m_bdata.m_centroidDiv > 0)
  434. {
  435. m_obboffset = new Vector3(m_bdata.m_centroid.X / m_bdata.m_centroidDiv, m_bdata.m_centroid.Y / m_bdata.m_centroidDiv, m_bdata.m_centroid.Z / m_bdata.m_centroidDiv);
  436. x = (m_bdata.m_obbXmax - m_bdata.m_obbXmin) * 0.5f;
  437. y = (m_bdata.m_obbYmax - m_bdata.m_obbYmin) * 0.5f;
  438. z = (m_bdata.m_obbZmax - m_bdata.m_obbZmin) * 0.5f;
  439. }
  440. else
  441. {
  442. m_obboffset = Vector3.Zero;
  443. x = 0.5f;
  444. y = 0.5f;
  445. z = 0.5f;
  446. }
  447. m_obb = new Vector3(x, y, z);
  448. releaseBuildingMeshData();
  449. }
  450. public bool ToStream(Stream st)
  451. {
  452. if (m_indicesPtr == IntPtr.Zero || m_verticesPtr == IntPtr.Zero)
  453. return false;
  454. BinaryWriter bw = new BinaryWriter(st);
  455. bool ok = true;
  456. try
  457. {
  458. bw.Write(m_vertexCount);
  459. bw.Write(m_indexCount);
  460. for (int i = 0; i < 3 * m_vertexCount; i++)
  461. bw.Write(vertices[i]);
  462. for (int i = 0; i < m_indexCount; i++)
  463. bw.Write(indexes[i]);
  464. bw.Write(m_obb.X);
  465. bw.Write(m_obb.Y);
  466. bw.Write(m_obb.Z);
  467. bw.Write(m_obboffset.X);
  468. bw.Write(m_obboffset.Y);
  469. bw.Write(m_obboffset.Z);
  470. }
  471. catch
  472. {
  473. ok = false;
  474. }
  475. if (bw != null)
  476. {
  477. bw.Flush();
  478. bw.Close();
  479. }
  480. return ok;
  481. }
  482. public static Mesh FromStream(Stream st, AMeshKey key)
  483. {
  484. Mesh mesh = new Mesh();
  485. mesh.releaseBuildingMeshData();
  486. BinaryReader br = new BinaryReader(st);
  487. bool ok = true;
  488. try
  489. {
  490. mesh.m_vertexCount = br.ReadInt32();
  491. mesh.m_indexCount = br.ReadInt32();
  492. int n = 3 * mesh.m_vertexCount;
  493. mesh.vertices = new float[n];
  494. for (int i = 0; i < n; i++)
  495. mesh.vertices[i] = br.ReadSingle();
  496. mesh.indexes = new int[mesh.m_indexCount];
  497. for (int i = 0; i < mesh.m_indexCount; i++)
  498. mesh.indexes[i] = br.ReadInt32();
  499. mesh.m_obb.X = br.ReadSingle();
  500. mesh.m_obb.Y = br.ReadSingle();
  501. mesh.m_obb.Z = br.ReadSingle();
  502. mesh.m_obboffset.X = br.ReadSingle();
  503. mesh.m_obboffset.Y = br.ReadSingle();
  504. mesh.m_obboffset.Z = br.ReadSingle();
  505. }
  506. catch
  507. {
  508. ok = false;
  509. }
  510. br.Close();
  511. if (ok)
  512. {
  513. mesh.pinMemory();
  514. mesh.Key = key;
  515. mesh.RefCount = 1;
  516. return mesh;
  517. }
  518. mesh.vertices = null;
  519. mesh.indexes = null;
  520. return null;
  521. }
  522. }
  523. }