123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653 |
- using System.Collections.Generic;
- using UnityEngine;
- using System.Threading;
- using System.Text;
- using System;
- using System.Globalization;
- public class ZEDSpatialMapping
- {
-
-
-
- public struct Chunk
- {
-
-
-
- public GameObject o;
-
-
-
- public ProceduralMesh proceduralMesh;
-
-
-
- public Mesh mesh;
- }
-
-
-
- public struct ProceduralMesh
- {
-
-
-
- public int[] triangles;
-
-
-
- public Vector3[] vertices;
-
-
-
- public MeshFilter mesh;
- };
-
-
-
- public enum RESOLUTION
- {
-
-
-
- HIGH,
-
-
-
-
- MEDIUM,
-
-
-
- LOW
- }
-
-
-
- public enum RANGE
- {
-
-
-
- NEAR,
-
-
-
- MEDIUM,
-
-
-
- FAR
- }
-
-
-
- private sl.ZEDCamera zedCamera;
-
-
-
- private ZEDSpatialMappingHelper spatialMappingHelper;
-
-
-
- public sl.FILTER filterParameters = sl.FILTER.MEDIUM;
-
-
-
-
- private bool saveRequested = false;
-
-
-
-
- private string savePath = "Assets/ZEDMesh.obj";
- #if UNITY_EDITOR
-
-
-
- private Color colorMesh = new Color(0.35f, 0.65f, 0.95f);
- #endif
-
-
-
- private int trianglesOffsetLastFrame;
-
-
-
- private int verticesOffsetLastFrame;
-
-
-
- private int uvsOffsetLastFrame;
-
-
-
- private int indexLastFrame;
-
-
-
- private bool remainMeshes = false;
-
-
-
- private bool stopWanted = false;
-
-
-
- private bool isFiltering = false;
-
-
-
- private bool isFilteringOver = false;
-
-
-
- private bool stopRunning = false;
-
-
-
-
- private bool running = false;
-
-
-
- private bool pause = false;
-
-
-
- public bool IsPaused
- {
- get { return pause; }
- }
-
-
-
- public bool display = false;
-
-
-
- private sl.ERROR_CODE scanningInitState;
-
-
-
- public delegate void OnNewMesh();
-
-
-
- public event OnNewMesh OnMeshUpdate;
-
-
-
- public delegate void OnSpatialMappingEnded();
-
-
-
- public event OnSpatialMappingEnded OnMeshReady;
-
-
-
- public delegate void OnSpatialMappingStarted();
-
-
-
- public event OnSpatialMappingStarted OnMeshStarted;
-
-
-
- private GameObject holder = null;
-
-
-
-
- private bool meshUpdated = false;
-
-
-
- private bool updateThreadRunning = false;
-
-
-
- public bool IsUpdateThreadRunning
- {
- get { return updateThreadRunning; }
- }
-
-
-
- private bool spatialMappingRequested = false;
-
-
-
-
- private bool updateTexture = false;
-
-
-
- private bool updatedTexture = false;
-
-
-
- private Thread scanningThread;
-
-
-
- private Thread filterThread;
-
-
-
- private object lockScanning = new object();
-
-
-
- private const int MAX_TIME = 5;
-
-
-
- private bool texturingRunning = false;
-
-
-
-
- public Vector3 gravityEstimation;
-
-
-
- public bool IsTexturingRunning
- {
- get
- {
- return texturingRunning;
- }
- }
-
-
-
- private bool hasColliders = true;
-
-
-
- private bool isTextured = false;
-
-
-
-
- private bool setMeshRenderer = false;
-
-
-
-
- private ZEDMeshRenderer[] meshRenderer = new ZEDMeshRenderer[2];
-
-
-
- private ZEDManager zedManager;
-
-
-
-
- public Dictionary<int, ZEDSpatialMapping.Chunk> Chunks
- {
- get { return spatialMappingHelper.chunks; }
- }
-
-
-
-
- public List<ZEDSpatialMapping.Chunk> ChunkList = new List<ZEDSpatialMapping.Chunk>();
-
-
-
-
-
-
- public ZEDSpatialMapping(Transform transform, ZEDManager zedManager)
- {
-
- spatialMappingHelper = new ZEDSpatialMappingHelper(zedManager.zedCamera, Resources.Load("Materials/SpatialMapping/Mat_ZED_Texture") as Material, Resources.Load("Materials/SpatialMapping/Mat_ZED_Geometry_Wireframe") as Material);
-
- this.zedCamera = zedManager.zedCamera;
- this.zedManager = zedManager;
- scanningInitState = sl.ERROR_CODE.FAILURE;
- }
-
-
-
-
-
-
- public void StartStatialMapping(sl.SPATIAL_MAP_TYPE type, RESOLUTION resolutionPreset, RANGE rangePreset, bool isTextured)
- {
-
- holder = new GameObject();
- holder.name = "[ZED Mesh Holder (" + zedManager.name + ")]";
- holder.transform.position = Vector3.zero;
- holder.transform.rotation = Quaternion.identity;
- StaticBatchingUtility.Combine(holder);
- holder.transform.position = Vector3.zero;
- holder.transform.rotation = Quaternion.identity;
- spatialMappingRequested = true;
- if (spatialMappingRequested && scanningInitState != sl.ERROR_CODE.SUCCESS)
- {
- scanningInitState = EnableSpatialMapping(type, resolutionPreset, rangePreset, isTextured);
- }
- zedManager.gravityRotation = Quaternion.identity;
- pause = false;
- }
-
-
-
-
-
-
-
-
- private sl.ERROR_CODE EnableSpatialMapping(sl.SPATIAL_MAP_TYPE type,RESOLUTION resolutionPreset, RANGE rangePreset, bool isTextured)
- {
- sl.ERROR_CODE error;
- this.isTextured = isTextured;
-
- error = spatialMappingHelper.EnableSpatialMapping(type,ZEDSpatialMappingHelper.ConvertResolutionPreset(resolutionPreset), ZEDSpatialMappingHelper.ConvertRangePreset(rangePreset), isTextured);
- if (meshRenderer[0]) meshRenderer[0].isTextured = isTextured;
- if (meshRenderer[1]) meshRenderer[1].isTextured = isTextured;
- stopWanted = false;
- running = true;
- if (error == sl.ERROR_CODE.SUCCESS)
- {
-
- display = true;
- meshUpdated = false;
- spatialMappingRequested = false;
- updateTexture = false;
- updatedTexture = false;
-
- ClearMeshes();
-
- zedCamera.RequestMesh();
-
- scanningThread = new Thread(UpdateMesh);
- updateThreadRunning = true;
- if (OnMeshStarted != null)
- {
- OnMeshStarted();
- }
- scanningThread.Start();
- }
- return error;
- }
-
-
-
- public void SetMeshRenderer()
- {
- if (!setMeshRenderer)
- {
- if (zedManager != null)
- {
- Transform left = zedManager.GetLeftCameraTransform();
- if (left != null)
- {
- meshRenderer[0] = left.gameObject.GetComponent<ZEDMeshRenderer>();
- if (!meshRenderer[0])
- {
- meshRenderer[0] = left.gameObject.AddComponent<ZEDMeshRenderer>();
- }
- meshRenderer[0].Create();
- }
- Transform right = zedManager.GetRightCameraTransform();
- if (right != null)
- {
- meshRenderer[1] = right.gameObject.GetComponent<ZEDMeshRenderer>();
- if (!meshRenderer[1])
- {
- meshRenderer[1] = right.gameObject.AddComponent<ZEDMeshRenderer>();
- }
- meshRenderer[1].Create();
- }
- setMeshRenderer = true;
- }
- }
- }
-
-
-
- public void Update()
- {
- SetMeshRenderer();
- if (meshUpdated || remainMeshes)
- {
- UpdateMeshMainthread();
- meshUpdated = false;
- }
- if (stopWanted && !remainMeshes)
- {
- stopRunning = true;
- stopWanted = false;
- Stop();
- }
-
- if (stopRunning && !isFiltering && isFilteringOver)
- {
- isFilteringOver = false;
- UpdateMeshMainthread(false);
- Thread disabling = new Thread(DisableSpatialMapping);
- disabling.Start();
- if (hasColliders)
- {
- if (!zedManager.IsStereoRig && gravityEstimation != Vector3.zero && zedManager.transform.parent != null)
- {
- Quaternion rotationToApplyForGravity = Quaternion.Inverse(Quaternion.FromToRotation(Vector3.up, -gravityEstimation.normalized));
- holder.transform.localRotation = rotationToApplyForGravity;
- zedManager.gravityRotation = rotationToApplyForGravity;
- }
- UpdateMeshCollider();
- }
- else
- {
- running = false;
- }
- stopRunning = false;
- }
- }
-
-
-
- private void UpdateMesh()
- {
- while (updateThreadRunning)
- {
- if (!remainMeshes)
- {
- lock (lockScanning)
- {
- if (meshUpdated == false && updateTexture)
- {
-
- spatialMappingHelper.ApplyTexture();
- meshUpdated = true;
- updateTexture = false;
- updatedTexture = true;
- updateThreadRunning = false;
- }
- else if (zedCamera.GetMeshRequestStatus() == sl.ERROR_CODE.SUCCESS && !pause && meshUpdated == false)
- {
- spatialMappingHelper.UpdateMesh();
- spatialMappingHelper.RetrieveMesh();
- meshUpdated = true;
- }
- }
-
- Thread.Sleep(5);
- }
- else
- {
-
- Thread.Sleep(5);
- }
- }
- }
-
-
-
- private void ClearMeshes()
- {
- if (holder != null)
- {
- foreach (Transform child in holder.transform)
- {
- GameObject.Destroy(child.gameObject);
- }
- spatialMappingHelper.Clear();
- }
- }
-
-
-
-
-
-
- private bool GoneOverTimeBudget(int startTimeMS)
- {
- return (Time.realtimeSinceStartup * 1000) - startTimeMS > MAX_TIME;
- }
-
-
-
-
-
- private void UpdateMeshMainthread(bool spreadUpdateOverTime = true)
- {
-
-
- int startTimeMS = (int)(Time.realtimeSinceStartup * 1000);
- int indexUpdate = 0;
- lock (lockScanning)
- {
- if (updatedTexture)
- {
- spreadUpdateOverTime = false;
- }
-
- int verticesOffset = 0, trianglesOffset = 0, uvsOffset = 0;
- if (remainMeshes && spreadUpdateOverTime)
- {
- verticesOffset = verticesOffsetLastFrame;
- trianglesOffset = trianglesOffsetLastFrame;
- uvsOffset = uvsOffsetLastFrame;
- indexUpdate = indexLastFrame;
- }
-
- if (updatedTexture)
- {
- ClearMeshes();
- spatialMappingHelper.SetMeshAndTexture();
- if (meshRenderer[0]) meshRenderer[0].isTextured = isTextured;
- if (meshRenderer[1]) meshRenderer[1].isTextured = isTextured;
- }
-
- for (; indexUpdate < spatialMappingHelper.NumberUpdatedSubMesh; indexUpdate++)
- {
- spatialMappingHelper.SetMesh(indexUpdate, ref verticesOffset, ref trianglesOffset, ref uvsOffset, holder.transform, updatedTexture);
- if (spreadUpdateOverTime && GoneOverTimeBudget(startTimeMS))
- {
- remainMeshes = true;
- break;
- }
- }
- if (spreadUpdateOverTime)
- {
- indexLastFrame = indexUpdate;
- }
- else
- {
- indexLastFrame = 0;
- }
-
- if ((indexUpdate == spatialMappingHelper.NumberUpdatedSubMesh) || spatialMappingHelper.NumberUpdatedSubMesh == 0)
- {
- verticesOffsetLastFrame = 0;
- trianglesOffsetLastFrame = 0;
- uvsOffsetLastFrame = 0;
- indexLastFrame = 0;
- remainMeshes = false;
- meshUpdated = false;
- zedCamera.RequestMesh();
- }
-
- else if (indexUpdate != spatialMappingHelper.NumberUpdatedSubMesh)
- {
- remainMeshes = true;
- indexLastFrame = indexUpdate + 1;
- verticesOffsetLastFrame = verticesOffset;
- trianglesOffsetLastFrame = trianglesOffset;
- uvsOffsetLastFrame = uvsOffset;
- }
-
- if (saveRequested && remainMeshes == false)
- {
- if (!isTextured || updatedTexture)
- {
- SaveMeshNow(savePath);
- saveRequested = false;
- }
- }
- }
- if (OnMeshUpdate != null)
- {
- OnMeshUpdate();
- }
-
- if (updatedTexture)
- {
- DisableSpatialMapping();
- updatedTexture = false;
- running = false;
- texturingRunning = false;
- if (hasColliders)
- {
- UpdateMeshCollider();
- }
- else
- {
- running = false;
- }
- }
- }
- public void ClearAllMeshes()
- {
- GameObject[] gos = GameObject.FindObjectsOfType<GameObject>() as GameObject[];
- spatialMappingHelper.Clear();
- for (int i = 0; i < gos.Length; i++)
- {
- string targetName = "[ZED Mesh Holder (" + zedManager.name + ")]";
- if (gos[i] != null && gos[i].name.Contains(targetName))
- {
- GameObject.Destroy(gos[i]);
- }
- }
- }
-
-
-
-
-
- public void SwitchDisplayMeshState(bool newDisplayState)
- {
- display = newDisplayState;
- }
-
-
-
-
- public void SwitchPauseState(bool newPauseState)
- {
- pause = newPauseState;
- zedCamera.PauseSpatialMapping(newPauseState);
- }
-
-
-
-
- public void UpdateMeshCollider(bool timeSlicing = false)
- {
- ChunkList.Clear();
- foreach (var submesh in Chunks)
- {
- ChunkList.Add(submesh.Value);
- }
- lock (lockScanning)
- {
- spatialMappingHelper.UpdateMeshCollider(ChunkList);
- }
- if (OnMeshReady != null)
- {
- OnMeshReady();
- }
- running = false;
- }
-
-
-
-
- public void Dispose()
- {
- if (scanningThread != null)
- {
- updateThreadRunning = false;
- scanningThread.Join();
- }
- ClearMeshes();
- GameObject.Destroy(holder);
- DisableSpatialMapping();
- }
-
-
-
-
- private void DisableSpatialMapping()
- {
- lock (lockScanning)
- {
- updateThreadRunning = false;
- spatialMappingHelper.DisableSpatialMapping();
- scanningInitState = sl.ERROR_CODE.FAILURE;
- spatialMappingRequested = false;
- }
- }
-
-
-
-
- public void RequestSaveMesh(string meshFilePath = "Assets/ZEDMesh.obj")
- {
- saveRequested = true;
- savePath = meshFilePath;
- if (updateThreadRunning)
- {
- StopStatialMapping();
- }
- }
-
-
-
-
-
-
-
- public bool LoadMesh(string meshFilePath = "ZEDMesh.obj")
- {
- if (holder == null)
- {
- holder = new GameObject();
- holder.name = "[ZED Mesh Holder (" + zedManager.name + ")]";
- holder.transform.position = Vector3.zero;
- holder.transform.rotation = Quaternion.identity;
- StaticBatchingUtility.Combine(holder);
- }
- if (OnMeshStarted != null)
- {
- OnMeshStarted();
- }
-
- DisableSpatialMapping();
-
- string basePath = meshFilePath.Substring(0, meshFilePath.LastIndexOf("."));
- if (!System.IO.File.Exists(basePath + ".area"))
- {
- Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.TRACKING_BASE_AREA_NOT_FOUND));
- }
- zedCamera.DisableTracking();
- Quaternion quat = Quaternion.identity; Vector3 tr = Vector3.zero;
- if (zedCamera.EnableTracking(ref quat, ref tr, true, false, false, false, true, System.IO.File.Exists(basePath + ".area") ? basePath + ".area" : "") != sl.ERROR_CODE.SUCCESS)
- {
- Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.TRACKING_NOT_INITIALIZED));
- }
- updateTexture = false;
- updatedTexture = false;
- bool meshUpdatedLoad = false;
- lock (lockScanning)
- {
- ClearMeshes();
- meshUpdatedLoad = spatialMappingHelper.LoadMesh(meshFilePath);
- if (meshUpdatedLoad)
- {
-
- if (spatialMappingHelper.GetWidthTexture() != -1)
- {
- updateTexture = true;
- updatedTexture = true;
- }
-
- if (!updateTexture)
- {
- spatialMappingHelper.RetrieveMesh();
- }
- }
- }
- if (meshUpdatedLoad)
- {
-
- UpdateMeshMainthread(false);
-
- if (hasColliders)
- {
- if (!zedManager.IsStereoRig && gravityEstimation != Vector3.zero)
- {
- Quaternion rotationToApplyForGravity = Quaternion.Inverse(Quaternion.FromToRotation(Vector3.up, -gravityEstimation.normalized));
- holder.transform.rotation = rotationToApplyForGravity;
- zedManager.gravityRotation = rotationToApplyForGravity;
- }
- UpdateMeshCollider();
- foreach (Chunk c in ChunkList)
- {
- c.o.transform.localRotation = Quaternion.identity;
- }
- }
- if (OnMeshReady != null)
- {
- OnMeshReady();
- }
- if (meshRenderer[0]) meshRenderer[0].UpdateRenderingPlane(true);
- if (meshRenderer[1]) meshRenderer[1].UpdateRenderingPlane(true);
- return true;
- }
- return false;
- }
-
-
-
-
- public void FilterMesh()
- {
- lock (lockScanning)
- {
- spatialMappingHelper.FilterMesh(filterParameters);
- spatialMappingHelper.ResizeMesh();
- spatialMappingHelper.RetrieveMesh();
- meshUpdated = true;
- }
- }
-
-
-
-
- void PostProcessMesh(bool filter = true)
- {
- isFiltering = true;
- if (filter)
- {
- FilterMesh();
- }
- MergeChunks();
- }
-
-
-
-
- public void MergeChunks()
- {
- lock (lockScanning)
- {
- spatialMappingHelper.MergeChunks();
- spatialMappingHelper.ResizeMesh();
- spatialMappingHelper.RetrieveMesh();
- meshUpdated = true;
- }
- isFiltering = false;
- isFilteringOver = true;
- }
-
-
-
-
- void ApplyTextureThreaded()
- {
- FilterMesh();
- UpdateMesh();
- }
-
-
-
- public bool ApplyTexture()
- {
- updateTexture = true;
- if (updateThreadRunning)
- {
- updateThreadRunning = false;
- scanningThread.Join();
- }
- scanningThread = new Thread(ApplyTextureThreaded);
- updateThreadRunning = true;
- scanningThread.Start();
- texturingRunning = true;
- return true;
- }
-
-
-
- private void Stop()
- {
- gravityEstimation = zedCamera.GetGravityEstimate();
- if (isTextured)
- {
- ApplyTexture();
- }
- else
- {
- stopRunning = false;
- if (updateThreadRunning)
- {
- updateThreadRunning = false;
- scanningThread.Join();
- }
- ClearMeshes();
- PostProcessMesh(true);
-
-
- stopRunning = true;
- }
- SwitchDisplayMeshState(true);
- }
-
-
-
-
- public bool IsRunning()
- {
- return running;
- }
-
-
-
- public void StopStatialMapping()
- {
- stopWanted = true;
- }
-
-
-
-
-
-
-
-
-
- private void SaveMeshNow(string meshFilePath = "Assets/ZEDMesh.obj")
- {
-
- CultureInfo oldCulture = Thread.CurrentThread.CurrentCulture;
- Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
-
- string extension = meshFilePath.Substring(meshFilePath.Length - 4);
- if (extension.ToLower() != ".obj")
- {
- Debug.LogError("Couldn't save to " + meshFilePath + ": Must save as .obj.");
- }
- lock (lockScanning)
- {
- Debug.Log("Saving mesh to " + meshFilePath);
-
- int vertcount = 0;
- int tricount = 0;
- foreach (Chunk chunk in Chunks.Values)
- {
- vertcount += chunk.mesh.vertices.Length;
- tricount += chunk.mesh.triangles.Length;
- }
- if (vertcount == 0) return;
- Vector3[] vertices = new Vector3[vertcount];
- Vector2[] uvs = new Vector2[vertcount];
- Vector3[] normals = new Vector3[vertcount];
- int[] triangles = new int[tricount];
- int vertssofar = 0;
- int trissofar = 0;
- for (int i = 0; i < Chunks.Keys.Count; i++)
- {
- Mesh chunkmesh = Chunks[i].mesh;
- Array.Copy(chunkmesh.vertices, 0, vertices, vertssofar, chunkmesh.vertices.Length);
- Array.Copy(chunkmesh.uv, 0, uvs, vertssofar, chunkmesh.uv.Length);
- chunkmesh.RecalculateNormals();
- Array.Copy(chunkmesh.normals, 0, normals, vertssofar, chunkmesh.normals.Length);
- Array.Copy(chunkmesh.triangles, 0, triangles, trissofar, chunkmesh.triangles.Length);
- for (int t = trissofar; t < trissofar + chunkmesh.triangles.Length; t++)
- {
- triangles[t] += vertssofar;
- }
- vertssofar += chunkmesh.vertices.Length;
- trissofar += chunkmesh.triangles.Length;
- }
- Material savemat = Chunks[0].o.GetComponent<MeshRenderer>().material;
-
-
- int forwardindex = meshFilePath.LastIndexOf('/');
- int backindex = meshFilePath.LastIndexOf('\\');
- int slashindex = forwardindex > backindex ? forwardindex : backindex;
- string basefilename = meshFilePath.Substring(slashindex + 1, meshFilePath.LastIndexOf(".") - slashindex - 1);
-
-
- StringBuilder objstring = new StringBuilder();
- objstring.Append("# Generated by the ZED SDK.\n");
- if (isTextured)
- objstring.Append("mtllib " + basefilename + ".mtl"+ "\n");
- foreach (Vector3 vec in vertices)
- {
-
- objstring.Append(string.Format("v {0} {1} {2}\n", -vec.x, vec.y, vec.z));
- }
- objstring.Append("\n");
- foreach (Vector2 uv in uvs)
- {
- objstring.Append(string.Format("vt {0} {1}\n", uv.x, uv.y));
- }
- objstring.Append("\n");
- foreach (Vector3 norm in normals)
- {
- objstring.Append(string.Format("vn {0} {1} {2}\n", -norm.x, norm.y, norm.z));
- }
-
- if (isTextured)
- {
- objstring.Append("usemtl ").Append("material0000").Append("\n");
-
- }
- for (int i = 0; i < triangles.Length; i += 3)
- {
-
- objstring.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n",
- triangles[i + 2] + 1, triangles[i + 1] + 1, triangles[i + 0] + 1));
- }
- System.IO.StreamWriter swriter = new System.IO.StreamWriter(meshFilePath);
- swriter.Write(objstring.ToString());
- swriter.Close();
-
- if (isTextured)
- {
-
-
-
- Texture textosave = savemat.mainTexture;
- RenderTexture buffertex = new RenderTexture(textosave.width, textosave.height, 0);
- Graphics.Blit(textosave, buffertex, savemat);
- RenderTexture oldactivert = RenderTexture.active;
- RenderTexture.active = buffertex;
- Texture2D texcopy = new Texture2D(textosave.width, textosave.height);
- texcopy.ReadPixels(new Rect(0, 0, buffertex.width, buffertex.height), 0, 0);
- texcopy.Apply();
- byte[] imagebytes = texcopy.EncodeToPNG();
- string imagepath = meshFilePath.Substring(0, meshFilePath.LastIndexOf(".")) + "_material0000_map_Kd.png";
- System.IO.File.WriteAllBytes(imagepath, imagebytes);
- RenderTexture.active = oldactivert;
-
- StringBuilder mtlstring = new StringBuilder();
- mtlstring.Append("newmtl " + "material0000" + "\n");
- mtlstring.Append("Ka 1.000000 1.000000 1.000000\n");
- mtlstring.Append("Kd 1.000000 1.000000 1.000000\n");
- mtlstring.Append("Ks 0.000000 0.000000 0.000000\n");
- mtlstring.Append("Tr 1.000000\n");
- mtlstring.Append("illum 1\n");
- mtlstring.Append("Ns 1.000000\n");
- mtlstring.Append("map_Kd " + basefilename + "_material0000_map_Kd.png");
- mtlstring.AppendFormat("\n");
- string mtlpath = meshFilePath.Substring(0, meshFilePath.LastIndexOf(".")) + ".mtl";
- swriter = new System.IO.StreamWriter(mtlpath);
- swriter.Write(mtlstring.ToString());
- swriter.Close();
- }
- }
-
- string areaName = meshFilePath.Substring(0, meshFilePath.LastIndexOf(".")) + ".area";
- zedCamera.SaveCurrentArea(areaName);
- Thread.CurrentThread.CurrentCulture = oldCulture;
- }
-
-
-
- #if UNITY_EDITOR
- private void OnDrawGizmos()
- {
- Gizmos.color = colorMesh;
- if (!IsRunning() && spatialMappingHelper != null && spatialMappingHelper.chunks.Count != 0 && display)
- {
- foreach (var submesh in spatialMappingHelper.chunks)
- {
- if (submesh.Value.proceduralMesh.mesh != null)
- {
- Gizmos.DrawWireMesh(submesh.Value.proceduralMesh.mesh.sharedMesh, submesh.Value.o.transform.position, submesh.Value.o.transform.rotation);
- }
- }
- }
- }
- #endif
-
-
-
-
-
- private class ZEDSpatialMappingHelper
- {
-
-
-
- private sl.ZEDCamera zedCamera;
-
-
-
- private const int MAX_SUBMESH = 1000;
-
-
-
-
- private int[] numVerticesInSubmesh = new int[MAX_SUBMESH];
-
-
-
- private int[] numTrianglesInSubmesh = new int[MAX_SUBMESH];
-
-
-
- private int[] UpdatedIndices = new int[MAX_SUBMESH];
-
-
-
-
- private int numVertices = 0;
-
-
-
- private int numTriangles = 0;
-
-
-
- private int numUpdatedSubmesh = 0;
-
-
-
-
- private Vector3[] vertices;
-
-
-
- private Vector2[] uvs;
-
-
-
- private int[] triangles;
-
-
-
- private int[] texturesSize = new int[2];
-
-
-
- public Dictionary<int, ZEDSpatialMapping.Chunk> chunks = new Dictionary<int, ZEDSpatialMapping.Chunk>(MAX_SUBMESH);
-
-
-
- private Material materialTexture;
-
-
-
-
- private Material materialMesh;
-
-
-
- public int NumberUpdatedSubMesh
- {
- get { return numUpdatedSubmesh; }
- }
-
-
-
-
- public Material GetMaterialSpatialMapping()
- {
- return materialMesh;
- }
-
-
-
-
-
- public ZEDSpatialMappingHelper(sl.ZEDCamera camera, Material materialTexture, Material materialMesh)
- {
- zedCamera = camera;
- this.materialTexture = materialTexture;
- this.materialMesh = materialMesh;
- }
-
-
-
- static public float ConvertRangePreset(RANGE rangePreset)
- {
- if (rangePreset == RANGE.NEAR)
- {
- return 3.5f;
- }
- else if (rangePreset == RANGE.MEDIUM)
- {
- return 5.0f;
- }
- if (rangePreset == RANGE.FAR)
- {
- return 10.0f;
- }
- return 5.0f;
- }
-
-
-
- static public float ConvertResolutionPreset(RESOLUTION resolutionPreset)
- {
- if (resolutionPreset == RESOLUTION.HIGH)
- {
- return 0.05f;
- }
- else if (resolutionPreset == RESOLUTION.MEDIUM)
- {
- return 0.10f;
- }
- if (resolutionPreset == RESOLUTION.LOW)
- {
- return 0.15f;
- }
- return 0.10f;
- }
-
-
-
-
- public sl.ERROR_CODE EnableSpatialMapping(sl.SPATIAL_MAP_TYPE type,float resolutionMeter, float maxRangeMeter, bool saveTexture)
- {
- return zedCamera.EnableSpatialMapping(type,resolutionMeter, maxRangeMeter, saveTexture);
- }
-
-
-
- public void DisableSpatialMapping()
- {
- zedCamera.DisableSpatialMapping();
- }
-
-
-
- public ZEDSpatialMapping.Chunk CreateNewMesh(int i, Material meshMat, Transform holder)
- {
-
- ZEDSpatialMapping.Chunk chunk = new ZEDSpatialMapping.Chunk();
- chunk.o = GameObject.CreatePrimitive(PrimitiveType.Quad);
- chunk.o.layer = zedCamera.TagInvisibleToZED;
- chunk.o.GetComponent<MeshCollider>().sharedMesh = null;
- chunk.o.name = "Chunk" + chunks.Count;
- chunk.o.transform.localPosition = Vector3.zero;
- chunk.o.transform.localRotation = Quaternion.identity;
- Mesh m = new Mesh();
- m.MarkDynamic();
- chunk.mesh = m;
-
- MeshRenderer meshRenderer = chunk.o.GetComponent<MeshRenderer>();
- meshRenderer.material = meshMat;
- meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
- meshRenderer.receiveShadows = false;
- meshRenderer.enabled = true;
- meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
- meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
-
- chunk.o.transform.parent = holder;
- chunk.o.layer = zedCamera.TagInvisibleToZED;
-
- chunk.proceduralMesh.mesh = chunk.o.GetComponent<MeshFilter>();
- chunks.Add(i, chunk);
- return chunk;
- }
-
-
-
-
- public void UpdateMeshCollider(List<ZEDSpatialMapping.Chunk> listMeshes, int startIndex = 0)
- {
- List<int> idsToDestroy = new List<int>();
-
- for (int i = startIndex; i < listMeshes.Count; ++i)
- {
- var submesh = listMeshes[i];
- MeshCollider m = submesh.o.GetComponent<MeshCollider>();
- if (m == null)
- {
- m = submesh.o.AddComponent<MeshCollider>();
- }
-
- Mesh tempMesh = submesh.o.GetComponent<MeshFilter>().sharedMesh;
- if (tempMesh.vertexCount < 3)
- {
- idsToDestroy.Add(i);
- continue;
- }
- m.sharedMesh = tempMesh;
- m.sharedMesh.RecalculateNormals();
- m.sharedMesh.RecalculateBounds();
- }
-
- for (int i = 0; i < idsToDestroy.Count; ++i)
- {
- GameObject.Destroy(chunks[idsToDestroy[i]].o);
- chunks.Remove(idsToDestroy[i]);
- }
- Clear();
- }
-
-
-
- public void ApplyTexture()
- {
- zedCamera.ApplyTexture(numVerticesInSubmesh, numTrianglesInSubmesh, ref numUpdatedSubmesh, UpdatedIndices, ref numVertices, ref numTriangles, texturesSize, MAX_SUBMESH);
- }
-
-
-
- public void UpdateMesh()
- {
- zedCamera.UpdateMesh(numVerticesInSubmesh, numTrianglesInSubmesh, ref numUpdatedSubmesh, UpdatedIndices, ref numVertices, ref numTriangles, MAX_SUBMESH);
- ResizeMesh();
- }
-
-
-
-
- public void RetrieveMesh()
- {
- zedCamera.RetrieveMesh(vertices, triangles, MAX_SUBMESH, null, System.IntPtr.Zero);
- }
-
-
-
- public void Clear()
- {
- chunks.Clear();
- vertices = new Vector3[0];
- triangles = new int[0];
- uvs = new Vector2[0];
- System.Array.Clear(vertices, 0, vertices.Length);
- System.Array.Clear(triangles, 0, triangles.Length);
- }
-
-
-
-
-
-
-
-
-
- public void SetMesh(int indexUpdate, ref int verticesOffset, ref int trianglesOffset, ref int uvsOffset, Transform holder, bool updatedTex)
- {
- ZEDSpatialMapping.Chunk subMesh;
- int updatedIndex = UpdatedIndices[indexUpdate];
- if (!chunks.TryGetValue(updatedIndex, out subMesh))
- {
- subMesh = CreateNewMesh(updatedIndex, materialMesh, holder);
- }
- Mesh currentMesh = subMesh.mesh;
- ZEDSpatialMapping.ProceduralMesh dynamicMesh = subMesh.proceduralMesh;
-
- if (dynamicMesh.triangles == null || dynamicMesh.triangles.Length != 3 * numTrianglesInSubmesh[indexUpdate])
- {
- dynamicMesh.triangles = new int[3 * numTrianglesInSubmesh[indexUpdate]];
- }
- if (dynamicMesh.vertices == null || dynamicMesh.vertices.Length != numVerticesInSubmesh[indexUpdate])
- {
- dynamicMesh.vertices = new Vector3[numVerticesInSubmesh[indexUpdate]];
- }
-
- currentMesh.Clear();
-
- System.Array.Copy(vertices, verticesOffset, dynamicMesh.vertices, 0, numVerticesInSubmesh[indexUpdate]);
- verticesOffset += numVerticesInSubmesh[indexUpdate];
- System.Buffer.BlockCopy(triangles, trianglesOffset * sizeof(int), dynamicMesh.triangles, 0, 3 * numTrianglesInSubmesh[indexUpdate] * sizeof(int));
- trianglesOffset += 3 * numTrianglesInSubmesh[indexUpdate];
- currentMesh.vertices = dynamicMesh.vertices;
- currentMesh.SetTriangles(dynamicMesh.triangles, 0, false);
- dynamicMesh.mesh.sharedMesh = currentMesh;
-
- if (updatedTex)
- {
- Vector2[] localUvs = new Vector2[numVerticesInSubmesh[indexUpdate]];
- subMesh.o.GetComponent<MeshRenderer>().sharedMaterial = materialTexture;
- System.Array.Copy(uvs, uvsOffset, localUvs, 0, numVerticesInSubmesh[indexUpdate]);
- uvsOffset += numVerticesInSubmesh[indexUpdate];
- currentMesh.uv = localUvs;
- }
- }
-
-
-
-
-
- public void SetMeshAndTexture()
- {
-
- if (texturesSize[0] > 8192) return;
- Texture2D textureMesh = new Texture2D(texturesSize[0], texturesSize[1], TextureFormat.ARGB32, false);
- if (textureMesh != null)
- {
- materialTexture.SetTexture("_MainTex", textureMesh);
- vertices = new Vector3[numVertices];
- uvs = new Vector2[numVertices];
- triangles = new int[3 * numTriangles];
- System.IntPtr texture = textureMesh.GetNativeTexturePtr();
- zedCamera.RetrieveMesh(vertices, triangles, MAX_SUBMESH, uvs, texture);
- }
- }
-
-
-
-
-
- public bool LoadMesh(string meshFilePath)
- {
- bool r = zedCamera.LoadMesh(meshFilePath, numVerticesInSubmesh, numTrianglesInSubmesh, ref numUpdatedSubmesh, UpdatedIndices, ref numVertices, ref numTriangles, MAX_SUBMESH, texturesSize);
- if (!r) Debug.LogWarning("[ZED] Failed to load mesh: "+ meshFilePath);
- vertices = new Vector3[numVertices];
- uvs = new Vector2[numVertices];
- triangles = new int[3 * numTriangles];
- return r;
- }
-
-
-
-
- public int GetWidthTexture()
- {
- return texturesSize[0];
- }
- public int GetHeightTexture()
- {
- return texturesSize[1];
- }
-
-
-
- public void ResizeMesh()
- {
- if (vertices.Length < numVertices)
- {
- vertices = new Vector3[numVertices * 2];
- }
- if (triangles.Length < 3 * numTriangles)
- {
- triangles = new int[3 * numTriangles * 2];
- }
- }
-
-
-
-
- public void FilterMesh(sl.FILTER filterParameters)
- {
- zedCamera.FilterMesh(filterParameters, numVerticesInSubmesh, numTrianglesInSubmesh, ref numUpdatedSubmesh, UpdatedIndices, ref numVertices, ref numTriangles, MAX_SUBMESH);
- }
-
-
-
-
- public void MergeChunks()
- {
- zedCamera.MergeChunks(MAX_SUBMESH, numVerticesInSubmesh, numTrianglesInSubmesh, ref numUpdatedSubmesh, UpdatedIndices, ref numVertices, ref numTriangles, MAX_SUBMESH);
- }
- }
- }
|