Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

674 lines
26 KiB

  1. /************************************************************************************
  2. Filename : ONSPPropagationGeometry.cs
  3. Content : Geometry Functions
  4. Attach to a game object with meshes and material scripts to create geometry
  5. NOTE: ensure that Oculus Spatialization is enabled for AudioSource components
  6. Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
  7. Licensed under the Oculus SDK Version 3.5 (the "License");
  8. you may not use the Oculus SDK except in compliance with the License,
  9. which is provided at the time of installation or download, or which
  10. otherwise accompanies this software in either electronic or hard copy form.
  11. You may obtain a copy of the License at
  12. https://developer.oculus.com/licenses/sdk-3.5/
  13. Unless required by applicable law or agreed to in writing, the Oculus SDK
  14. distributed under the License is distributed on an "AS IS" BASIS,
  15. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. See the License for the specific language governing permissions and
  17. limitations under the License.
  18. ************************************************************************************/
  19. #define INCLUDE_TERRAIN_TREES
  20. using UnityEngine;
  21. using System;
  22. using System.Collections.Generic;
  23. using Oculus.Spatializer.Propagation;
  24. public class ONSPPropagationGeometry : MonoBehaviour
  25. {
  26. public static string GeometryAssetDirectory = "AudioGeometry";
  27. public static string GeometryAssetPath { get { return Application.streamingAssetsPath + "/" + GeometryAssetDirectory; } }
  28. //-------
  29. // PUBLIC
  30. /// The path to the serialized mesh file that holds the preprocessed mesh geometry.
  31. public string filePathRelative = "";
  32. public string filePath { get { return GeometryAssetPath + "/" + filePathRelative; } }
  33. public bool fileEnabled = false;
  34. public bool includeChildMeshes = true;
  35. //-------
  36. // PRIVATE
  37. private IntPtr geometryHandle = IntPtr.Zero;
  38. //-------
  39. // PUBLIC STATIC
  40. public static int OSPSuccess = 0;
  41. public const string GEOMETRY_FILE_EXTENSION = "ovramesh";
  42. private static string GetPath(Transform current)
  43. {
  44. if (current.parent == null)
  45. return current.gameObject.scene.name + "/" + current.name;
  46. return GetPath(current.parent) + "-" + current.name;
  47. }
  48. /// <summary>
  49. /// If script is attached to a gameobject, it will try to create geometry
  50. /// </summary>
  51. void Awake()
  52. {
  53. CreatePropagationGeometry();
  54. }
  55. /// <summary>
  56. /// Call this function to create geometry handle
  57. /// </summary>
  58. void CreatePropagationGeometry()
  59. {
  60. // Create Geometry
  61. if (ONSPPropagation.Interface.CreateAudioGeometry(out geometryHandle) != OSPSuccess)
  62. {
  63. throw new Exception("Unable to create geometry handle");
  64. }
  65. // Upload Mesh
  66. if (filePath != null && filePath.Length != 0 && fileEnabled && Application.isPlaying)
  67. {
  68. if (!ReadFile())
  69. {
  70. Debug.LogError("Failed to read file, attempting to regenerate audio geometry");
  71. // We should not try to upload data dynamically if data already exists
  72. UploadGeometry();
  73. }
  74. }
  75. else
  76. {
  77. UploadGeometry();
  78. }
  79. }
  80. /// <summary>
  81. /// Update the world transform (TODO)
  82. /// </summary>
  83. private void Update()
  84. {
  85. if (geometryHandle == IntPtr.Zero)
  86. return;
  87. Matrix4x4 m = transform.localToWorldMatrix;
  88. // Note: flip Z to convert from left-handed (+Z forward) to right-handed (+Z backward)
  89. float[] matrix = { m[0,0], m[1,0], -m[2,0], m[3,0],
  90. m[0,1], m[1,1], -m[2,1], m[3,1],
  91. m[0,2], m[1,2], -m[2,2], m[3,2],
  92. m[0,3], m[1,3], -m[2,3], m[3,3] };
  93. ONSPPropagation.Interface.AudioGeometrySetTransform(geometryHandle, matrix);
  94. }
  95. /// <summary>
  96. /// Call when destroyed
  97. /// </summary>
  98. private void OnDestroy()
  99. {
  100. // DESTROY GEOMETRY
  101. if (geometryHandle != IntPtr.Zero && ONSPPropagation.Interface.DestroyAudioGeometry(geometryHandle) != OSPSuccess)
  102. {
  103. throw new Exception("Unable to destroy geometry");
  104. }
  105. geometryHandle = IntPtr.Zero;
  106. }
  107. //
  108. // FUNCTIONS FOR UPLOADING MESHES VIA GAME OBJECT
  109. //
  110. static int terrainDecimation = 4;
  111. private struct MeshMaterial
  112. {
  113. public MeshFilter meshFilter;
  114. public ONSPPropagationMaterial[] materials;
  115. }
  116. private struct TerrainMaterial
  117. {
  118. public Terrain terrain;
  119. public ONSPPropagationMaterial[] materials;
  120. public Mesh[] treePrototypeMeshes;
  121. }
  122. private static void traverseMeshHierarchy(GameObject obj, ONSPPropagationMaterial[] currentMaterials, bool includeChildren,
  123. List<MeshMaterial> meshMaterials, List<TerrainMaterial> terrainMaterials, bool ignoreStatic, ref int ignoredMeshCount)
  124. {
  125. if (!obj.activeInHierarchy)
  126. return;
  127. MeshFilter[] meshes = obj.GetComponents<MeshFilter>();
  128. Terrain[] terrains = obj.GetComponents<Terrain>();
  129. ONSPPropagationMaterial[] materials = obj.GetComponents<ONSPPropagationMaterial>();
  130. // Initialize the current material array to a new array if there are any new materials.
  131. if (materials != null && materials.Length > 0)
  132. {
  133. // Determine the length of the material array.
  134. int maxLength = materials.Length;
  135. if (currentMaterials != null)
  136. maxLength = Math.Max(maxLength, currentMaterials.Length);
  137. ONSPPropagationMaterial[] newMaterials = new ONSPPropagationMaterial[maxLength];
  138. // Copy the previous materials into the new array.
  139. if (currentMaterials != null)
  140. {
  141. for (int i = materials.Length; i < maxLength; i++)
  142. newMaterials[i] = currentMaterials[i];
  143. }
  144. currentMaterials = newMaterials;
  145. // Copy the current materials.
  146. for (int i = 0; i < materials.Length; i++)
  147. currentMaterials[i] = materials[i];
  148. }
  149. // Gather the meshes.
  150. foreach (MeshFilter meshFilter in meshes)
  151. {
  152. Mesh mesh = meshFilter.sharedMesh;
  153. if (mesh == null)
  154. continue;
  155. if (ignoreStatic && !mesh.isReadable)
  156. {
  157. Debug.LogWarning("Mesh: " + meshFilter.gameObject.name + " not readable, cannot be static.", meshFilter.gameObject);
  158. ++ignoredMeshCount;
  159. continue;
  160. }
  161. MeshMaterial m = new MeshMaterial();
  162. m.meshFilter = meshFilter;
  163. m.materials = currentMaterials;
  164. meshMaterials.Add(m);
  165. }
  166. // Gather the terrains.
  167. foreach (Terrain terrain in terrains)
  168. {
  169. TerrainMaterial m = new TerrainMaterial();
  170. m.terrain = terrain;
  171. m.materials = currentMaterials;
  172. terrainMaterials.Add(m);
  173. }
  174. // Traverse to the child objects.
  175. if (includeChildren)
  176. {
  177. foreach (Transform child in obj.transform)
  178. {
  179. if (child.GetComponent<ONSPPropagationGeometry>() == null) // skip children which have their own component
  180. traverseMeshHierarchy(child.gameObject, currentMaterials, includeChildren, meshMaterials, terrainMaterials, ignoreStatic, ref ignoredMeshCount);
  181. }
  182. }
  183. }
  184. //
  185. // CALL THIS ON GAME OBJECT THAT HAS GEOMETRY ATTACHED TO IT
  186. //
  187. private int uploadMesh(IntPtr geometryHandle, GameObject meshObject, Matrix4x4 worldToLocal)
  188. {
  189. int unused = 0;
  190. return uploadMesh(geometryHandle, meshObject, worldToLocal, false, ref unused);
  191. }
  192. private int uploadMesh(IntPtr geometryHandle, GameObject meshObject, Matrix4x4 worldToLocal, bool ignoreStatic, ref int ignoredMeshCount)
  193. {
  194. // Get the child mesh objects.
  195. List<MeshMaterial> meshes = new List<MeshMaterial>();
  196. List<TerrainMaterial> terrains = new List<TerrainMaterial>();
  197. traverseMeshHierarchy(meshObject, null, includeChildMeshes, meshes, terrains, ignoreStatic, ref ignoredMeshCount);
  198. #if INCLUDE_TERRAIN_TREES
  199. // TODO: expose tree material
  200. ONSPPropagationMaterial[] treeMaterials = new ONSPPropagationMaterial[1];
  201. treeMaterials[0] = gameObject.AddComponent<ONSPPropagationMaterial>();
  202. #if true
  203. treeMaterials[0].SetPreset(ONSPPropagationMaterial.Preset.Foliage);
  204. #else
  205. // Custom material that is highly transmissive
  206. treeMaterials[0].absorption.points = new List<ONSPPropagationMaterial.Point>{
  207. new ONSPPropagationMaterial.Point(125f, .03f),
  208. new ONSPPropagationMaterial.Point(250f, .06f),
  209. new ONSPPropagationMaterial.Point(500f, .11f),
  210. new ONSPPropagationMaterial.Point(1000f, .17f),
  211. new ONSPPropagationMaterial.Point(2000f, .27f),
  212. new ONSPPropagationMaterial.Point(4000f, .31f) };
  213. treeMaterials[0].scattering.points = new List<ONSPPropagationMaterial.Point>{
  214. new ONSPPropagationMaterial.Point(125f, .20f),
  215. new ONSPPropagationMaterial.Point(250f, .3f),
  216. new ONSPPropagationMaterial.Point(500f, .4f),
  217. new ONSPPropagationMaterial.Point(1000f, .5f),
  218. new ONSPPropagationMaterial.Point(2000f, .7f),
  219. new ONSPPropagationMaterial.Point(4000f, .8f) };
  220. treeMaterials[0].transmission.points = new List<ONSPPropagationMaterial.Point>(){
  221. new ONSPPropagationMaterial.Point(125f, .95f),
  222. new ONSPPropagationMaterial.Point(250f, .92f),
  223. new ONSPPropagationMaterial.Point(500f, .87f),
  224. new ONSPPropagationMaterial.Point(1000f, .81f),
  225. new ONSPPropagationMaterial.Point(2000f, .71f),
  226. new ONSPPropagationMaterial.Point(4000f, .67f) };
  227. #endif
  228. #endif
  229. //***********************************************************************
  230. // Count the number of vertices and indices.
  231. int totalVertexCount = 0;
  232. uint totalIndexCount = 0;
  233. int totalFaceCount = 0;
  234. int totalMaterialCount = 0;
  235. foreach (MeshMaterial m in meshes)
  236. {
  237. updateCountsForMesh(ref totalVertexCount, ref totalIndexCount, ref totalFaceCount, ref totalMaterialCount, m.meshFilter.sharedMesh);
  238. }
  239. for (int i = 0; i < terrains.Count; ++i)
  240. {
  241. TerrainMaterial t = terrains[i];
  242. TerrainData terrain = t.terrain.terrainData;
  243. #if UNITY_2019_3_OR_NEWER
  244. int w = terrain.heightmapResolution;
  245. int h = terrain.heightmapResolution;
  246. #else
  247. int w = terrain.heightmapWidth;
  248. int h = terrain.heightmapHeight;
  249. #endif
  250. int wRes = (w - 1) / terrainDecimation + 1;
  251. int hRes = (h - 1) / terrainDecimation + 1;
  252. int vertexCount = wRes * hRes;
  253. int indexCount = (wRes - 1) * (hRes - 1) * 6;
  254. totalMaterialCount++;
  255. totalVertexCount += vertexCount;
  256. totalIndexCount += (uint)indexCount;
  257. totalFaceCount += indexCount / 3;
  258. #if INCLUDE_TERRAIN_TREES
  259. TreePrototype[] treePrototypes = terrain.treePrototypes;
  260. t.treePrototypeMeshes = new Mesh[treePrototypes.Length];
  261. // assume the sharedMesh with the lowest vertex is the lowest LOD
  262. for (int j = 0; j < treePrototypes.Length; ++j)
  263. {
  264. GameObject prefab = treePrototypes[j].prefab;
  265. MeshFilter[] meshFilters = prefab.GetComponentsInChildren<MeshFilter>();
  266. int minVertexCount = int.MaxValue;
  267. int index = -1;
  268. for (int k = 0; k < meshFilters.Length; ++k)
  269. {
  270. int count = meshFilters[k].sharedMesh.vertexCount;
  271. if (count < minVertexCount)
  272. {
  273. minVertexCount = count;
  274. index = k;
  275. }
  276. }
  277. t.treePrototypeMeshes[j] = meshFilters[index].sharedMesh;
  278. }
  279. TreeInstance[] trees = terrain.treeInstances;
  280. foreach (TreeInstance tree in trees)
  281. {
  282. updateCountsForMesh(ref totalVertexCount, ref totalIndexCount, ref totalFaceCount, ref totalMaterialCount, t.treePrototypeMeshes[tree.prototypeIndex]);
  283. }
  284. terrains[i] = t;
  285. #endif
  286. }
  287. //***********************************************************************
  288. // Copy the mesh data.
  289. List<Vector3> tempVertices = new List<Vector3>();
  290. List<int> tempIndices = new List<int>();
  291. MeshGroup[] groups = new MeshGroup[totalMaterialCount];
  292. float[] vertices = new float[totalVertexCount * 3];
  293. int[] indices = new int[totalIndexCount];
  294. int vertexOffset = 0;
  295. int indexOffset = 0;
  296. int groupOffset = 0;
  297. foreach (MeshMaterial m in meshes)
  298. {
  299. MeshFilter meshFilter = m.meshFilter;
  300. // Compute the combined transform to go from mesh-local to geometry-local space.
  301. Matrix4x4 matrix = worldToLocal * meshFilter.gameObject.transform.localToWorldMatrix;
  302. uploadMeshFilter(tempVertices, tempIndices, groups, vertices, indices, ref vertexOffset, ref indexOffset, ref groupOffset, meshFilter.sharedMesh, m.materials, matrix);
  303. }
  304. foreach (TerrainMaterial t in terrains)
  305. {
  306. TerrainData terrain = t.terrain.terrainData;
  307. // Compute the combined transform to go from mesh-local to geometry-local space.
  308. Matrix4x4 matrix = worldToLocal * t.terrain.gameObject.transform.localToWorldMatrix;
  309. #if UNITY_2019_3_OR_NEWER
  310. int w = terrain.heightmapResolution;
  311. int h = terrain.heightmapResolution;
  312. #else
  313. int w = terrain.heightmapWidth;
  314. int h = terrain.heightmapHeight;
  315. #endif
  316. float[,] tData = terrain.GetHeights(0, 0, w, h);
  317. Vector3 meshScale = terrain.size;
  318. meshScale = new Vector3(meshScale.x / (w - 1) * terrainDecimation, meshScale.y, meshScale.z / (h - 1) * terrainDecimation);
  319. int wRes = (w - 1) / terrainDecimation + 1;
  320. int hRes = (h - 1) / terrainDecimation + 1;
  321. int vertexCount = wRes * hRes;
  322. int triangleCount = (wRes - 1) * (hRes - 1) * 2;
  323. // Initialize the group.
  324. groups[groupOffset].faceType = FaceType.TRIANGLES;
  325. groups[groupOffset].faceCount = (UIntPtr)triangleCount;
  326. groups[groupOffset].indexOffset = (UIntPtr)indexOffset;
  327. if (t.materials != null && 0 < t.materials.Length)
  328. {
  329. t.materials[0].StartInternal();
  330. groups[groupOffset].material = t.materials[0].materialHandle;
  331. }
  332. else
  333. groups[groupOffset].material = IntPtr.Zero;
  334. // Build vertices and UVs
  335. for (int y = 0; y < hRes; y++)
  336. {
  337. for (int x = 0; x < wRes; x++)
  338. {
  339. int offset = (vertexOffset + y * wRes + x) * 3;
  340. Vector3 v = matrix.MultiplyPoint3x4(Vector3.Scale(meshScale, new Vector3(y, tData[x * terrainDecimation, y * terrainDecimation], x)));
  341. vertices[offset + 0] = v.x;
  342. vertices[offset + 1] = v.y;
  343. vertices[offset + 2] = v.z;
  344. }
  345. }
  346. // Build triangle indices: 3 indices into vertex array for each triangle
  347. for (int y = 0; y < hRes - 1; y++)
  348. {
  349. for (int x = 0; x < wRes - 1; x++)
  350. {
  351. // For each grid cell output two triangles
  352. indices[indexOffset + 0] = (vertexOffset + (y * wRes) + x);
  353. indices[indexOffset + 1] = (vertexOffset + ((y + 1) * wRes) + x);
  354. indices[indexOffset + 2] = (vertexOffset + (y * wRes) + x + 1);
  355. indices[indexOffset + 3] = (vertexOffset + ((y + 1) * wRes) + x);
  356. indices[indexOffset + 4] = (vertexOffset + ((y + 1) * wRes) + x + 1);
  357. indices[indexOffset + 5] = (vertexOffset + (y * wRes) + x + 1);
  358. indexOffset += 6;
  359. }
  360. }
  361. vertexOffset += vertexCount;
  362. groupOffset++;
  363. #if INCLUDE_TERRAIN_TREES
  364. TreeInstance[] trees = terrain.treeInstances;
  365. foreach (TreeInstance tree in trees)
  366. {
  367. Vector3 pos = Vector3.Scale(tree.position, terrain.size);
  368. Matrix4x4 treeLocalToWorldMatrix = t.terrain.gameObject.transform.localToWorldMatrix;
  369. treeLocalToWorldMatrix.SetColumn(3, treeLocalToWorldMatrix.GetColumn(3) + new Vector4(pos.x, pos.y, pos.z, 0.0f));
  370. // TODO: tree rotation
  371. Matrix4x4 treeMatrix = worldToLocal * treeLocalToWorldMatrix;
  372. uploadMeshFilter(tempVertices, tempIndices, groups, vertices, indices, ref vertexOffset, ref indexOffset, ref groupOffset, t.treePrototypeMeshes[tree.prototypeIndex], treeMaterials, treeMatrix);
  373. }
  374. #endif
  375. }
  376. // Upload mesh data
  377. return ONSPPropagation.Interface.AudioGeometryUploadMeshArrays(geometryHandle,
  378. vertices, totalVertexCount,
  379. indices, indices.Length,
  380. groups, groups.Length);
  381. }
  382. private static void uploadMeshFilter(List<Vector3> tempVertices, List<int> tempIndices, MeshGroup[] groups, float[] vertices, int[] indices,
  383. ref int vertexOffset, ref int indexOffset, ref int groupOffset, Mesh mesh, ONSPPropagationMaterial[] materials, Matrix4x4 matrix)
  384. {
  385. // Get the mesh vertices.
  386. tempVertices.Clear();
  387. mesh.GetVertices(tempVertices);
  388. // Copy the Vector3 vertices into a packed array of floats for the API.
  389. int meshVertexCount = tempVertices.Count;
  390. for (int i = 0; i < meshVertexCount; i++)
  391. {
  392. // Transform into the parent space.
  393. Vector3 v = matrix.MultiplyPoint3x4(tempVertices[i]);
  394. int offset = (vertexOffset + i) * 3;
  395. vertices[offset + 0] = v.x;
  396. vertices[offset + 1] = v.y;
  397. vertices[offset + 2] = v.z;
  398. }
  399. // Copy the data for each submesh.
  400. for (int i = 0; i < mesh.subMeshCount; i++)
  401. {
  402. MeshTopology topology = mesh.GetTopology(i);
  403. if (topology == MeshTopology.Triangles || topology == MeshTopology.Quads)
  404. {
  405. // Get the submesh indices.
  406. tempIndices.Clear();
  407. mesh.GetIndices(tempIndices, i);
  408. int subMeshIndexCount = tempIndices.Count;
  409. // Copy and adjust the indices.
  410. for (int j = 0; j < subMeshIndexCount; j++)
  411. indices[indexOffset + j] = tempIndices[j] + vertexOffset;
  412. // Initialize the group.
  413. if (topology == MeshTopology.Triangles)
  414. {
  415. groups[groupOffset + i].faceType = FaceType.TRIANGLES;
  416. groups[groupOffset + i].faceCount = (UIntPtr)(subMeshIndexCount / 3);
  417. }
  418. else if (topology == MeshTopology.Quads)
  419. {
  420. groups[groupOffset + i].faceType = FaceType.QUADS;
  421. groups[groupOffset + i].faceCount = (UIntPtr)(subMeshIndexCount / 4);
  422. }
  423. groups[groupOffset + i].indexOffset = (UIntPtr)indexOffset;
  424. if (materials != null && materials.Length != 0)
  425. {
  426. int matIndex = i;
  427. if (matIndex >= materials.Length)
  428. matIndex = materials.Length - 1;
  429. materials[matIndex].StartInternal();
  430. groups[groupOffset + i].material = materials[matIndex].materialHandle;
  431. }
  432. else
  433. groups[groupOffset + i].material = IntPtr.Zero;
  434. indexOffset += subMeshIndexCount;
  435. }
  436. }
  437. vertexOffset += meshVertexCount;
  438. groupOffset += mesh.subMeshCount;
  439. }
  440. private static void updateCountsForMesh(ref int totalVertexCount, ref uint totalIndexCount, ref int totalFaceCount, ref int totalMaterialCount, Mesh mesh)
  441. {
  442. totalMaterialCount += mesh.subMeshCount;
  443. totalVertexCount += mesh.vertexCount;
  444. for (int i = 0; i < mesh.subMeshCount; i++)
  445. {
  446. MeshTopology topology = mesh.GetTopology(i);
  447. if (topology == MeshTopology.Triangles || topology == MeshTopology.Quads)
  448. {
  449. uint meshIndexCount = mesh.GetIndexCount(i);
  450. totalIndexCount += meshIndexCount;
  451. if (topology == MeshTopology.Triangles)
  452. totalFaceCount += (int)meshIndexCount / 3;
  453. else if (topology == MeshTopology.Quads)
  454. totalFaceCount += (int)meshIndexCount / 4;
  455. }
  456. }
  457. }
  458. //***********************************************************************
  459. // UploadGeometry
  460. public void UploadGeometry()
  461. {
  462. int ignoredMeshCount = 0;
  463. if (uploadMesh(geometryHandle, gameObject, gameObject.transform.worldToLocalMatrix, true, ref ignoredMeshCount) != OSPSuccess)
  464. throw new Exception("Unable to upload audio mesh geometry");
  465. if (ignoredMeshCount != 0)
  466. {
  467. Debug.LogError("Failed to upload meshes, " + ignoredMeshCount + " static meshes ignored. Turn on \"File Enabled\" to process static meshes offline", gameObject);
  468. }
  469. }
  470. #if UNITY_EDITOR
  471. //***********************************************************************
  472. // WriteFile - Write the serialized mesh file.
  473. public bool WriteFile()
  474. {
  475. if (filePathRelative == "")
  476. {
  477. filePathRelative = GetPath(transform);
  478. string modifier = "";
  479. int counter = 0;
  480. while (System.IO.File.Exists(filePath + modifier))
  481. {
  482. modifier = "-" + counter;
  483. ++counter;
  484. if (counter > 10000)
  485. {
  486. // sanity check to prevent hang
  487. throw new Exception("Unable to find sutiable file name");
  488. }
  489. }
  490. filePathRelative = filePathRelative + modifier;
  491. Debug.Log("No file path specified, autogenerated: " + filePathRelative);
  492. }
  493. // Create the directory
  494. string directoryName = filePathRelative.Substring(0, filePathRelative.LastIndexOf('/'));
  495. System.IO.Directory.CreateDirectory(GeometryAssetPath + "/" + directoryName);
  496. // Create a temporary geometry.
  497. IntPtr tempGeometryHandle = IntPtr.Zero;
  498. if (ONSPPropagation.Interface.CreateAudioGeometry(out tempGeometryHandle) != OSPSuccess)
  499. {
  500. throw new Exception("Failed to create temp geometry handle");
  501. }
  502. // Upload the mesh geometry.
  503. if (uploadMesh(tempGeometryHandle, gameObject, gameObject.transform.worldToLocalMatrix) != OSPSuccess)
  504. {
  505. Debug.LogError("Error uploading mesh " + gameObject.name);
  506. return false;
  507. }
  508. // Write the mesh to a file.
  509. if (ONSPPropagation.Interface.AudioGeometryWriteMeshFile(tempGeometryHandle, filePath) != OSPSuccess)
  510. {
  511. Debug.LogError("Error writing mesh file " + filePath);
  512. return false;
  513. }
  514. // Destroy the geometry.
  515. if (ONSPPropagation.Interface.DestroyAudioGeometry(tempGeometryHandle) != OSPSuccess)
  516. {
  517. throw new Exception("Failed to destroy temp geometry handle");
  518. }
  519. return true;
  520. }
  521. #endif
  522. //***********************************************************************
  523. // ReadFile - Read the serialized mesh file.
  524. public bool ReadFile()
  525. {
  526. if (filePath == null || filePath.Length == 0)
  527. {
  528. Debug.LogError("Invalid mesh file path");
  529. return false;
  530. }
  531. if (ONSPPropagation.Interface.AudioGeometryReadMeshFile(geometryHandle, filePath) != OSPSuccess)
  532. {
  533. Debug.LogError("Error reading mesh file " + filePath);
  534. return false;
  535. }
  536. return true;
  537. }
  538. public bool WriteToObj()
  539. {
  540. // Create a temporary geometry.
  541. IntPtr tempGeometryHandle = IntPtr.Zero;
  542. if (ONSPPropagation.Interface.CreateAudioGeometry(out tempGeometryHandle) != OSPSuccess)
  543. {
  544. throw new Exception("Failed to create temp geometry handle");
  545. }
  546. // Upload the mesh geometry.
  547. if (uploadMesh(tempGeometryHandle, gameObject, gameObject.transform.worldToLocalMatrix) != OSPSuccess)
  548. {
  549. Debug.LogError("Error uploading mesh " + gameObject.name);
  550. return false;
  551. }
  552. // Write the mesh to a .obj file.
  553. if (ONSPPropagation.Interface.AudioGeometryWriteMeshFileObj(tempGeometryHandle, filePath + ".obj") != OSPSuccess)
  554. {
  555. Debug.LogError("Error writing .obj file " + filePath + ".obj");
  556. return false;
  557. }
  558. // Destroy the geometry.
  559. if (ONSPPropagation.Interface.DestroyAudioGeometry(tempGeometryHandle) != OSPSuccess)
  560. {
  561. throw new Exception("Failed to destroy temp geometry handle");
  562. }
  563. return true;
  564. }
  565. }