1
0

Mesh.cs 20 KB

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