ZEDManager.cs 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335
  1. using UnityEngine;
  2. using System;
  3. using System.Threading;
  4. using UnityEngine.XR;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. /// <summary>
  8. /// The central script of the ZED Unity plugin, and the primary way a developer can interact with the camera.
  9. /// It sets up and closes connection to the ZED, adjusts parameters based on user settings, enables/disables/handles
  10. /// features like tracking, and holds numerous useful properties, methods, and callbacks.
  11. /// </summary>
  12. /// <remarks>
  13. /// ZEDManager is attached to the root objects in the ZED_Rig_Mono and ZED_Rig_Stereo prefabs.
  14. /// If using ZED_Rig_Stereo, it will set isStereoRig to true, which triggers several behaviors unique to stereo pass-through AR.
  15. /// </remarks>
  16. public class ZEDManager : MonoBehaviour
  17. {
  18. /// <summary>
  19. /// Static function to get instance of the ZEDManager with a given camera_ID. See sl.ZED_CAMERA_ID for the available choices.
  20. /// </summary>
  21. public static object grabLock;
  22. static ZEDManager[] ZEDManagerInstance = null;
  23. public static ZEDManager GetInstance(sl.ZED_CAMERA_ID _id)
  24. {
  25. if (ZEDManagerInstance == null)
  26. return null;
  27. else
  28. return ZEDManagerInstance[(int)_id];
  29. }
  30. /// <summary>
  31. /// Static function to get all ZEDManagers that have been properly instantiated.
  32. /// <para>Cameras may not necessarily be connected, if they haven't finished connecting, have disconnected,
  33. /// or if no camera is available.</para>
  34. /// </summary>
  35. /// <returns></returns>
  36. public static List<ZEDManager> GetInstances()
  37. {
  38. List<ZEDManager> instances = new List<ZEDManager>();
  39. for (int i = 0; i < (int)sl.Constant.MAX_CAMERA_PLUGIN; i++)
  40. {
  41. ZEDManager instance = GetInstance((sl.ZED_CAMERA_ID)i);
  42. if (instance != null)
  43. instances.Add(instance);
  44. }
  45. return instances;
  46. }
  47. /// <summary>
  48. /// For advanced debugging. Default false. Set true for the Unity wrapper to log all SDK calls to a new file
  49. /// at C:/ProgramData/stereolabs/SL_Unity_wrapper.txt. This helps find issues that may occur within
  50. /// the protected .dll, but can decrease performance.
  51. /// </summary>
  52. private bool wrapperVerbose = true;
  53. /// <summary>
  54. /// Current instance of the ZED Camera, which handles calls to the Unity wrapper .dll.
  55. /// </summary>
  56. public sl.ZEDCamera zedCamera = null;
  57. /////////////////////////////////////////////////////////////////////////
  58. ///////////////////////// Camera Settings ///////////////////////////////
  59. /////////////////////////////////////////////////////////////////////////
  60. /// <summary>
  61. /// Resolution setting for all images retrieved from the camera. Higher resolution means lower framerate.
  62. /// HD720 is strongly recommended for pass-through AR.
  63. /// </summary>
  64. /// <summary>
  65. /// Camera ID
  66. /// </summary>
  67. [HideInInspector]
  68. public sl.ZED_CAMERA_ID cameraID = sl.ZED_CAMERA_ID.CAMERA_ID_01;
  69. /// <summary>
  70. /// The accuracy of depth calculations. Higher settings mean more accurate occlusion and lighting but costs performance.
  71. /// Note there's a significant jump in performance cost between QUALITY and ULTRA modes.
  72. /// </summary>
  73. /*[Tooltip("The accuracy of depth calculations. Higher settings mean more accurate occlusion and lighting but costs performance.")]*/
  74. [HideInInspector]
  75. public sl.DEPTH_MODE depthMode = sl.DEPTH_MODE.PERFORMANCE;
  76. /// <summary>
  77. /// Input Type in SDK (USB, SVO or Stream)
  78. /// </summary>
  79. [HideInInspector]
  80. public sl.INPUT_TYPE inputType = sl.INPUT_TYPE.INPUT_TYPE_USB;
  81. /// <summary>
  82. /// Camera Resolution
  83. /// </summary>
  84. [HideInInspector]
  85. public sl.RESOLUTION resolution = sl.RESOLUTION.HD720;
  86. /// <summary>
  87. /// Targeted FPS, based on the resolution. VGA = 100, HD720 = 60, HD1080 = 30, HD2K = 15.
  88. /// </summary>
  89. [HideInInspector]
  90. public int FPS = 60;
  91. /// <summary>
  92. /// SVO Input FileName
  93. /// </summary>
  94. [HideInInspector]
  95. public string svoInputFileName = "";
  96. /// <summary>
  97. /// Optional opencv calib file
  98. /// </summary>
  99. public string opencvCalibFile = "";
  100. /// <summary>
  101. /// SVO loop back option
  102. /// </summary>
  103. [HideInInspector]
  104. public bool svoLoopBack = true;
  105. /// <summary>
  106. /// SVO loop back option
  107. /// </summary>
  108. [HideInInspector]
  109. public bool svoRealTimeMode = false;
  110. /// <summary>
  111. /// Current frame being read from the SVO. Doesn't apply when recording.
  112. /// </summary>
  113. [HideInInspector]
  114. [SerializeField]
  115. private int currentFrame = 0;
  116. /// <summary>
  117. /// Current frame being read from the SVO. Doesn't apply when recording.
  118. /// </summary>
  119. public int CurrentFrame
  120. {
  121. get
  122. {
  123. return currentFrame;
  124. }
  125. set
  126. {
  127. currentFrame = value;
  128. }
  129. }
  130. /// <summary>
  131. /// Total number of frames in a loaded SVO.
  132. /// </summary>
  133. [HideInInspector]
  134. [SerializeField]
  135. private int numberFrameMax = 0;
  136. /// <summary>
  137. /// Total number of frames in a loaded SVO.
  138. /// </summary>
  139. public int NumberFrameMax
  140. {
  141. set
  142. {
  143. numberFrameMax = value;
  144. }
  145. get
  146. {
  147. return numberFrameMax;
  148. }
  149. }
  150. [HideInInspector]
  151. [SerializeField]
  152. public bool pauseSVOReading = false;
  153. [HideInInspector]
  154. public bool pauseLiveReading = false;
  155. /// <summary>
  156. /// Ask a new frame is in pause (SVO only)
  157. /// </summary>
  158. [HideInInspector]
  159. public bool NeedNewFrameGrab = false;
  160. /// <summary>
  161. /// Streaming Input IP (v2.8)
  162. /// </summary>
  163. [HideInInspector]
  164. public string streamInputIP = "127.0.0.1";
  165. /// <summary>
  166. /// Streaming Input Port (v2.8)
  167. /// </summary>
  168. [HideInInspector]
  169. public int streamInputPort = 30000;
  170. #if ZED_HDRP
  171. /////////////////////////////////////////////////////////////////////////
  172. ///////////////////////// SRP Lighting //////////////////////////////////
  173. /////////////////////////////////////////////////////////////////////////
  174. public enum shaderType
  175. {
  176. Lit,
  177. Unlit,
  178. Greenscreen_Lit,
  179. Greenscreen_Unlit,
  180. DontChange
  181. }
  182. /// <summary>
  183. ///
  184. /// </summary>
  185. [HideInInspector]
  186. public shaderType srpShaderType = shaderType.Lit;
  187. /// <summary>
  188. /// How much the ZED image should light itself via emission.
  189. /// Setting to zero is most realistic, but requires you to emulate the real-world lighting conditions within Unity. Higher settings cause the image\
  190. /// to be uniformly lit, but light and shadow effects are less visible.
  191. /// </summary>
  192. [HideInInspector]
  193. public float selfIllumination = 0.5f;
  194. /// <summary>
  195. ///
  196. /// </summary>
  197. [HideInInspector]
  198. public bool applyZEDNormals = false;
  199. #endif
  200. /////////////////////////////////////////////////////////////////////////
  201. ///////////////////////// Motion Tracking ///////////////////////////////
  202. /////////////////////////////////////////////////////////////////////////
  203. /// <summary>
  204. /// If enabled, the ZED will move/rotate itself using its own inside-out tracking.
  205. /// If false, the camera tracking will move with the VR HMD if connected and available.
  206. /// <para>Normally, ZEDManager's GameObject will move according to the tracking. But if in AR pass-through mode,
  207. /// then the Camera_eyes object in ZED_Rig_Stereo will move while this object stays still. </para>
  208. /// </summary>
  209. [HideInInspector]
  210. public bool enableTracking = true;
  211. /// <summary>
  212. /// Enables the spatial memory. Will detect and correct tracking drift by remembering features and anchors in the environment,
  213. /// but may cause visible jumps when it happens.
  214. /// </summary>
  215. [HideInInspector]
  216. public bool enableSpatialMemory = true;
  217. /// <summary>
  218. /// If using Spatial Memory, you can specify a path to an existing .area file to start with some memory already loaded.
  219. /// .area files are created by scanning a scene with ZEDSpatialMappingManager and saving the scan.
  220. /// </summary>
  221. [HideInInspector]
  222. public string pathSpatialMemory;
  223. /// <summary>
  224. /// Estimate initial position by detecting the floor.
  225. /// </summary>
  226. [HideInInspector]
  227. public bool estimateInitialPosition = true;
  228. /// <summary>
  229. /// If true, tracking is enabled but doesn't move after initializing.
  230. /// </summary>
  231. [HideInInspector]
  232. public bool trackingIsStatic = false;
  233. /////////////////////////////////////////////////////////////////////////
  234. ///////////////////////// Spatial Mapping ///////////////////////////////
  235. /////////////////////////////////////////////////////////////////////////
  236. /// <summary>
  237. /// Resolution setting for the scan. A higher resolution creates more submeshes and uses more memory, but is more accurate.
  238. /// </summary>
  239. [HideInInspector]
  240. public ZEDSpatialMapping.RESOLUTION mappingResolutionPreset = ZEDSpatialMapping.RESOLUTION.MEDIUM;
  241. /// <summary>
  242. /// Maximum distance geometry can be from the camera to be scanned. Geometry scanned from farther away will be less accurate.
  243. /// </summary>
  244. [HideInInspector]
  245. public ZEDSpatialMapping.RANGE mappingRangePreset = ZEDSpatialMapping.RANGE.MEDIUM;
  246. /// <summary>
  247. /// Whether mesh filtering is needed.
  248. /// </summary>
  249. [HideInInspector]
  250. public bool isMappingFilteringEnable = false;
  251. /// <summary>
  252. /// Whether surface textures will be scanned and applied. Note that texturing will add further delay to the post-scan finalizing period.
  253. /// </summary>
  254. [HideInInspector]
  255. public bool isMappingTextured = false;
  256. /// <summary>
  257. /// Whether to save the mesh .obj and .area files once the scan is finished.
  258. /// </summary>
  259. [HideInInspector]
  260. public bool saveMeshWhenOver = false;
  261. /// <summary>
  262. /// Path to save the .obj and .area files.
  263. /// </summary>
  264. [HideInInspector]
  265. public string meshPath = "Assets/ZEDMesh.obj";
  266. /// <summary>
  267. /// Filtering setting. More filtering results in fewer faces in the mesh, reducing both file size and accuracy.
  268. /// </summary>
  269. [HideInInspector]
  270. public sl.FILTER meshFilterParameters;
  271. /// <summary>
  272. /// Instance of the ZEDSpatialMapping class that handles the actual spatial mapping implementation within Unity.
  273. /// </summary>
  274. [HideInInspector]
  275. private ZEDSpatialMapping spatialMapping = null;
  276. public ZEDSpatialMapping GetSpatialMapping { get { return spatialMapping; } }
  277. /// <summary>
  278. /// Whether the spatial mapping is currently scanning.
  279. /// </summary>
  280. public bool IsMappingRunning { get { return spatialMapping != null ? spatialMapping.IsRunning() : false; } }
  281. /// <summary>
  282. /// List of the processed submeshes. This list isn't filled until StopSpatialMapping() is called.
  283. /// </summary>
  284. public List<ZEDSpatialMapping.Chunk> MappingChunkList { get { return spatialMapping != null ? spatialMapping.ChunkList : null; } }
  285. /// <summary>
  286. /// Whether the mesh update thread is running.
  287. /// </summary>
  288. public bool IsMappingUpdateThreadRunning { get { return spatialMapping != null ? spatialMapping.IsUpdateThreadRunning : false; } }
  289. /// <summary>
  290. /// Whether the spatial mapping was running but has been paused (not stopped) by the user.
  291. /// </summary>
  292. public bool IsMappingPaused { get { return spatialMapping != null ? spatialMapping.IsPaused : false; } }
  293. /// <summary>
  294. /// Whether the mesh is in the texturing stage of finalization.
  295. /// </summary>
  296. public bool IsMappingTexturingRunning { get { return spatialMapping != null ? spatialMapping.IsTexturingRunning : false; } }
  297. /// <summary>
  298. /// Gets a boolean value indicating whether the spatial mapping display is enabled.
  299. /// </summary>
  300. public bool IsSpatialMappingDisplay { get { return spatialMapping != null ? spatialMapping.display : false; } }
  301. /// <summary>
  302. /// Gets a boolean value indicating whether the spatial mapping has chunks
  303. /// </summary>
  304. public bool SpatialMappingHasChunks { get { return spatialMapping != null ? spatialMapping.Chunks.Count > 0 : false; } }
  305. /////////////////////////////////////////////////////////////////////////
  306. //////////////////////// Object Detection //////////////////////////////
  307. /////////////////////////////////////////////////////////////////////////
  308. /// <summary>
  309. /// Sync the Object on the image.
  310. /// </summary>
  311. [HideInInspector]
  312. public bool objectDetectionImageSyncMode = false;
  313. /// <summary>
  314. /// Whether to track objects across multiple frames using the ZED's position relative to the floor.
  315. /// Requires tracking to be on. It's also recommended to enable Estimate Initial Position to find the floor.
  316. /// </summary>
  317. [HideInInspector]
  318. public bool objectDetectionTracking = true;
  319. /// <summary>
  320. /// Whether to calculate 2D masks for each object, showing exactly which pixels within the 2D bounding box are the object.
  321. /// Requires more performance, so do not enable unless needed.
  322. /// </summary>
  323. [HideInInspector]
  324. public bool objectDetection2DMask = false;
  325. /// <summary>
  326. /// Choose what detection model to use in the Object detection module
  327. /// </summary>
  328. [HideInInspector]
  329. public sl.DETECTION_MODEL objectDetectionModel = sl.DETECTION_MODEL.MULTI_CLASS_BOX;
  330. /// <summary>
  331. /// Defines if the body fitting will be applied
  332. /// </summary>
  333. [HideInInspector]
  334. public bool objectDetectionBodyFitting = true;
  335. /// <summary>
  336. /// Defines a upper depth range for detections.
  337. /// </summary>
  338. [HideInInspector]
  339. public float objectDetectionMaxRange = 40.0f;
  340. /// <summary>
  341. /// Defines a upper depth range for detections.
  342. /// </summary>
  343. [HideInInspector]
  344. public sl.OBJECT_FILTERING_MODE objectDetectionFilteringMode = sl.OBJECT_FILTERING_MODE.NMS3D;
  345. [HideInInspector]
  346. public sl.BODY_FORMAT objectDetectionBodyFormat = sl.BODY_FORMAT.POSE_34;
  347. [HideInInspector]
  348. public sl.BODY_FORMAT bodyFormat = sl.BODY_FORMAT.POSE_34;
  349. /// <summary>
  350. /// Detection sensitivity. Represents how sure the SDK must be that an object exists to report it. Ex: If the threshold is 80, then only objects
  351. /// where the SDK is 80% sure or greater will appear in the list of detected objects.
  352. /// </summary>
  353. [HideInInspector]
  354. public int SK_personDetectionConfidenceThreshold = 50;
  355. /// <summary>
  356. /// Detection sensitivity. Represents how sure the SDK must be that an object exists to report it. Ex: If the threshold is 80, then only objects
  357. /// where the SDK is 80% sure or greater will appear in the list of detected objects.
  358. /// </summary>
  359. [HideInInspector]
  360. public int OD_personDetectionConfidenceThreshold = 60;
  361. /// <summary>
  362. /// Detection sensitivity. Represents how sure the SDK must be that an object exists to report it. Ex: If the threshold is 80, then only objects
  363. /// where the SDK is 80% sure or greater will appear in the list of detected objects.
  364. /// </summary>
  365. [HideInInspector]
  366. public int vehicleDetectionConfidenceThreshold = 60;
  367. /// <summary>
  368. /// Detection sensitivity. Represents how sure the SDK must be that an object exists to report it. Ex: If the threshold is 80, then only objects
  369. /// where the SDK is 80% sure or greater will appear in the list of detected objects.
  370. /// </summary>
  371. [HideInInspector]
  372. public int bagDetectionConfidenceThreshold = 60;
  373. /// <summary>
  374. /// Detection sensitivity. Represents how sure the SDK must be that an object exists to report it. Ex: If the threshold is 80, then only objects
  375. /// where the SDK is 80% sure or greater will appear in the list of detected objects.
  376. /// </summary>
  377. [HideInInspector]
  378. public int animalDetectionConfidenceThreshold = 60;
  379. /// <summary>
  380. /// Detection sensitivity. Represents how sure the SDK must be that an object exists to report it. Ex: If the threshold is 80, then only objects
  381. /// where the SDK is 80% sure or greater will appear in the list of detected objects.
  382. /// </summary>
  383. [HideInInspector]
  384. public int electronicsDetectionConfidenceThreshold = 60;
  385. /// <summary>
  386. /// Detection sensitivity. Represents how sure the SDK must be that an object exists to report it. Ex: If the threshold is 80, then only objects
  387. /// where the SDK is 80% sure or greater will appear in the list of detected objects.
  388. /// </summary>
  389. [HideInInspector]
  390. public int fruitVegetableDetectionConfidenceThreshold = 60;
  391. /// <summary>
  392. /// Detection sensitivity. Represents how sure the SDK must be that an object exists to report it. Ex: If the threshold is 80, then only objects
  393. /// where the SDK is 80% sure or greater will appear in the list of detected objects.
  394. /// </summary>
  395. [HideInInspector]
  396. public int sportDetectionConfidenceThreshold = 60;
  397. /// <summary>
  398. /// Whether to detect people during object detection.
  399. /// </summary>
  400. [HideInInspector]
  401. public bool objectClassPersonFilter = true;
  402. /// <summary>
  403. /// Whether to detect vehicles during object detection.
  404. /// </summary>
  405. [HideInInspector]
  406. public bool objectClassVehicleFilter = true;
  407. /// <summary>
  408. /// Whether to detect bags during object detection.
  409. /// </summary>
  410. [HideInInspector]
  411. public bool objectClassBagFilter = true;
  412. /// <summary>
  413. /// Whether to detect animals during object detection.
  414. /// </summary>
  415. [HideInInspector]
  416. public bool objectClassAnimalFilter = true;
  417. /// <summary>
  418. /// Whether to detect electronics during object detection.
  419. /// </summary>
  420. [HideInInspector]
  421. public bool objectClassElectronicsFilter = true;
  422. /// <summary>
  423. /// Whether to detect fruits and vegetables during object detection.
  424. /// </summary>
  425. [HideInInspector]
  426. public bool objectClassFruitVegetableFilter = true;
  427. /// <summary>
  428. /// Whether to detect sport related objects during object detection.
  429. /// </summary>
  430. [HideInInspector]
  431. public bool objectClassSportFilter = true;
  432. /// <summary>
  433. /// Whether the object detection module has been activated successfully.
  434. /// </summary>
  435. private bool objectDetectionRunning = false;
  436. /// <summary>
  437. /// Whether the object detection module has been activated successfully.
  438. /// </summary>
  439. public bool IsObjectDetectionRunning { get { return objectDetectionRunning; } }
  440. /// <summary>
  441. /// Set to true when there is not a fresh frame of detected objects waiting for processing, meaning we can retrieve the next one.
  442. /// </summary>
  443. private bool requestobjectsframe = true;
  444. /// <summary>
  445. /// Set to true when a new frame of detected objects has been retrieved in the image acquisition thread, ready for the main thread to process.
  446. /// </summary>
  447. private bool newobjectsframeready = false;
  448. /// <summary>
  449. /// Last object detection frame detected by the SDK. This data comes straight from the C++ SDK; see detectionFrame for an abstracted version
  450. /// with many helper functions for use inside Unity.
  451. /// </summary>
  452. private sl.ObjectsFrameSDK objectsFrameSDK = new sl.ObjectsFrameSDK();
  453. /// <summary>
  454. /// Last object detection frame detected by the SDK. This data comes straight from the C++ SDK; see GetDetectionFrame for an abstracted version
  455. /// with many helper functions for use inside Unity.
  456. /// </summary>
  457. public sl.ObjectsFrameSDK GetSDKObjectsFrame { get { return objectsFrameSDK; } }
  458. /// <summary>
  459. /// Timestamp of the most recent object frame fully processed. This is used to calculate the FPS of the object detection module.
  460. /// </summary>
  461. private ulong lastObjectFrameTimeStamp = 0;
  462. /// <summary>
  463. /// Frame rate at which the object detection module is running. Only reports performance; changing this value has no effect on detection.
  464. /// </summary>
  465. private float objDetectionModuleFPS = 15.0f;
  466. /// <summary>
  467. /// Last object detection frame detected by the SDK, in the form of a DetectionFrame instance which has many helper functions for use in Unity.
  468. /// </summary>
  469. private DetectionFrame detectionFrame;
  470. /// <summary>
  471. /// Last object detection frame detected by the SDK, in the form of a DetectionFrame instance which has many helper functions for use in Unity.
  472. /// </summary>
  473. public DetectionFrame GetDetectionFrame { get { return detectionFrame; } }
  474. /// <summary>
  475. /// Delegate for events that take an object detection frame straight from the SDK (not abstracted).
  476. /// </summary>
  477. public delegate void onNewDetectionTriggerSDKDelegate(sl.ObjectsFrameSDK objFrame);
  478. /// <summary>
  479. /// Event that's called whenever the Object Detection module detects a new frame.
  480. /// Includes data straight from the C++ SDK. See OnObjectDetection/DetectionFrame for an abstracted version that has many helper functions
  481. /// that makes it easier to use in Unity.
  482. /// </summary>
  483. public event onNewDetectionTriggerSDKDelegate OnObjectDetection_SDKData;
  484. /// <summary>
  485. /// Delegate for events that take an object detection frame, in the form of a DetectionFrame object which has helper functions.
  486. /// </summary>
  487. public delegate void onNewDetectionTriggerDelegate(DetectionFrame objFrame);
  488. /// <summary>
  489. /// Event that's called whenever the Object Detection module detects a new frame.
  490. /// Supplies data in the form of a DetectionFrame instance, which has many helper functions for use in Unity.
  491. /// </summary>
  492. public event onNewDetectionTriggerDelegate OnObjectDetection;
  493. private sl.dll_ObjectDetectionRuntimeParameters od_runtime_params = new sl.dll_ObjectDetectionRuntimeParameters();
  494. /////////////////////////////////////////////////////////////////////////
  495. ///////////////////////////// Rendering ///////////////////////////////////
  496. /////////////////////////////////////////////////////////////////////////
  497. /// <summary>
  498. /// Rendering paths available to the ZED with the corresponding Unity rendering path.
  499. /// </summary>
  500. public enum ZEDRenderingMode
  501. {
  502. FORWARD = RenderingPath.Forward,
  503. DEFERRED = RenderingPath.DeferredShading
  504. };
  505. /// <summary>
  506. /// When enabled, the real world can occlude (cover up) virtual objects that are behind it.
  507. /// Otherwise, virtual objects will appear in front.
  508. /// </summary>
  509. [HideInInspector]
  510. public bool depthOcclusion = true;
  511. /// <summary>
  512. /// Enables post-processing effects on virtual objects that blends them in with the real world.
  513. /// </summary>
  514. [HideInInspector]
  515. public bool postProcessing = true;
  516. /// <summary>
  517. /// Field version of CameraBrightness property.
  518. /// </summary>
  519. [SerializeField]
  520. [HideInInspector]
  521. private int m_cameraBrightness = 100;
  522. /// Brightness of the final real-world image. Default is 100. Lower to darken the environment in a realistic-looking way.
  523. /// This is a rendering setting that doesn't affect the raw input from the camera.
  524. /// </summary>
  525. public int CameraBrightness
  526. {
  527. get { return m_cameraBrightness; }
  528. set
  529. {
  530. if (m_cameraBrightness == value) return;
  531. m_cameraBrightness = value;
  532. if (OnCamBrightnessChange != null)
  533. OnCamBrightnessChange(m_cameraBrightness);
  534. }
  535. }
  536. /// <summary>
  537. /// Whether to enable the new color/gamma curve added to the ZED SDK in v3.0. Exposes more detail in darker regions
  538. /// and removes a slight red bias.
  539. /// </summary>
  540. [HideInInspector]
  541. [SerializeField]
  542. public bool enableImageEnhancement = true;
  543. /// Field version of MaxDepthRange property.
  544. /// </summary>
  545. [SerializeField]
  546. private float m_maxDepthRange = 40f;
  547. /// <summary>
  548. /// Maximum depth at which the camera will display the real world, in meters. Pixels further than this value will be invisible.
  549. /// </summary>
  550. [HideInInspector]
  551. public float MaxDepthRange
  552. {
  553. get { return m_maxDepthRange; }
  554. set
  555. {
  556. if (m_maxDepthRange == value) return;
  557. m_maxDepthRange = value;
  558. if (OnMaxDepthChange != null)
  559. OnMaxDepthChange(m_maxDepthRange);
  560. }
  561. }
  562. /////////////////////////////////////////////////////////////////////////
  563. ///////////////////////// Recording Module //////////////////////////////
  564. /////////////////////////////////////////////////////////////////////////
  565. /// <summary>
  566. /// SVO Output file name
  567. /// </summary>
  568. [HideInInspector]
  569. public string svoOutputFileName = "Assets/Recording.svo";
  570. /// <summary>
  571. /// SVO Compression mode used for recording
  572. /// </summary>
  573. [HideInInspector]
  574. public sl.SVO_COMPRESSION_MODE svoOutputCompressionMode = sl.SVO_COMPRESSION_MODE.H264_BASED;
  575. /// <summary>
  576. /// SVO specific bitrate in KBits/s
  577. /// Default : 0 = internal bitrate
  578. /// </summary>
  579. [HideInInspector]
  580. public int svoOutputBitrate = 0;
  581. /// <summary>
  582. /// SVO specific FPS
  583. /// Default : 0 = Camera FPS
  584. /// </summary>
  585. [HideInInspector]
  586. public int svoOutputTargetFPS = 0;
  587. /// <summary>
  588. /// If input is streaming, then set to direct-dump into SVO file (false) or decoding/re-encoding (true).
  589. /// Recommended to leave at false to save an encoding session.
  590. /// </summary>
  591. public bool svoOutputTranscodeStreaming = false;
  592. /// <summary>
  593. /// Indicates if frame must be recorded
  594. /// </summary>
  595. [HideInInspector]
  596. public bool needRecordFrame = false;
  597. /////////////////////////////////////////////////////////////////////////
  598. ///////////////////////// Streaming Module //////////////////////////////
  599. /////////////////////////////////////////////////////////////////////////
  600. /// <summary>
  601. /// Enable/Disable Streaming module
  602. /// </summary>
  603. [HideInInspector]
  604. public bool enableStreaming = false;
  605. /// <summary>
  606. /// Status of streaming request
  607. /// </summary>
  608. private bool isStreamingEnable = false;
  609. /// <summary>
  610. /// Codec used for Streaming
  611. /// </summary>
  612. [HideInInspector]
  613. public sl.STREAMING_CODEC streamingCodec = sl.STREAMING_CODEC.AVCHD_BASED;
  614. /// <summary>
  615. /// port used for Streaming
  616. /// </summary>
  617. [HideInInspector]
  618. public int streamingPort = 30000;
  619. /// <summary>
  620. /// bitrate used for Streaming
  621. /// </summary>
  622. [HideInInspector]
  623. public int bitrate = 8000;
  624. /// <summary>
  625. /// gop size used for Streaming
  626. /// </summary>
  627. [HideInInspector]
  628. public int gopSize = -1;
  629. /// <summary>
  630. /// Enable/Disable adaptative bitrate
  631. /// </summary>
  632. [HideInInspector]
  633. public bool adaptativeBitrate = false;
  634. /// <summary>
  635. /// Enable/Disable adaptative bitrate
  636. /// </summary>
  637. [HideInInspector]
  638. public int chunkSize = 8096;
  639. /// <summary>
  640. /// Set a specific target for the streaming framerate
  641. /// </summary>
  642. [HideInInspector]
  643. public int streamingTargetFramerate = 0;
  644. /////////////////////////////////////////////////////////////////////////
  645. ///////////////////////// Advanced control /////////////////////////////
  646. /////////////////////////////////////////////////////////////////////////
  647. ///
  648. /// <summary>
  649. /// True to make the ZED image fade from black when the application starts.
  650. /// </summary>
  651. [HideInInspector]
  652. public bool fadeInOnStart = true;
  653. /// <summary>
  654. /// True to apply DontDestroyOnLoad() on the ZED rig in Awake(), preserving it between scenes.
  655. /// </summary>
  656. [HideInInspector]
  657. public bool dontDestroyOnLoad = false;
  658. /// <summary>
  659. /// Grey Out Skybox on Start", "True to set the background to a neutral gray when the scene starts.
  660. /// Recommended for AR so that lighting on virtual objects better matches the real world.
  661. /// </summary>
  662. [HideInInspector]
  663. public bool greySkybox = true;
  664. /// <summary>
  665. /// Field version of confidenceThreshold property.
  666. /// </summary>
  667. [SerializeField]
  668. [HideInInspector]
  669. private int m_confidenceThreshold = 100;
  670. /// <summary>
  671. /// How tolerant the ZED SDK is to low confidence values. Lower values filter more pixels.
  672. /// </summary>
  673. public int confidenceThreshold
  674. {
  675. get
  676. {
  677. return m_confidenceThreshold;
  678. }
  679. set
  680. {
  681. if (value == m_confidenceThreshold) return;
  682. m_confidenceThreshold = Mathf.RoundToInt(Mathf.Clamp(value, 0, 100));
  683. if (Application.isPlaying && zedReady)
  684. {
  685. runtimeParameters.confidenceThreshold = m_confidenceThreshold;
  686. }
  687. }
  688. }
  689. [SerializeField]
  690. [HideInInspector]
  691. private int m_textureConfidenceThreshold = 100;
  692. /// <summary>
  693. /// How tolerant the ZED SDK is to low confidence values. Lower values filter more pixels.
  694. /// </summary>
  695. public int textureConfidenceThreshold
  696. {
  697. get
  698. {
  699. return m_textureConfidenceThreshold;
  700. }
  701. set
  702. {
  703. if (value == m_textureConfidenceThreshold) return;
  704. m_textureConfidenceThreshold = Mathf.RoundToInt(Mathf.Clamp(value, 0, 100));
  705. if (Application.isPlaying && zedReady)
  706. {
  707. runtimeParameters.textureConfidenceThreshold = m_textureConfidenceThreshold;
  708. }
  709. }
  710. }
  711. /// <summary>
  712. /// Options for enabling the depth measurement map for the right camera. Costs performance if on, even if not used.
  713. /// </summary>
  714. public enum RightDepthEnabledMode
  715. {
  716. /// <summary>
  717. /// Right depth measure will be enabled if a ZEDRenderingPlane component set to the right eye is detected as a child of
  718. /// ZEDManager's GameObject, as in the ZED rig prefabs.
  719. /// </summary>
  720. AUTO,
  721. /// <summary>
  722. /// Right depth measure is disabled.
  723. /// </summary>
  724. OFF,
  725. /// <summary>
  726. /// Right depth measure is enabled.
  727. /// </summary>
  728. ON
  729. }
  730. /// <summary>
  731. /// Whether to enable depth measurements from the right camera. Required for depth effects in AR pass-through, but requires performance even if not used.
  732. /// Auto enables it only if a ZEDRenderingPlane component set to the right eye is detected as a child of ZEDManager's GameObject (as in the ZED rig prefabs.)
  733. /// </summary>
  734. [HideInInspector]
  735. public RightDepthEnabledMode enableRightDepthMeasure = RightDepthEnabledMode.AUTO;
  736. /// <summary>
  737. /// Delegate for OnCamBrightnessChange, which is used to update shader properties when the brightness setting changes.
  738. /// </summary>
  739. public delegate void onCamBrightnessChangeDelegate(int newVal);
  740. /// <summary>
  741. /// Event fired when the camera brightness setting is changed. Used to update shader properties.
  742. /// </summary>
  743. public event onCamBrightnessChangeDelegate OnCamBrightnessChange;
  744. /// <summary>
  745. /// Delegate for OnCamBrightnessChange, which is used to update shader properties when the max depth setting changes.
  746. /// </summary>
  747. public delegate void onMaxDepthChangeDelegate(float newVal);
  748. /// <summary>
  749. /// Event fired when the max depth setting is changed. Used to update shader properties.
  750. /// </summary>
  751. public event onMaxDepthChangeDelegate OnMaxDepthChange;
  752. /// <summary>
  753. /// Whether to show the hidden camera rig used in stereo AR mode to prepare images for HMD output.
  754. /// </summary>
  755. [SerializeField]
  756. [HideInInspector]
  757. private bool showarrig = false;
  758. /// <summary>
  759. /// Whether to show the hidden camera rig used in stereo AR mode to prepare images for HMD output.
  760. /// <para>This is rarely needed, but can be useful for understanding how the ZED output works.</para>
  761. /// </summary>
  762. public bool showARRig
  763. {
  764. get
  765. {
  766. return showarrig;
  767. }
  768. set
  769. {
  770. if (Application.isPlaying && showarrig != value && zedRigDisplayer != null)
  771. {
  772. zedRigDisplayer.hideFlags = value ? HideFlags.None : HideFlags.HideInHierarchy;
  773. }
  774. showarrig = value;
  775. }
  776. }
  777. private float maxdepthrange = 40f;
  778. public float maxDepthRange
  779. {
  780. get
  781. {
  782. return maxdepthrange;
  783. }
  784. set
  785. {
  786. maxdepthrange = Mathf.Clamp(value, 0, 40);
  787. if (Application.isPlaying)
  788. {
  789. setRenderingSettings();
  790. }
  791. }
  792. }
  793. /// <summary>
  794. /// If true, and you are using a ZED2 or ZED Mini, IMU fusion uses data from the camera's IMU to improve tracking results.
  795. /// </summary>
  796. [HideInInspector]
  797. public bool enableIMUFusion = true;
  798. /// <summary>
  799. /// If true, the ZED SDK will subtly adjust the ZED's calibration during runtime to account for heat and other factors.
  800. /// Reasons to disable this are rare.
  801. /// </summary>
  802. [HideInInspector]
  803. public bool enableSelfCalibration = true;
  804. /////////////////////////////////////////////////////////////////////////
  805. ///////////////////////// Video Settings ////////////////////////////////
  806. /////////////////////////////////////////////////////////////////////////
  807. //Controls for the ZED's video settings (brightness, saturation, exposure, etc.)
  808. /// <summary>
  809. /// Behavior options for how the ZED's video settings (brightness, saturation, etc.) are applied when the ZED first connects.
  810. /// </summary>
  811. public enum VideoSettingsInitMode
  812. {
  813. /// <summary>
  814. /// Camera will be assigned video settings set in ZEDManager's Inspector before running the scene.
  815. /// </summary>
  816. Custom,
  817. /// <summary>
  818. /// Camera will load settings last applied to the ZED. May have been from a source outside Unity.
  819. /// This is the default behavior in the ZED SDK and most ZED apps.
  820. /// </summary>
  821. LoadFromSDK,
  822. /// <summary>
  823. /// Camera will load default video settings.
  824. /// </summary>
  825. Default
  826. }
  827. /// <summary>
  828. /// How the ZED's video settings (brightness, saturation, etc.) are applied when the ZED first connects.
  829. /// </summary>
  830. public VideoSettingsInitMode videoSettingsInitMode = VideoSettingsInitMode.Custom;
  831. /// <summary>
  832. /// Brightness setting for the ZED camera itself.
  833. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  834. /// </summary>
  835. [SerializeField]
  836. private int videoBrightness = 4;
  837. /// <summary>
  838. /// Contrast setting for the ZED camera itself.
  839. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  840. /// </summary>
  841. [SerializeField]
  842. private int videoContrast = 4;
  843. /// <summary>
  844. /// Hue setting for the ZED camera itself.
  845. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  846. /// </summary>
  847. [SerializeField]
  848. private int videoHue = 0;
  849. /// <summary>
  850. /// Saturation setting for the ZED camera itself.
  851. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  852. /// </summary>
  853. [SerializeField]
  854. private int videoSaturation = 4;
  855. /// <summary>
  856. /// Auto gain/exposure setting for the ZED camera itself.
  857. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  858. /// </summary>
  859. [SerializeField]
  860. private bool videoAutoGainExposure = true;
  861. /// <summary>
  862. /// Gain setting for the ZED camera itself.
  863. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom and videoAutoGainExposure is false.
  864. /// </summary>
  865. [SerializeField]
  866. private int videoGain = 10;
  867. /// <summary>
  868. /// Exposure setting for the ZED camera itself.
  869. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom and videoAutoGainExposure is false.
  870. /// </summary>
  871. [SerializeField]
  872. public int videoExposure = 100;
  873. /// <summary>
  874. /// Auto White Balance setting for the ZED camera itself.
  875. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  876. /// </summary>
  877. [SerializeField]
  878. private bool videoAutoWhiteBalance = true;
  879. /// <summary>
  880. /// White Balance temperature setting for the ZED camera itself.
  881. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom and videoAutoWhiteBalance is false.
  882. /// </summary>
  883. [SerializeField]
  884. private int videoWhiteBalance = 3200;
  885. /// <summary>
  886. /// Sharpness setting for the ZED camera itself.
  887. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  888. /// </summary>
  889. [SerializeField]
  890. private int videoSharpness = 3;
  891. /// <summary>
  892. /// Sharpness setting for the ZED camera itself.
  893. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  894. /// </summary>
  895. [SerializeField]
  896. private int videoGamma = 5;
  897. /// <summary>
  898. /// Whether the LED on the ZED camera is on.
  899. /// Serialized value is applied to the camera on start when videoSettingsInitMode is set to Custom.
  900. /// </summary>
  901. [SerializeField]
  902. private bool videoLEDStatus = true;
  903. /////////////////////////////////////////////////////////////////////////
  904. ///////////////////////// Status Report /////////////////////////////////
  905. /////////////////////////////////////////////////////////////////////////
  906. //Strings used for the Status display in the Inspector.
  907. [Header("Status")]
  908. /// <summary>
  909. /// The camera model (ZED or ZED-M).
  910. /// </summary>
  911. [ReadOnly("Camera S/N")] [HideInInspector] public string cameraModel = "-";
  912. /// <summary>
  913. /// The camera serial number.
  914. /// </summary>
  915. [ReadOnly("Camera S/N")] [HideInInspector] public string cameraSerialNumber = "-";
  916. /// <summary>
  917. /// The camera firmware version
  918. /// </summary>
  919. [ReadOnly("Camera Firmware")] [HideInInspector] public string cameraFirmware = "-";
  920. /// <summary>
  921. /// Version of the installed ZED SDK, for display in the Inspector.
  922. /// </summary>
  923. [ReadOnly("Version")] [HideInInspector] public string versionZED = "-";
  924. /// <summary>
  925. /// How many frames per second the engine is rendering, for display in the Inspector.
  926. /// </summary>
  927. [ReadOnly("Engine FPS")] [HideInInspector] public string engineFPS = "-";
  928. /// <summary>
  929. /// How many images per second are received from the ZED, for display in the Inspector.
  930. /// </summary>
  931. [ReadOnly("Camera FPS")] [HideInInspector] public string cameraFPS = "-";
  932. /// <summary>
  933. /// The connected VR headset, if any, for display in the Inspector.
  934. /// </summary>
  935. [ReadOnly("HMD Device")] [HideInInspector] public string HMDDevice = "-";
  936. /// <summary>
  937. /// Whether the ZED's tracking is on, off, or searching (lost position, trying to recover) for display in the Inspector.
  938. /// </summary>
  939. [ReadOnly("Tracking State")] [HideInInspector] public string trackingState = "-";
  940. /// <summary>
  941. /// Object detection framerate
  942. /// </summary>
  943. [ReadOnly("Object Detection FPS")] [HideInInspector] public string objectDetectionFPS = "-";
  944. ////////////////////////////
  945. //////// Private ///////////
  946. ////////////////////////////
  947. /// <summary>
  948. /// Initialization parameters used to start the ZED. Holds settings that can't be changed at runtime
  949. /// (resolution, depth mode, .SVO path, etc.).
  950. /// </summary>
  951. private sl.InitParameters initParameters;
  952. /// <summary>
  953. /// Runtime parameters used to grab a new image. Settings can change each frame, but are lower level
  954. /// (sensing mode, point cloud, if depth is enabled, etc.).
  955. /// </summary>
  956. private sl.RuntimeParameters runtimeParameters;
  957. /// <summary>
  958. /// Enables the ZED SDK's depth stabilizer, which improves depth accuracy and stability. There's rarely a reason to disable this.
  959. /// </summary>
  960. private bool depthStabilizer = true;
  961. /// <summary>
  962. /// Indicates if Sensors( IMU,...) is needed/required. For most applications, it is required.
  963. /// Sensors are transmitted through USB2.0 lines. If USB2 is not available (USB3.0 only extension for example), set it to false.
  964. /// </summary>
  965. private bool sensorsRequired = false;
  966. /// <summary>
  967. /// Set the camera in Flip mode
  968. /// </summary>
  969. private sl.FLIP_MODE cameraFlipMode = sl.FLIP_MODE.AUTO;
  970. /// <summary>
  971. /// Whether the camera is currently being tracked using the ZED's inside-out tracking.
  972. /// </summary>ccvv
  973. private bool isZEDTracked = false;
  974. /// <summary>
  975. /// Whether the ZED's inside-out tracking has been activated.
  976. /// </summary>
  977. private bool isTrackingEnable = false;
  978. /// <summary>
  979. /// Whether the camera is tracked in any way (ZED's tracking or a VR headset's tracking).
  980. /// </summary>
  981. private bool isCameraTracked = false;
  982. /// <summary>
  983. /// Public accessor for whether the camera is tracked in any way (ZED's tracking or a VR headset's tracking).
  984. /// </summary>
  985. public bool IsCameraTracked
  986. {
  987. get { return isCameraTracked; }
  988. }
  989. /// <summary>
  990. /// Whether the camera has a new frame available.
  991. /// </summary>
  992. private bool isNewFrameGrabbed = false;
  993. /// <summary>
  994. /// Public accessor for whether the camera has a new frame available.
  995. /// </summary>
  996. public bool IsNewFrameGrabbed
  997. {
  998. get { return isNewFrameGrabbed; }
  999. }
  1000. /// <summary>
  1001. /// Orientation last returned by the ZED's tracking.
  1002. /// </summary>
  1003. private Quaternion zedOrientation = Quaternion.identity;
  1004. /// <summary>
  1005. /// Position last returned by the ZED's tracking.
  1006. /// </summary>
  1007. private Vector3 zedPosition = Vector3.zero;
  1008. /// <summary>
  1009. /// If Estimate Initial Position is true and we're in SVO mode with Loop enabled, we'll want to cache our first pose to initialPosition and initialRotation.
  1010. /// This flag lets us know if we've done that yet so we can only assign them on the first tracked frame.
  1011. /// </summary>
  1012. private bool initialPoseCached = false;
  1013. /// <summary>
  1014. /// Position of the camera (zedRigRoot) when the scene starts. Not used in Stereo AR.
  1015. /// </summary>
  1016. private Vector3 initialPosition = new Vector3();
  1017. /// <summary>
  1018. /// Orientation of the camera (zedRigRoot) when the scene starts. Not used in Stereo AR.
  1019. /// </summary>
  1020. private Quaternion initialRotation = Quaternion.identity;
  1021. /// <summary>
  1022. /// Sensing mode: STANDARD or FILL. FILL corrects for missing depth values.
  1023. /// Almost always better to use FILL, since we need depth without holes for proper occlusion.
  1024. /// </summary>
  1025. [SerializeField]
  1026. [HideInInspector]
  1027. public sl.SENSING_MODE sensingMode = sl.SENSING_MODE.FILL;
  1028. /// <summary>
  1029. /// Rotation offset used to retrieve the tracking with a rotational offset.
  1030. /// </summary>
  1031. private Quaternion rotationOffset;
  1032. /// <summary>
  1033. /// Position offset used to retrieve the tracking with a positional offset.
  1034. /// </summary>
  1035. private Vector3 positionOffset;
  1036. /// <summary>
  1037. /// Enables pose smoothing during drift correction. Leave it to true.
  1038. /// </summary>
  1039. private bool enablePoseSmoothing = true;
  1040. [HideInInspector]
  1041. public sl.ERROR_CODE ZEDGrabError = sl.ERROR_CODE.FAILURE;
  1042. #if UNITY_EDITOR
  1043. /// <summary>
  1044. /// The engine FPS, updated every frame.
  1045. /// </summary>
  1046. private float fps_engine = 90.0f;
  1047. #endif
  1048. /// <summary>
  1049. /// Recording state
  1050. /// </summary>
  1051. private bool isRecording = false;
  1052. ///////////////////////////////////////
  1053. /////////// Static States /////////////
  1054. ///////////////////////////////////////
  1055. /// <summary>
  1056. /// Whether AR mode is activated.
  1057. /// </summary>
  1058. private bool isStereoRig = false;
  1059. /// <summary>
  1060. /// Whether AR mode is activated. Assigned by ZEDManager.CheckStereoMode() in Awake().
  1061. /// Will be true if the ZED_Rig_Stereo prefab (or a similarly-structured prefab) is used.
  1062. /// </summary>
  1063. public bool IsStereoRig
  1064. {
  1065. get { return isStereoRig; }
  1066. }
  1067. /// <summary>
  1068. /// Checks if the ZED has finished initializing.
  1069. /// </summary>
  1070. private bool zedReady = false;
  1071. /// <summary>
  1072. /// Checks if the ZED has finished initializing.
  1073. /// </summary>
  1074. public bool IsZEDReady
  1075. {
  1076. get { return zedReady; }
  1077. }
  1078. /// <summary>
  1079. /// Flag set to true if the camera was connected and the wasn't anymore.
  1080. /// Causes ZEDDisconnected() to be called each frame, which attemps to restart it.
  1081. /// </summary>
  1082. private bool isDisconnected = false;
  1083. /// <summary>
  1084. /// Current state of tracking: On, Off, or Searching (lost tracking, trying to recover). Used by anti-drift.
  1085. /// </summary>
  1086. private sl.TRACKING_STATE zedtrackingState = sl.TRACKING_STATE.TRACKING_OFF;
  1087. /// <summary>
  1088. /// Current state of tracking: On, Off, or Searching (lost tracking, trying to recover). Used by anti-drift.
  1089. /// </summary>
  1090. public sl.TRACKING_STATE ZEDTrackingState
  1091. {
  1092. get { return zedtrackingState; }
  1093. }
  1094. /// <summary>
  1095. /// First position registered after the tracking has started (whether via ZED or a VR HMD).
  1096. /// </summary>
  1097. public Vector3 OriginPosition { get; private set; }
  1098. /// <summary>
  1099. /// First rotation/orientation registered after the tracking has started (whether via ZED or a VR HMD).
  1100. /// </summary>
  1101. public Quaternion OriginRotation { get; private set; }
  1102. /// <summary>
  1103. /// In AR pass-through mode, whether to compare the ZED's IMU data against the reported position of
  1104. /// the VR headset. This helps compensate for drift and should usually be left on.
  1105. /// However, in some setups, like when using a custom mount, this can cause tracking errors.
  1106. /// </summary><remarks>
  1107. /// Read more about the potential errors here: https://support.stereolabs.com/hc/en-us/articles/360026482413
  1108. /// </remarks>
  1109. public bool setIMUPriorInAR = true;
  1110. /// <summary>
  1111. /// If true, the ZED rig will enter 'pass-through' mode if it detects a stereo rig - at least two cameras as children with ZEDRenderingPlane
  1112. /// components, each with a different eye) - and a VR headset is connected. If false, it will never enter pass-through mode.
  1113. /// </summary>
  1114. public bool allowARPassThrough = true;
  1115. ///////////////////////////////////////////////////
  1116. [HideInInspector] public Quaternion gravityRotation = Quaternion.identity;
  1117. [HideInInspector] public Vector3 ZEDSyncPosition;
  1118. [HideInInspector] public Vector3 HMDSyncPosition;
  1119. [HideInInspector] public Quaternion ZEDSyncRotation;
  1120. [HideInInspector] public Quaternion HMDSyncRotation;
  1121. /// <summary>
  1122. /// Image acquisition thread.
  1123. /// </summary>
  1124. private Thread threadGrab = null;
  1125. /// <summary>
  1126. /// State of the image acquisition thread.
  1127. /// </summary>
  1128. private bool running = false;
  1129. /// <summary>
  1130. /// Initialization thread.
  1131. /// </summary>
  1132. private Thread threadOpening = null;
  1133. /// <summary>
  1134. /// Result of the latest attempt to initialize the ZED.
  1135. /// </summary>
  1136. private sl.ERROR_CODE lastInitStatus = sl.ERROR_CODE.ERROR_CODE_LAST;
  1137. public sl.ERROR_CODE LastInitStatus { get { return lastInitStatus; } }
  1138. /// <summary>
  1139. /// State of the ZED initialization thread.
  1140. /// </summary>
  1141. private bool openingLaunched;
  1142. /// <summary>
  1143. /// Wait Handle used to safely tell the init thread to shut down.
  1144. /// </summary>
  1145. EventWaitHandle initQuittingHandle;
  1146. /// <summary>
  1147. /// When true, the init thread will close early instead of completing all its connection attempts.
  1148. /// Set to true when the application is closed before a camera finishes its initialization.
  1149. /// </summary>
  1150. private bool forceCloseInit = false;
  1151. /// <summary>
  1152. /// Tracking initialization thread. Used as the tracking takes some time to start.
  1153. /// </summary>
  1154. private Thread trackerThread = null;
  1155. ///////////////////////////////////////////
  1156. ////// Camera and Player Transforms //////
  1157. ///////////////////////////////////////////
  1158. /// <summary>
  1159. /// Transform of the left camera in the ZED rig.
  1160. /// </summary>
  1161. private Transform camLeftTransform = null;
  1162. /// <summary>
  1163. /// Transform of the right camera in the ZED rig. Only exists in a stereo rig (like ZED_Rig_Stereo).
  1164. /// </summary>
  1165. private Transform camRightTransform = null;
  1166. /// <summary>
  1167. /// Contains the position of the player's head, which is different from the ZED's position in AR mode.
  1168. /// But its position relative to the ZED does not change during use (it's a rigid transform).
  1169. /// In ZED_Rig_Mono, this will be the root ZED_Rig_Mono object. In ZED_Rig_Stereo, this is Camera_eyes.
  1170. /// </summary>
  1171. private Transform zedRigRoot = null;
  1172. /// <summary>
  1173. /// Left camera in the ZED rig. Also the "main" camera if in ZED_Rig_Mono.
  1174. /// </summary>
  1175. private Camera cameraLeft;
  1176. /// <summary>
  1177. /// Right camera of the ZED rig. Only exists in a stereo rig (like ZED_Rig_Stereo).
  1178. /// </summary>
  1179. private Camera cameraRight;
  1180. /// <summary>
  1181. /// Gets the center transform, which is the transform moved by the tracker in AR mode.
  1182. /// This is the root object in ZED_Rig_Mono, and Camera_eyes in ZED_Rig_Stereo.
  1183. /// </summary>
  1184. public Transform GetZedRootTansform()
  1185. {
  1186. return zedRigRoot;
  1187. }
  1188. /// <summary>
  1189. /// Returns the left ZED camera transform. If there is no left camera but there is a right camera,
  1190. /// returns the right camera transform instead.
  1191. /// </summary>
  1192. /// <returns></returns>
  1193. public Transform GetMainCameraTransform()
  1194. {
  1195. if (camLeftTransform) return camLeftTransform;
  1196. else if (camRightTransform) return camRightTransform;
  1197. else return null;
  1198. }
  1199. /// <summary>
  1200. /// Gets the left camera transform in the ZED rig. It's best to use this one as it's available in all configurations.
  1201. /// </summary>
  1202. public Transform GetLeftCameraTransform()
  1203. {
  1204. return camLeftTransform;
  1205. }
  1206. /// <summary>
  1207. /// Get the right camera transform in the ZED rig. Only available in the stereo rig (ZED_Rig_Stereo).
  1208. /// </summary>
  1209. public Transform GetRightCameraTransform()
  1210. {
  1211. return camRightTransform;
  1212. }
  1213. /// <summary>
  1214. /// Returns the left ZED camera. If there is no left camera but there is a right camera,
  1215. /// returns the right camera instead.
  1216. /// </summary>
  1217. /// <returns></returns>
  1218. public Camera GetMainCamera()
  1219. {
  1220. if (cameraLeft) return cameraLeft;
  1221. else if (cameraRight) return cameraRight;
  1222. else return null;
  1223. }
  1224. /// <summary>
  1225. /// Gets the left camera in the ZED rig. Both ZED_Rig_Mono and ZED_Rig_Stereo have a left camera by default.
  1226. /// </summary>
  1227. public Camera GetLeftCamera()
  1228. {
  1229. if (cameraLeft == null && camLeftTransform != null)
  1230. cameraLeft = camLeftTransform.GetComponent<Camera>();
  1231. return cameraLeft;
  1232. }
  1233. /// <summary>
  1234. /// Get the right camera in the ZED rig. Only available in the stereo rig (ZED_Rig_Stereo) unless configured otherwise.
  1235. /// </summary>
  1236. public Camera GetRightCamera()
  1237. {
  1238. if (cameraRight == null && camRightTransform != null)
  1239. cameraRight = camRightTransform.GetComponent<Camera>();
  1240. return cameraRight;
  1241. }
  1242. #pragma warning disable 414
  1243. /// <summary>
  1244. /// Save the foldout options as it was used last time
  1245. /// </summary>
  1246. [SerializeField]
  1247. [HideInInspector]
  1248. private bool advancedPanelOpen = false;
  1249. [SerializeField]
  1250. [HideInInspector]
  1251. private bool spatialMappingFoldoutOpen = false;
  1252. [SerializeField]
  1253. [HideInInspector]
  1254. private bool objectDetectionFoldoutOpen = false;
  1255. [SerializeField]
  1256. [HideInInspector]
  1257. private bool recordingFoldoutOpen = false;
  1258. [SerializeField]
  1259. [HideInInspector]
  1260. private bool streamingOutFoldoutOpen = false;
  1261. [SerializeField]
  1262. [HideInInspector]
  1263. private bool camControlFoldoutOpen = false;
  1264. #pragma warning restore 414
  1265. /////////////////////////////////////
  1266. ////// Timestamps //////
  1267. /////////////////////////////////////
  1268. /// <summary>
  1269. /// Timestamp of the last ZED image grabbed. Textures from this grab may not have updated yet.
  1270. /// </summary>
  1271. private ulong cameraTimeStamp = 0;
  1272. /// <summary>
  1273. /// Timestamp of the last ZED image grabbed. Textures from this grab may not have updated yet.
  1274. /// </summary>
  1275. public ulong CameraTimeStamp
  1276. {
  1277. get { return cameraTimeStamp; }
  1278. }
  1279. /// <summary>
  1280. /// Timestamp of the images used to create the current textures.
  1281. /// </summary>
  1282. private ulong imageTimeStamp = 0;
  1283. /// <summary>
  1284. /// Timestamp of the images used to create the current textures.
  1285. /// </summary>
  1286. public ulong ImageTimeStamp
  1287. {
  1288. get { return imageTimeStamp; }
  1289. }
  1290. /// <summary>
  1291. /// Whether the grabbing thread should grab a new frame from the ZED SDK.
  1292. /// True unless the last grabbed frame hasn't been applied yet, or the ZED isn't initialized.
  1293. /// </summary>
  1294. private bool requestNewFrame = false;
  1295. /// <summary>
  1296. /// Whether a new frame has been grabbed from the ZED SDK that needs to be updated.
  1297. /// </summary>
  1298. private bool newFrameAvailable = false;
  1299. /////////////////////////////////////
  1300. ////// Layers for ZED //////
  1301. /////////////////////////////////////
  1302. /// <summary>
  1303. /// Layer assigned to the cameras and objects of a (normally hidden) AR camera rig created to handle
  1304. /// pass-through AR. This allows the cameras to see nothing but two canvas objects with the final MR images.
  1305. /// </summary>
  1306. [HideInInspector]
  1307. public int arLayer
  1308. {
  1309. get
  1310. {
  1311. return ZEDLayers.arlayer;
  1312. }
  1313. }
  1314. [SerializeField]
  1315. [HideInInspector]
  1316. //private int arlayer = 30;
  1317. /////////////////////////////////////
  1318. ////// ZED specific events //////
  1319. /////////////////////////////////////
  1320. /// <summary>
  1321. /// Delegate for OnZEDReady.
  1322. /// </summary>
  1323. public delegate void OnZEDManagerReady();
  1324. /// <summary>
  1325. /// Called when the ZED has finished initializing successfully.
  1326. /// Used by many scripts to run startup logic that requires that the ZED is active.
  1327. /// </summary>
  1328. public event OnZEDManagerReady OnZEDReady;
  1329. /// <summary>
  1330. /// Delegate for OnZEDDisconnected.
  1331. /// </summary>
  1332. public delegate void OnZEDManagerDisconnected();
  1333. /// <summary>
  1334. /// Event called when ZED was running but became disconnected.
  1335. /// </summary>
  1336. public event OnZEDManagerDisconnected OnZEDDisconnected;
  1337. /// <summary>
  1338. /// Delegate for new Frame grabbed for external module update
  1339. /// </summary>
  1340. public delegate void OnGrabAction();
  1341. /// <summary>
  1342. /// Event called when ZED has grabbed a new frame.
  1343. /// </summary>
  1344. public event OnGrabAction OnGrab;
  1345. #region CHECK_AR
  1346. private bool hasXRDevice()
  1347. {
  1348. #if UNITY_2020_1_OR_NEWER
  1349. var xrDisplaySubsystems = new List<XRDisplaySubsystem>();
  1350. SubsystemManager.GetInstances<XRDisplaySubsystem>(xrDisplaySubsystems);
  1351. foreach (var xrDisplay in xrDisplaySubsystems)
  1352. {
  1353. if (xrDisplay.running)
  1354. {
  1355. return true;
  1356. }
  1357. }
  1358. return false;
  1359. #else
  1360. return XRDevice.isPresent;
  1361. #endif
  1362. }
  1363. /// <summary>
  1364. /// Checks if this GameObject is a stereo rig. Requires a child object called 'Camera_eyes' and
  1365. /// two cameras as children of that object, one with stereoTargetEye set to Left, the other two Right.
  1366. /// Regardless, sets references to leftCamera and (if relevant) rightCamera.
  1367. /// </summary>
  1368. private void CheckStereoMode()
  1369. {
  1370. zedRigRoot = gameObject.transform; //The object moved by tracking. By default it's this Transform. May get changed.
  1371. bool devicePresent = hasXRDevice(); //May not need.
  1372. //Set first left eye
  1373. Component[] cams = gameObject.GetComponentsInChildren<Camera>();
  1374. //Camera firstmonocam = null;
  1375. List<Camera> monocams = new List<Camera>();
  1376. foreach (Camera cam in cams)
  1377. {
  1378. switch (cam.stereoTargetEye)
  1379. {
  1380. case StereoTargetEyeMask.Left:
  1381. if (!cameraLeft)
  1382. {
  1383. cameraLeft = cam;
  1384. camLeftTransform = cam.transform;
  1385. }
  1386. break;
  1387. case StereoTargetEyeMask.Right:
  1388. if (!cameraRight)
  1389. {
  1390. cameraRight = cam;
  1391. camRightTransform = cam.transform;
  1392. }
  1393. break;
  1394. case StereoTargetEyeMask.None:
  1395. monocams.Add(cam);
  1396. break;
  1397. case StereoTargetEyeMask.Both:
  1398. default:
  1399. break;
  1400. }
  1401. }
  1402. //If the left camera or right camera haven't been assigned via stereo target eyes, search the monocams
  1403. //based on their ZEDRenderingPlane assignments.
  1404. //This won't affect whether the rig is in stereo mode, but allows the cameras to be accessed via GetLeftCamera() and GetRightCamera().
  1405. if (cameraLeft == null || cameraRight == null)
  1406. {
  1407. foreach (Camera cam in monocams)
  1408. {
  1409. ZEDRenderingPlane rendplane = cam.gameObject.GetComponent<ZEDRenderingPlane>();
  1410. if (!rendplane) continue;
  1411. if (!cameraLeft && (rendplane.viewSide == ZEDRenderingPlane.ZED_CAMERA_SIDE.LEFT || rendplane.viewSide == ZEDRenderingPlane.ZED_CAMERA_SIDE.LEFT_FORCE))
  1412. {
  1413. cameraLeft = cam;
  1414. camLeftTransform = cam.transform;
  1415. }
  1416. else if (!cameraRight && (rendplane.viewSide == ZEDRenderingPlane.ZED_CAMERA_SIDE.RIGHT || rendplane.viewSide == ZEDRenderingPlane.ZED_CAMERA_SIDE.RIGHT_FORCE))
  1417. {
  1418. cameraRight = cam;
  1419. camRightTransform = cam.transform;
  1420. }
  1421. }
  1422. }
  1423. if (camLeftTransform && camRightTransform && cameraLeft.stereoTargetEye == StereoTargetEyeMask.Left) //We found both a left- and right-eye camera.
  1424. {
  1425. if (camLeftTransform.transform.parent != null)
  1426. {
  1427. zedRigRoot = camLeftTransform.parent; //Make the camera's parent object (Camera_eyes in the ZED_Rig_Stereo prefab) the new zedRigRoot to be tracked.
  1428. }
  1429. if (hasXRDevice() && allowARPassThrough)
  1430. {
  1431. isStereoRig = true;
  1432. }
  1433. else
  1434. {
  1435. isStereoRig = false;
  1436. //If there's no VR headset, then cameras set to Left and Right won't display in Unity. Set them both to None.
  1437. if (cameraLeft) cameraLeft.stereoTargetEye = StereoTargetEyeMask.None;
  1438. if (cameraRight) cameraRight.stereoTargetEye = StereoTargetEyeMask.None;
  1439. }
  1440. }
  1441. else //Not all conditions for a stereo rig were met.
  1442. {
  1443. isStereoRig = false;
  1444. if (camLeftTransform)
  1445. {
  1446. Camera caml = camLeftTransform.gameObject.GetComponent<Camera>();
  1447. cameraLeft = caml;
  1448. if (camLeftTransform.transform.parent != null)
  1449. zedRigRoot = camLeftTransform.parent;
  1450. }
  1451. else
  1452. {
  1453. zedRigRoot = transform;
  1454. }
  1455. }
  1456. }
  1457. #endregion
  1458. /// <summary>
  1459. /// Sets the target GameObject and all its children to the specified layer.
  1460. /// </summary>
  1461. /// <param name="go">Target GameObject.</param>
  1462. /// <param name="layerNumber">Layer that the GameObject and all children will be set to.</param>
  1463. public static void SetLayerRecursively(GameObject go, int layerNumber)
  1464. {
  1465. if (go == null) return;
  1466. foreach (Transform trans in go.GetComponentsInChildren<Transform>(true))
  1467. {
  1468. trans.gameObject.layer = layerNumber;
  1469. }
  1470. }
  1471. /// <summary>
  1472. /// Stops the initialization and grabbing threads.
  1473. /// </summary>
  1474. public void Destroy()
  1475. {
  1476. running = false;
  1477. //In case the opening thread is still running.
  1478. if (threadOpening != null)
  1479. {
  1480. initQuittingHandle.Reset();
  1481. forceCloseInit = true;
  1482. initQuittingHandle.Set();
  1483. threadOpening.Join();
  1484. threadOpening = null;
  1485. }
  1486. //Shut down the image grabbing thread.
  1487. if (threadGrab != null)
  1488. {
  1489. threadGrab.Join();
  1490. threadGrab = null;
  1491. }
  1492. if (IsMappingRunning)
  1493. StopSpatialMapping();
  1494. Thread.Sleep(10);
  1495. }
  1496. /// <summary>
  1497. /// Called by Unity when the application is closed.
  1498. /// Also called by Reset() to properly start from a 'clean slate.'
  1499. /// </summary>
  1500. private void OnApplicationQuit()
  1501. {
  1502. CloseManager();
  1503. //sl.ZEDCamera.UnloadPlugin();
  1504. //If this was the last camera to close, make sure all instances are closed.
  1505. bool notlast = false;
  1506. foreach (ZEDManager manager in ZEDManagerInstance)
  1507. {
  1508. if (manager != null && manager.IsZEDReady == true)
  1509. {
  1510. notlast = true;
  1511. break;
  1512. }
  1513. }
  1514. if (notlast == false)
  1515. {
  1516. sl.ZEDCamera.UnloadPlugin();
  1517. }
  1518. }
  1519. private void CloseManager()
  1520. {
  1521. if (spatialMapping != null)
  1522. spatialMapping.Dispose();
  1523. if (IsObjectDetectionRunning)
  1524. {
  1525. StopObjectDetection();
  1526. }
  1527. #if !ZED_HDRP && !ZED_URP
  1528. ClearRendering();
  1529. #endif
  1530. zedReady = false;
  1531. OnCamBrightnessChange -= SetCameraBrightness;
  1532. OnMaxDepthChange -= SetMaxDepthRange;
  1533. Destroy(); //Close the grab and initialization threads.
  1534. if (zedCamera != null)
  1535. {
  1536. if (isRecording)
  1537. {
  1538. zedCamera.DisableRecording();
  1539. }
  1540. zedCamera.Destroy();
  1541. zedCamera = null;
  1542. }
  1543. #if UNITY_EDITOR //Prevents building the app otherwise.
  1544. //Restore the AR layers that were hidden, if necessary.
  1545. if (!showarrig)
  1546. {
  1547. LayerMask layerNumberBinary = (1 << arLayer); //Convert layer index into binary number.
  1548. UnityEditor.Tools.visibleLayers |= (layerNumberBinary);
  1549. }
  1550. #endif
  1551. sl.ZEDCamera.UnloadInstance((int)cameraID);
  1552. }
  1553. #if !ZED_HDRP && !ZED_URP
  1554. private void ClearRendering()
  1555. {
  1556. if (camLeftTransform != null)
  1557. {
  1558. ZEDRenderingPlane leftRenderingPlane = camLeftTransform.GetComponent<ZEDRenderingPlane>();
  1559. if (leftRenderingPlane)
  1560. {
  1561. leftRenderingPlane.Clear();
  1562. }
  1563. }
  1564. if (IsStereoRig)
  1565. {
  1566. ZEDRenderingPlane rightRenderingPlane = GetRightCameraTransform().GetComponent<ZEDRenderingPlane>();
  1567. rightRenderingPlane.Clear();
  1568. }
  1569. }
  1570. #endif
  1571. /// <summary>
  1572. /// Sets up starting properties and starts the ZED initialization co-routine.
  1573. /// </summary>
  1574. void Awake()
  1575. {
  1576. // If never initialized, init the array of instances linked to each ZEDManager that could be created.
  1577. if (ZEDManagerInstance == null)
  1578. {
  1579. ZEDManagerInstance = new ZEDManager[(int)sl.Constant.MAX_CAMERA_PLUGIN];
  1580. for (int i = 0; i < (int)sl.Constant.MAX_CAMERA_PLUGIN; i++)
  1581. ZEDManagerInstance[i] = null;
  1582. }
  1583. initialPosition = transform.localPosition;
  1584. initialRotation = transform.localRotation;
  1585. zedReady = false;
  1586. ZEDManagerInstance[(int)cameraID] = this;
  1587. zedCamera = new sl.ZEDCamera();
  1588. if (dontDestroyOnLoad) DontDestroyOnLoad(transform.root); //If you want the ZED rig not to be destroyed when loading a scene.
  1589. //Set first few parameters for initialization. This will get passed to the ZED SDK when initialized.
  1590. initParameters = new sl.InitParameters();
  1591. initParameters.resolution = resolution;
  1592. initParameters.cameraFPS = FPS;
  1593. initParameters.cameraDeviceID = (int)cameraID;
  1594. initParameters.depthMode = depthMode;
  1595. initParameters.depthStabilization = depthStabilizer;
  1596. initParameters.sensorsRequired = sensorsRequired;
  1597. initParameters.depthMaximumDistance = 40.0f; // 40 meters should be enough for all applications
  1598. initParameters.cameraImageFlip = (int)cameraFlipMode;
  1599. initParameters.enableImageEnhancement = enableImageEnhancement;
  1600. initParameters.cameraDisableSelfCalib = !enableSelfCalibration;
  1601. initParameters.optionalOpencvCalibrationFile = opencvCalibFile;
  1602. //Check if this rig is a stereo rig. Will set isStereoRig accordingly.
  1603. CheckStereoMode();
  1604. //Set initialization parameters that may change depending on what was done in CheckStereoMode().
  1605. isZEDTracked = enableTracking;
  1606. zedPosition = initialPosition;
  1607. zedOrientation = initialRotation;
  1608. lastInitStatus = sl.ERROR_CODE.ERROR_CODE_LAST;
  1609. bool res = zedCamera.CreateCamera((int)cameraID, wrapperVerbose);
  1610. if (!res)
  1611. {
  1612. Debug.LogError("ZEDManager on " + gameObject.name + " couldn't connect to camera: " + cameraID +
  1613. ". Check if another ZEDManager is already connected.");
  1614. this.gameObject.SetActive(false);
  1615. return;
  1616. }
  1617. initParameters.inputType = inputType;
  1618. if (inputType == sl.INPUT_TYPE.INPUT_TYPE_USB)
  1619. {
  1620. }
  1621. else if (inputType == sl.INPUT_TYPE.INPUT_TYPE_SVO)
  1622. {
  1623. initParameters.pathSVO = svoInputFileName;
  1624. initParameters.svoRealTimeMode = svoRealTimeMode;
  1625. }
  1626. else if (inputType == sl.INPUT_TYPE.INPUT_TYPE_STREAM)
  1627. {
  1628. initParameters.ipStream = streamInputIP;
  1629. initParameters.portStream = (ushort)streamInputPort;
  1630. }
  1631. versionZED = "[SDK]: " + sl.ZEDCamera.GetSDKVersion().ToString() + " [Plugin]: " + sl.ZEDCamera.PluginVersion.ToString();
  1632. //Behavior specific to AR pass-through mode.
  1633. if (isStereoRig)
  1634. {
  1635. //Creates a hidden camera rig that handles final output to the headset.
  1636. GameObject o = CreateZEDRigDisplayer();
  1637. if (!showarrig) o.hideFlags = HideFlags.HideInHierarchy;
  1638. o.transform.parent = transform;
  1639. initParameters.depthMinimumDistance = 0.1f; //Allow depth calculation to very close objects.
  1640. //For the Game/output window, mirror the headset view using a custom script that avoids stretching.
  1641. CreateMirror();
  1642. }
  1643. //Determine if we should enable the right depth measurement, which costs performance but is needed for pass-through AR.
  1644. switch (enableRightDepthMeasure)
  1645. {
  1646. case RightDepthEnabledMode.AUTO:
  1647. default:
  1648. if (isStereoRig) //If so, we've already determined we have both a left and right ZEDRenderingPlane, so skip the lookups.
  1649. {
  1650. initParameters.enableRightSideMeasure = true;
  1651. }
  1652. else
  1653. {
  1654. foreach (ZEDRenderingPlane renderplane in GetComponentsInChildren<ZEDRenderingPlane>())
  1655. {
  1656. //If we have any ZEDRenderingPlanes that are looking through the right side, enable the measurements.
  1657. if (renderplane.viewSide == ZEDRenderingPlane.ZED_CAMERA_SIDE.RIGHT ||
  1658. renderplane.viewSide == ZEDRenderingPlane.ZED_CAMERA_SIDE.RIGHT_FORCE)
  1659. {
  1660. initParameters.enableRightSideMeasure = true;
  1661. break;
  1662. }
  1663. }
  1664. }
  1665. break;
  1666. case RightDepthEnabledMode.OFF:
  1667. initParameters.enableRightSideMeasure = false;
  1668. break;
  1669. case RightDepthEnabledMode.ON:
  1670. initParameters.enableRightSideMeasure = true;
  1671. break;
  1672. }
  1673. //Starts a coroutine that initializes the ZED without freezing the game.
  1674. lastInitStatus = sl.ERROR_CODE.ERROR_CODE_LAST;
  1675. openingLaunched = false;
  1676. StartCoroutine(InitZED());
  1677. OnCamBrightnessChange += SetCameraBrightness; //Subscribe event for adjusting brightness setting.
  1678. OnMaxDepthChange += SetMaxDepthRange;
  1679. //Create Module Object
  1680. //Create the spatial mapping module object (even if not used necessarly)
  1681. spatialMapping = new ZEDSpatialMapping(transform, this);
  1682. }
  1683. void Start()
  1684. {
  1685. //adjust layers for multiple camera
  1686. //setLayersForMultiCamera ();
  1687. }
  1688. #region INITIALIZATION
  1689. //const int MAX_OPENING_TRIES = 10;
  1690. private uint numberTriesOpening = 0;/// Counter of tries to open the ZED
  1691. /// <summary>
  1692. /// ZED opening function. Should be called in the initialization thread (threadOpening).
  1693. /// </summary>
  1694. private void OpenZEDInBackground()
  1695. {
  1696. openingLaunched = true;
  1697. int timeout = 0;
  1698. do
  1699. {
  1700. initQuittingHandle.WaitOne(0); //Makes sure we haven't been turned off early, which only happens in Destroy() from OnApplicationQuit().
  1701. if (forceCloseInit) break;
  1702. lastInitStatus = zedCamera.Init(ref initParameters);
  1703. timeout++;
  1704. numberTriesOpening++;
  1705. } while (lastInitStatus != sl.ERROR_CODE.SUCCESS);
  1706. }
  1707. /// <summary>
  1708. /// Initialization coroutine.
  1709. /// </summary>
  1710. private System.Collections.IEnumerator InitZED()
  1711. {
  1712. zedReady = false;
  1713. if (!openingLaunched)
  1714. {
  1715. initQuittingHandle = new EventWaitHandle(true, EventResetMode.ManualReset);
  1716. threadOpening = new Thread(new ThreadStart(OpenZEDInBackground)); //Assign thread.
  1717. threadOpening.Start();
  1718. }
  1719. while (lastInitStatus != sl.ERROR_CODE.SUCCESS)
  1720. {
  1721. yield return new WaitForSeconds(0.3f);
  1722. }
  1723. //ZED has initialized successfully.
  1724. if (lastInitStatus == sl.ERROR_CODE.SUCCESS)
  1725. {
  1726. threadOpening.Join();
  1727. //Initialize the tracking thread, AR initial transforms and SVO read/write as needed.
  1728. ZEDReady();
  1729. //If using tracking, wait until the tracking thread has been initialized.
  1730. while (enableTracking && !isTrackingEnable)
  1731. {
  1732. yield return new WaitForSeconds(0.5f);
  1733. }
  1734. //Tells all the listeners that the ZED is ready! :)
  1735. if (OnZEDReady != null)
  1736. {
  1737. OnZEDReady();
  1738. }
  1739. //Make sure the screen is at 16:9 aspect ratio or close. Warn the user otherwise.
  1740. float ratio = (float)Screen.width / (float)Screen.height;
  1741. float target = 16.0f / 9.0f;
  1742. if (Mathf.Abs(ratio - target) > 0.01)
  1743. {
  1744. Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.SCREEN_RESOLUTION));
  1745. }
  1746. //get informations from camera (S/N, firmware, model...)
  1747. cameraModel = zedCamera.GetCameraModel().ToString();
  1748. cameraFirmware = zedCamera.GetCameraFirmwareVersion().ToString() + "-" + zedCamera.GetSensorsFirmwareVersion().ToString();
  1749. cameraSerialNumber = zedCamera.GetZEDSerialNumber().ToString();
  1750. if (inputType == sl.INPUT_TYPE.INPUT_TYPE_SVO)
  1751. {
  1752. numberFrameMax = zedCamera.GetSVONumberOfFrames();
  1753. }
  1754. // If streaming has been switched on before play
  1755. if (enableStreaming && !isStreamingEnable)
  1756. {
  1757. lock (zedCamera.grabLock)
  1758. {
  1759. sl.ERROR_CODE err = zedCamera.EnableStreaming(streamingCodec, (uint)bitrate, (ushort)streamingPort, gopSize, adaptativeBitrate, chunkSize, streamingTargetFramerate);
  1760. if (err == sl.ERROR_CODE.SUCCESS)
  1761. {
  1762. isStreamingEnable = true;
  1763. }
  1764. else
  1765. {
  1766. enableStreaming = false;
  1767. isStreamingEnable = false;
  1768. }
  1769. }
  1770. }
  1771. //If not already launched, launch the image grabbing thread.
  1772. if (!running)
  1773. {
  1774. running = true;
  1775. requestNewFrame = true;
  1776. threadGrab = new Thread(new ThreadStart(ThreadedZEDGrab));
  1777. threadGrab.Start();
  1778. }
  1779. zedReady = true;
  1780. isDisconnected = false; //In case we just regained connection.
  1781. setRenderingSettings(); //Find the ZEDRenderingPlanes in the rig and configure them.
  1782. AdjustZEDRigCameraPosition(); //If in AR mode, move cameras to proper offset relative to zedRigRoot.
  1783. }
  1784. }
  1785. /// <summary>
  1786. /// Adjust camera(s) relative to zedRigRoot transform, which is what is moved each frame. Called at start of tracking.
  1787. /// <para>In AR mode, offset is each camera's position relative to center of the user's head. Otherwise, cameras are just spaced
  1788. /// by the camera's baseline/IPD, or no offset is applied if there's just one camera. </para>
  1789. /// </summary>
  1790. void AdjustZEDRigCameraPosition()
  1791. {
  1792. //Vector3 rightCameraOffset = new Vector3(zedCamera.Baseline, 0.0f, 0.0f);
  1793. if (isStereoRig && hasXRDevice()) //Using AR pass-through mode.
  1794. {
  1795. //zedRigRoot transform (origin of the global camera) is placed on the HMD headset. Therefore, we move the
  1796. //camera in front of it by offsetHmdZEDPosition to compensate for the ZED's position on the headset.
  1797. //If values are wrong, tweak calibration file created in ZEDMixedRealityPlugin.
  1798. camLeftTransform.localPosition = arRig.HmdToZEDCalibration.translation;
  1799. camLeftTransform.localRotation = arRig.HmdToZEDCalibration.rotation;
  1800. if (camRightTransform) camRightTransform.localPosition = camLeftTransform.localPosition + new Vector3(zedCamera.Baseline, 0.0f, 0.0f); //Space the eyes apart.
  1801. if (camRightTransform) camRightTransform.localRotation = camLeftTransform.localRotation;
  1802. }
  1803. else if (camLeftTransform && camRightTransform) //Using stereo rig, but no VR headset.
  1804. {
  1805. //When no VR HMD is available, simply put the origin at the left camera.
  1806. camLeftTransform.localPosition = Vector3.zero;
  1807. camLeftTransform.localRotation = Quaternion.identity;
  1808. camRightTransform.localPosition = new Vector3(zedCamera.Baseline, 0.0f, 0.0f); //Space the eyes apart.
  1809. camRightTransform.localRotation = Quaternion.identity;
  1810. }
  1811. else //Using mono rig (ZED_Rig_Mono). No offset needed.
  1812. {
  1813. if (GetMainCameraTransform())
  1814. {
  1815. GetMainCameraTransform().localPosition = Vector3.zero;
  1816. GetMainCameraTransform().localRotation = Quaternion.identity;
  1817. }
  1818. }
  1819. }
  1820. /// <summary>
  1821. /// Find the ZEDRenderingPlane components in the ZED rig and set their rendering settings
  1822. /// (rendering path, shader values, etc.) for left and right cameras. Also activate/deactivate depth occlusions.
  1823. /// </summary>
  1824. void setRenderingSettings()
  1825. {
  1826. ZEDRenderingPlane leftRenderingPlane = null;
  1827. if (GetLeftCameraTransform() != null)
  1828. {
  1829. leftRenderingPlane = GetLeftCameraTransform().GetComponent<ZEDRenderingPlane>();
  1830. if (leftRenderingPlane)
  1831. {
  1832. leftRenderingPlane.SetPostProcess(postProcessing);
  1833. GetLeftCameraTransform().GetComponent<Camera>().renderingPath = RenderingPath.UsePlayerSettings;
  1834. SetCameraBrightness(m_cameraBrightness);
  1835. cameraLeft.cullingMask &= ~(1 << zedCamera.TagInvisibleToZED);
  1836. }
  1837. }
  1838. ZEDRenderingPlane rightRenderingPlane = null;
  1839. if (GetRightCameraTransform() != null)
  1840. {
  1841. rightRenderingPlane = GetRightCameraTransform().GetComponent<ZEDRenderingPlane>();
  1842. if (rightRenderingPlane)
  1843. {
  1844. rightRenderingPlane.SetPostProcess(postProcessing);
  1845. cameraRight.renderingPath = RenderingPath.UsePlayerSettings;
  1846. cameraRight.cullingMask &= ~(1 << zedCamera.TagInvisibleToZED);
  1847. }
  1848. }
  1849. SetCameraBrightness(m_cameraBrightness);
  1850. SetMaxDepthRange(m_maxDepthRange);
  1851. #if ZED_HDRP
  1852. SetSelfIllumination(selfIllumination);
  1853. SetBoolValueOnPlaneMaterials("_ApplyZEDNormals", applyZEDNormals);
  1854. #endif
  1855. Camera maincam = GetMainCamera();
  1856. if (maincam != null)
  1857. {
  1858. ZEDRenderingMode renderingPath = (ZEDRenderingMode)maincam.actualRenderingPath;
  1859. //Make sure we're in either forward or deferred rendering. Default to forward otherwise.
  1860. if (renderingPath != ZEDRenderingMode.FORWARD && renderingPath != ZEDRenderingMode.DEFERRED)
  1861. {
  1862. Debug.LogError("[ZED Plugin] Only Forward and Deferred Shading rendering path are supported");
  1863. if (cameraLeft) cameraLeft.renderingPath = RenderingPath.Forward;
  1864. if (cameraRight) cameraRight.renderingPath = RenderingPath.Forward;
  1865. }
  1866. //Set depth occlusion.
  1867. if (renderingPath == ZEDRenderingMode.FORWARD)
  1868. {
  1869. if (leftRenderingPlane)
  1870. leftRenderingPlane.ManageKeywordPipe(!depthOcclusion, "NO_DEPTH");
  1871. if (rightRenderingPlane)
  1872. rightRenderingPlane.ManageKeywordPipe(!depthOcclusion, "NO_DEPTH");
  1873. }
  1874. else if (renderingPath == ZEDRenderingMode.DEFERRED)
  1875. {
  1876. if (leftRenderingPlane)
  1877. leftRenderingPlane.ManageKeywordDeferredMat(!depthOcclusion, "NO_DEPTH");
  1878. if (rightRenderingPlane)
  1879. rightRenderingPlane.ManageKeywordDeferredMat(!depthOcclusion, "NO_DEPTH");
  1880. }
  1881. }
  1882. }
  1883. #endregion
  1884. #region IMAGE_ACQUIZ
  1885. /// <summary>
  1886. /// Continuously grabs images from the ZED. Runs on its own thread.
  1887. /// </summary>
  1888. private void ThreadedZEDGrab()
  1889. {
  1890. runtimeParameters = new sl.RuntimeParameters();
  1891. runtimeParameters.sensingMode = sensingMode;
  1892. runtimeParameters.enableDepth = true;
  1893. runtimeParameters.confidenceThreshold = confidenceThreshold;
  1894. runtimeParameters.textureConfidenceThreshold = textureConfidenceThreshold;
  1895. runtimeParameters.removeSaturatedAreas = true;
  1896. //Don't change this reference frame. If we need normals in the world frame, better to do the conversion ourselves.
  1897. runtimeParameters.measure3DReferenceFrame = sl.REFERENCE_FRAME.CAMERA;
  1898. while (running)
  1899. {
  1900. if (zedCamera == null)
  1901. return;
  1902. if (runtimeParameters.sensingMode != sensingMode) runtimeParameters.sensingMode = sensingMode;
  1903. AcquireImages();
  1904. }
  1905. }
  1906. /// <summary>
  1907. /// Grabs images from the ZED SDK and updates tracking, FPS and timestamp values.
  1908. /// Called from ThreadedZEDGrab() in a separate thread.
  1909. /// </summary>
  1910. private void AcquireImages()
  1911. {
  1912. if (requestNewFrame && zedReady)
  1913. {
  1914. if (inputType == sl.INPUT_TYPE.INPUT_TYPE_SVO)
  1915. {
  1916. //handle pause
  1917. if (NeedNewFrameGrab && pauseSVOReading)
  1918. {
  1919. ZEDGrabError = zedCamera.Grab(ref runtimeParameters);
  1920. NeedNewFrameGrab = false;
  1921. }
  1922. else if (!pauseSVOReading)
  1923. ZEDGrabError = zedCamera.Grab(ref runtimeParameters);
  1924. currentFrame = zedCamera.GetSVOPosition();
  1925. }
  1926. else if (!pauseLiveReading)
  1927. {
  1928. ZEDGrabError = zedCamera.Grab(ref runtimeParameters);
  1929. }
  1930. lock (zedCamera.grabLock)
  1931. {
  1932. if (ZEDGrabError == sl.ERROR_CODE.CAMERA_NOT_DETECTED)
  1933. {
  1934. Debug.Log("Camera not detected or disconnected.");
  1935. isDisconnected = true;
  1936. Thread.Sleep(10);
  1937. requestNewFrame = false;
  1938. }
  1939. else if (ZEDGrabError == sl.ERROR_CODE.SUCCESS)
  1940. {
  1941. #if UNITY_EDITOR
  1942. float camera_fps = zedCamera.GetCameraFPS();
  1943. cameraFPS = camera_fps.ToString() + " FPS";
  1944. #endif
  1945. //Update object detection here if using object sync.
  1946. if (objectDetectionRunning && objectDetectionImageSyncMode == true && requestobjectsframe)
  1947. {
  1948. RetrieveObjectDetectionFrame();
  1949. }
  1950. //Get position of camera
  1951. if (isTrackingEnable)
  1952. {
  1953. zedtrackingState = zedCamera.GetPosition(ref zedOrientation, ref zedPosition, sl.TRACKING_FRAME.LEFT_EYE);
  1954. //zedtrackingState = sl.TRACKING_STATE.TRACKING_OK;
  1955. if (inputType == sl.INPUT_TYPE.INPUT_TYPE_SVO && svoLoopBack == true && initialPoseCached == false)
  1956. {
  1957. initialPosition = zedPosition;
  1958. initialRotation = zedOrientation;
  1959. initialPoseCached = true;
  1960. }
  1961. }
  1962. else
  1963. {
  1964. zedtrackingState = sl.TRACKING_STATE.TRACKING_OFF;
  1965. }
  1966. // Indicate that a new frame is available and pause the thread until a new request is called
  1967. newFrameAvailable = true;
  1968. requestNewFrame = false;
  1969. }
  1970. else
  1971. Thread.Sleep(1);
  1972. }
  1973. }
  1974. else
  1975. {
  1976. //To avoid "overheating."
  1977. Thread.Sleep(1);
  1978. }
  1979. }
  1980. #endregion
  1981. /// <summary>
  1982. /// Initialize the SVO, and launch the thread to initialize tracking. Called once the ZED
  1983. /// is initialized successfully.
  1984. /// </summary>
  1985. private void ZEDReady()
  1986. {
  1987. //Apply camera settings based on user preference.
  1988. InitVideoSettings(videoSettingsInitMode);
  1989. FPS = (int)zedCamera.GetRequestedCameraFPS();
  1990. if (enableTracking)
  1991. {
  1992. trackerThread = new Thread(EnableTrackingThreaded);
  1993. trackerThread.Start();
  1994. }
  1995. else if (estimateInitialPosition)
  1996. {
  1997. sl.ERROR_CODE err = zedCamera.EstimateInitialPosition(ref initialRotation, ref initialPosition);
  1998. if (zedCamera.GetCameraModel() != sl.MODEL.ZED)
  1999. zedCamera.GetInternalIMUOrientation(ref initialRotation, sl.TIME_REFERENCE.IMAGE);
  2000. if (err != sl.ERROR_CODE.SUCCESS)
  2001. Debug.LogWarning("Failed to estimate initial camera position");
  2002. }
  2003. if (enableTracking)
  2004. trackerThread.Join();
  2005. if (isStereoRig && hasXRDevice())
  2006. {
  2007. ZEDMixedRealityPlugin.Pose pose = arRig.InitTrackingAR();
  2008. OriginPosition = pose.translation;
  2009. OriginRotation = pose.rotation;
  2010. if (!zedCamera.IsHmdCompatible && zedCamera.IsCameraReady)
  2011. Debug.LogWarning("WARNING: AR Passtrough with a ZED is not recommended. Consider using ZED Mini, designed for this purpose.");
  2012. }
  2013. else
  2014. {
  2015. OriginPosition = initialPosition;
  2016. OriginRotation = initialRotation;
  2017. }
  2018. //Set the original transform for the Rig
  2019. zedRigRoot.localPosition = OriginPosition;
  2020. zedRigRoot.localRotation = OriginRotation;
  2021. }
  2022. /// <summary>
  2023. /// Initializes the ZED's inside-out tracking. Started as a separate thread in OnZEDReady.
  2024. /// </summary>
  2025. void EnableTrackingThreaded()
  2026. {
  2027. lock (zedCamera.grabLock)
  2028. {
  2029. //If using spatial memory and given a path to a .area file, make sure that path is valid.
  2030. if (enableSpatialMemory && pathSpatialMemory != "" && !System.IO.File.Exists(pathSpatialMemory))
  2031. {
  2032. Debug.Log("Specified path to .area file '" + pathSpatialMemory + "' does not exist. Ignoring.");
  2033. pathSpatialMemory = "";
  2034. }
  2035. sl.ERROR_CODE err = (zedCamera.EnableTracking(ref zedOrientation, ref zedPosition, enableSpatialMemory,
  2036. enablePoseSmoothing, estimateInitialPosition, trackingIsStatic, enableIMUFusion, pathSpatialMemory));
  2037. //Now enable the tracking with the proper parameters.
  2038. if (!(enableTracking = (err == sl.ERROR_CODE.SUCCESS)))
  2039. {
  2040. throw new Exception(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.TRACKING_NOT_INITIALIZED));
  2041. }
  2042. else
  2043. {
  2044. isTrackingEnable = true;
  2045. }
  2046. }
  2047. }
  2048. #if ZED_HDRP
  2049. public bool GetChosenSRPMaterial(out Material srpMat)
  2050. {
  2051. switch(srpShaderType)
  2052. {
  2053. case shaderType.Lit:
  2054. srpMat = Resources.Load<Material>("Materials/Lighting/Mat_ZED_HDRP_Lit");
  2055. if (srpMat == null)
  2056. {
  2057. Debug.LogError("Couldn't find material in Resources. Path: " + "Materials/Lighting/Mat_ZED_HDRP_Lit");
  2058. return false;
  2059. }
  2060. else return true;
  2061. case shaderType.Unlit:
  2062. srpMat = Resources.Load<Material>("Materials/Unlit/Mat_ZED_Unlit_RawInput");
  2063. if (srpMat == null)
  2064. {
  2065. Debug.LogError("Couldn't find material in Resources. Path: " + "Materials/Unlit/Mat_ZED_Unlit_RawInput");
  2066. return false;
  2067. }
  2068. else return true;
  2069. case shaderType.Greenscreen_Lit:
  2070. srpMat = Resources.Load<Material>("Materials/Lighting/Mat_ZED_Greenscreen_HDRP_Lit");
  2071. if (srpMat == null)
  2072. {
  2073. Debug.LogError("Couldn't find material in Resources. Path: " + "Materials/Lighting/Mat_ZED_Greenscreen_HDRP_Lit");
  2074. return false;
  2075. }
  2076. else return true;
  2077. case shaderType.Greenscreen_Unlit:
  2078. srpMat = Resources.Load<Material>("Materials/Unlit/Mat_ZED_Greenscreen_Unlit");
  2079. if (srpMat == null)
  2080. {
  2081. Debug.LogError("Couldn't find material in Resources. Path: " + "Materials/Unlit/Mat_ZED_Greenscreen_Unlit");
  2082. return false;
  2083. }
  2084. else return true;
  2085. case shaderType.DontChange:
  2086. default:
  2087. srpMat = null;
  2088. return false;
  2089. }
  2090. }
  2091. #endif
  2092. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2093. ////////////////////////////////////////////////////////// ENGINE UPDATE REGION /////////////////////////////////////////////////////////////////////////////
  2094. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2095. #region ENGINE_UPDATE
  2096. /// <summary>
  2097. /// If a new frame is available, this function retrieves the images and updates the Unity textures. Called in Update().
  2098. /// </summary>
  2099. public void UpdateImages()
  2100. {
  2101. if (zedCamera == null)
  2102. return;
  2103. if (newFrameAvailable) //ThreadedZEDGrab()/AcquireImages() grabbed images we haven't updated yet.
  2104. {
  2105. lock (zedCamera.grabLock)
  2106. {
  2107. zedCamera.RetrieveTextures(); //Tell the wrapper to compute the textures.
  2108. zedCamera.UpdateTextures(); //Tell the wrapper to update the textures.
  2109. imageTimeStamp = zedCamera.GetImagesTimeStamp();
  2110. }
  2111. //For external module ... Trigger the capture done event.
  2112. if (OnGrab != null)
  2113. OnGrab();
  2114. //SVO and loop back ? --> reset position if needed
  2115. if (zedCamera.GetInputType() == sl.INPUT_TYPE.INPUT_TYPE_SVO && svoLoopBack)
  2116. {
  2117. int maxSVOFrame = zedCamera.GetSVONumberOfFrames();
  2118. if (zedCamera.GetSVOPosition() >= maxSVOFrame - (svoRealTimeMode ? 2 : 1))
  2119. {
  2120. zedCamera.SetSVOPosition(0);
  2121. if (enableTracking)
  2122. {
  2123. if (!(enableTracking = (zedCamera.ResetTracking(initialRotation, initialPosition) == sl.ERROR_CODE.SUCCESS)))
  2124. {
  2125. Debug.LogError("ZED Tracking disabled: Not available during SVO playback when Loop is enabled.");
  2126. }
  2127. }
  2128. zedRigRoot.localPosition = initialPosition;
  2129. zedRigRoot.localRotation = initialRotation;
  2130. }
  2131. }
  2132. requestNewFrame = true; //Lets ThreadedZEDGrab/AcquireImages() start grabbing again.
  2133. newFrameAvailable = false;
  2134. }
  2135. }
  2136. /// <summary>
  2137. /// Gets the tracking position from the ZED and updates zedRigRoot's position. Also updates the AR tracking if enabled.
  2138. /// Only called in Live (not SVO playback) mode. Called in Update().
  2139. /// </summary>
  2140. private void UpdateTracking()
  2141. {
  2142. if (!zedReady)
  2143. return;
  2144. if (isZEDTracked) //ZED inside-out tracking is enabled and initialized.
  2145. {
  2146. Quaternion r;
  2147. Vector3 v;
  2148. isCameraTracked = true;
  2149. if (hasXRDevice() && isStereoRig) //AR pass-through mode.
  2150. {
  2151. if (calibrationHasChanged) //If the HMD offset calibration file changed during runtime.
  2152. {
  2153. AdjustZEDRigCameraPosition(); //Re-apply the ZED's offset from the VR headset.
  2154. calibrationHasChanged = false;
  2155. }
  2156. arRig.ExtractLatencyPose(imageTimeStamp); //Find what HMD's pose was at ZED image's timestamp for latency compensation.
  2157. arRig.AdjustTrackingAR(zedPosition, zedOrientation, out r, out v, setIMUPriorInAR);
  2158. zedRigRoot.localRotation = r;
  2159. zedRigRoot.localPosition = v;
  2160. //Debug.DrawLine(new Vector3(0, 0.05f, 0), (r * Vector3.one * 5) + new Vector3(0, 0.05f, 0), Color.red);
  2161. //Debug.DrawLine(Vector3.zero, zedOrientation * Vector3.one * 5, Color.green);
  2162. ZEDSyncPosition = v;
  2163. ZEDSyncRotation = r;
  2164. HMDSyncPosition = arRig.LatencyPose().translation;
  2165. HMDSyncRotation = arRig.LatencyPose().rotation;
  2166. }
  2167. else //Not AR pass-through mode.
  2168. {
  2169. zedRigRoot.localRotation = zedOrientation;
  2170. if (!ZEDSupportFunctions.IsVector3NaN(zedPosition))
  2171. zedRigRoot.localPosition = zedPosition;
  2172. }
  2173. }
  2174. else if (hasXRDevice() && isStereoRig) //ZED tracking is off but HMD tracking is on. Fall back to that.
  2175. {
  2176. isCameraTracked = true;
  2177. arRig.ExtractLatencyPose(imageTimeStamp); //Find what HMD's pose was at ZED image's timestamp for latency compensation.
  2178. zedRigRoot.localRotation = arRig.LatencyPose().rotation;
  2179. zedRigRoot.localPosition = arRig.LatencyPose().translation;
  2180. }
  2181. else //The ZED is not tracked by itself or an HMD.
  2182. isCameraTracked = false;
  2183. }
  2184. /// <summary>
  2185. /// Stores the HMD's current pose. Used in AR mode for latency compensation.
  2186. /// Pose will be applied to final canvases when a new image's timestamp matches
  2187. /// the time when this is called.
  2188. /// </summary>
  2189. void UpdateHmdPose()
  2190. {
  2191. if (IsStereoRig && hasXRDevice())
  2192. arRig.CollectPose(); //Save headset pose with current timestamp.
  2193. }
  2194. /// <summary>
  2195. /// Updates images, collects HMD poses for latency correction, and applies tracking.
  2196. /// Called by Unity each frame.
  2197. /// </summary>
  2198. void Update()
  2199. {
  2200. //Check if ZED is disconnected; invoke event and call function if so.
  2201. if (isDisconnected)
  2202. {
  2203. if (OnZEDDisconnected != null)
  2204. OnZEDDisconnected(); //Invoke event. Used for GUI message and pausing ZEDRenderingPlanes.
  2205. ZEDDisconnected(); //Tries to reset the camera.
  2206. return;
  2207. }
  2208. // Then update all modules
  2209. UpdateImages(); //Image is updated first so we have its timestamp for latency compensation.
  2210. UpdateHmdPose(); //Store the HMD's pose at the current timestamp.
  2211. UpdateTracking(); //Apply position/rotation changes to zedRigRoot.
  2212. UpdateObjectsDetection(); //Update od if activated
  2213. UpdateMapping(); //Update mapping if activated
  2214. /// If in Unity Editor, update the ZEDManager status list
  2215. #if UNITY_EDITOR
  2216. //Update strings used for di splaying stats in the Inspector.
  2217. if (zedCamera != null)
  2218. {
  2219. float frame_drop_count = zedCamera.GetFrameDroppedPercent();
  2220. float CurrentTickFPS = 1.0f / Time.deltaTime;
  2221. fps_engine = (fps_engine + CurrentTickFPS) / 2.0f;
  2222. engineFPS = fps_engine.ToString("F0") + " FPS";
  2223. if (frame_drop_count > 30 && fps_engine < 45)
  2224. engineFPS += "WARNING: Low engine framerate detected";
  2225. if (isZEDTracked)
  2226. trackingState = ZEDTrackingState.ToString();
  2227. else if (hasXRDevice() && isStereoRig)
  2228. trackingState = "HMD Tracking";
  2229. else
  2230. trackingState = "Camera Not Tracked";
  2231. }
  2232. #endif
  2233. }
  2234. public void LateUpdate()
  2235. {
  2236. if (IsStereoRig)
  2237. {
  2238. arRig.LateUpdateHmdRendering(); //Update textures on final AR rig for output to the headset.
  2239. }
  2240. }
  2241. #endregion
  2242. /// <summary>
  2243. /// Event called when camera is disconnected
  2244. /// </summary>
  2245. void ZEDDisconnected()
  2246. {
  2247. cameraFPS = "Disconnected";
  2248. isDisconnected = true;
  2249. if (zedReady)
  2250. {
  2251. Reset(); //Cache tracking, turn it off and turn it back on again.
  2252. }
  2253. }
  2254. private void OnDestroy()
  2255. {
  2256. //OnApplicationQuit();
  2257. CloseManager();
  2258. }
  2259. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2260. //////////////////////////////////////////////////////// SPATIAL MAPPING REGION /////////////////////////////////////////////////////////////////////////////
  2261. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2262. #region MAPPING_MODULE
  2263. /// <summary>
  2264. /// Tells ZEDSpatialMapping to begin a new scan. This clears the previous scan from the scene if there is one.
  2265. /// </summary>
  2266. public void StartSpatialMapping()
  2267. {
  2268. transform.position = Vector3.zero;
  2269. transform.rotation = Quaternion.identity;
  2270. spatialMapping.StartStatialMapping(sl.SPATIAL_MAP_TYPE.MESH, mappingResolutionPreset, mappingRangePreset, isMappingTextured);
  2271. }
  2272. /// <summary>
  2273. /// Ends the current spatial mapping. Once called, the current mesh will be filtered, textured (if enabled) and saved (if enabled),
  2274. /// and a mesh collider will be added.
  2275. /// </summary>
  2276. public void StopSpatialMapping()
  2277. {
  2278. if (spatialMapping != null)
  2279. {
  2280. if (saveMeshWhenOver)
  2281. SaveMesh(meshPath);
  2282. spatialMapping.StopStatialMapping();
  2283. }
  2284. }
  2285. /// <summary>
  2286. /// Updates the filtering parameters and call the ZEDSpatialMapping instance's Update() function.
  2287. /// </summary>
  2288. private void UpdateMapping()
  2289. {
  2290. if (spatialMapping != null)
  2291. {
  2292. //if (IsMappingUpdateThreadRunning)
  2293. if (spatialMapping.IsRunning())
  2294. {
  2295. spatialMapping.filterParameters = meshFilterParameters;
  2296. spatialMapping.Update();
  2297. }
  2298. }
  2299. }
  2300. /// <summary>
  2301. /// Toggles whether to display the mesh or not.
  2302. /// </summary>
  2303. /// <param name="state"><c>True</c> to make the mesh visible, <c>false</c> to make it invisible. </param>
  2304. public void SwitchDisplayMeshState(bool state)
  2305. {
  2306. if (spatialMapping != null)
  2307. spatialMapping.SwitchDisplayMeshState(state);
  2308. }
  2309. public void ClearAllMeshes()
  2310. {
  2311. if (spatialMapping != null)
  2312. spatialMapping.ClearAllMeshes();
  2313. }
  2314. /// <summary>
  2315. /// Pauses the current scan.
  2316. /// </summary>
  2317. /// <param name="state"><c>True</c> to pause the scanning, <c>false</c> to unpause it.</param>
  2318. public void SwitchPauseState(bool state)
  2319. {
  2320. if (spatialMapping != null)
  2321. spatialMapping.SwitchPauseState(state);
  2322. }
  2323. /// <summary>
  2324. /// Saves the mesh into a 3D model (.obj, .ply or .bin) file. Also saves an .area file for spatial memory for better tracking.
  2325. /// Calling this will end the spatial mapping if it's running. Note it can take a significant amount of time to finish.
  2326. /// </summary>
  2327. /// <param name="meshPath">Path where the mesh and .area files will be saved.</param>
  2328. public void SaveMesh(string meshPath = "ZEDMeshObj.obj")
  2329. {
  2330. spatialMapping.RequestSaveMesh(meshPath);
  2331. }
  2332. /// <summary>
  2333. /// Loads a mesh and spatial memory data from a file.
  2334. /// If scanning is running, it will be stopped. Existing scans in the scene will be cleared.
  2335. /// </summary>
  2336. /// <param name="meshPath">Path to the 3D mesh file (.obj, .ply or .bin) to load.</param>
  2337. /// <returns><c>True</c> if successfully loaded, <c>false</c> otherwise.</returns>
  2338. public bool LoadMesh(string meshPath = "ZEDMeshObj.obj")
  2339. {
  2340. //Cache the save setting and set to false, to avoid overwriting the mesh file during the load.
  2341. bool oldSaveWhenOver = saveMeshWhenOver;
  2342. saveMeshWhenOver = false;
  2343. gravityRotation = Quaternion.identity;
  2344. spatialMapping.SetMeshRenderer();
  2345. bool loadresult = spatialMapping.LoadMesh(meshPath);
  2346. saveMeshWhenOver = oldSaveWhenOver; //Restoring old setting.
  2347. return loadresult;
  2348. }
  2349. #endregion
  2350. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2351. //////////////////////////////////////////////////////// OBJECT DETECTION REGION //////////////////////////////////////////////////////////////////////////////
  2352. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2353. #region OBJECT_DETECTION
  2354. /// <summary>
  2355. /// True when the object detection coroutine is in the process of starting.
  2356. /// Used to prevent object detection from being launched multiple times at once, which causes instability.
  2357. /// </summary>
  2358. private bool odIsStarting = false;
  2359. /// <summary>
  2360. /// Starts the ZED object detection.
  2361. /// <para>Note: This will lock the main thread for a moment, which may appear to be a freeze.</para>
  2362. /// </summary>
  2363. public void StartObjectDetection()
  2364. {
  2365. sl.AI_Model_status AiModelStatus = sl.ZEDCamera.CheckAIModelStatus(sl.ZEDCamera.cvtDetection(objectDetectionModel));
  2366. if (!AiModelStatus.optimized)
  2367. {
  2368. Debug.LogError("The Model * " + objectDetectionModel.ToString() + " * has not been downloaded/optimized. Use the ZED Diagnostic tool to download/optimze all the AI model you plan to use.");
  2369. // return;
  2370. }
  2371. //We start a coroutine so we can delay actually starting the detection.
  2372. //This is because the main thread is locked for awhile when you call this, appearing like a freeze.
  2373. //This time lets us deliver a log message to the user indicating that this is expected.
  2374. StartCoroutine(startObjectDetection());
  2375. }
  2376. /// <summary>
  2377. /// <summary>
  2378. /// Starts the object detection module after a two-frame delay, allowing us to deliver a log message
  2379. /// to the user indicating that what appears to be a freeze is actually expected and will pass.
  2380. /// </summary>
  2381. /// <returns></returns>
  2382. private IEnumerator startObjectDetection()
  2383. {
  2384. if (odIsStarting == true)
  2385. {
  2386. Debug.LogError("Tried to start Object Detection while it was already starting. Do you have two scripts trying to start it?");
  2387. yield break;
  2388. }
  2389. if (objectDetectionRunning)
  2390. {
  2391. Debug.LogWarning("Tried to start Object Detection while it was already running.");
  2392. }
  2393. if (zedCamera != null)
  2394. {
  2395. odIsStarting = true;
  2396. Debug.LogWarning("Starting Object Detection. This may take a moment.");
  2397. bool oldpausestate = pauseSVOReading; //The two frame delay will cause you to miss some SVO frames if playing back from an SVO, unless we pause.
  2398. pauseSVOReading = true;
  2399. yield return null;
  2400. pauseSVOReading = oldpausestate;
  2401. sl.dll_ObjectDetectionParameters od_param = new sl.dll_ObjectDetectionParameters();
  2402. od_param.imageSync = objectDetectionImageSyncMode;
  2403. od_param.enableObjectTracking = objectDetectionTracking;
  2404. od_param.enable2DMask = objectDetection2DMask;
  2405. od_param.detectionModel = objectDetectionModel;
  2406. od_param.maxRange = objectDetectionMaxRange;
  2407. od_param.filteringMode = objectDetectionFilteringMode;
  2408. if (objectDetectionBodyFormat == sl.BODY_FORMAT.POSE_34 && objectDetectionBodyFitting == false && (objectDetectionModel == sl.DETECTION_MODEL.HUMAN_BODY_ACCURATE || objectDetectionModel == sl.DETECTION_MODEL.HUMAN_BODY_MEDIUM
  2409. || objectDetectionModel == sl.DETECTION_MODEL.HUMAN_BODY_FAST))
  2410. {
  2411. Debug.LogWarning("sl.BODY_FORMAT.POSE_34 is chosen, Skeleton Tracking will automatically enable body fitting");
  2412. objectDetectionBodyFitting = true;
  2413. }
  2414. od_param.bodyFormat = objectDetectionBodyFormat;
  2415. od_param.enableBodyFitting = objectDetectionBodyFitting;
  2416. od_runtime_params.object_confidence_threshold = new int[(int)sl.OBJECT_CLASS.LAST];
  2417. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.PERSON] = (objectDetectionModel == sl.DETECTION_MODEL.HUMAN_BODY_ACCURATE || objectDetectionModel == sl.DETECTION_MODEL.HUMAN_BODY_FAST || objectDetectionModel == sl.DETECTION_MODEL.HUMAN_BODY_MEDIUM) ? SK_personDetectionConfidenceThreshold : OD_personDetectionConfidenceThreshold;
  2418. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.VEHICLE] = vehicleDetectionConfidenceThreshold;
  2419. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.BAG] = bagDetectionConfidenceThreshold;
  2420. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.ANIMAL] = animalDetectionConfidenceThreshold;
  2421. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.ELECTRONICS] = electronicsDetectionConfidenceThreshold;
  2422. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.FRUIT_VEGETABLE] = fruitVegetableDetectionConfidenceThreshold;
  2423. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.SPORT] = sportDetectionConfidenceThreshold;
  2424. od_runtime_params.objectClassFilter = new int[(int)sl.OBJECT_CLASS.LAST];
  2425. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.PERSON] = Convert.ToInt32(objectClassPersonFilter);
  2426. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.VEHICLE] = Convert.ToInt32(objectClassVehicleFilter);
  2427. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.BAG] = Convert.ToInt32(objectClassBagFilter);
  2428. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.ANIMAL] = Convert.ToInt32(objectClassAnimalFilter);
  2429. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.ELECTRONICS] = Convert.ToInt32(objectClassElectronicsFilter);
  2430. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.FRUIT_VEGETABLE] = Convert.ToInt32(objectClassFruitVegetableFilter);
  2431. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.SPORT] = Convert.ToInt32(objectClassSportFilter);
  2432. System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); //Time how long the loading takes so we can tell the user.
  2433. watch.Start();
  2434. sl.ERROR_CODE err = zedCamera.EnableObjectsDetection(ref od_param);
  2435. if (err == sl.ERROR_CODE.SUCCESS)
  2436. {
  2437. Debug.Log("Object Detection module started in " + watch.Elapsed.Seconds + " seconds.");
  2438. objectDetectionRunning = true;
  2439. }
  2440. else
  2441. {
  2442. Debug.Log("Object Detection failed to start. (Error: " + err + " )");
  2443. objectDetectionRunning = false;
  2444. }
  2445. watch.Stop();
  2446. odIsStarting = false;
  2447. }
  2448. }
  2449. /// <summary>
  2450. /// Stops the object detection.
  2451. /// </summary>
  2452. public void StopObjectDetection()
  2453. {
  2454. if (zedCamera != null && running)
  2455. {
  2456. zedCamera.DisableObjectsDetection();
  2457. objectDetectionRunning = false;
  2458. }
  2459. }
  2460. /// <summary>
  2461. /// Updates the objects detection by triggering the detection event
  2462. /// </summary>
  2463. public void UpdateObjectsDetection()
  2464. {
  2465. if (!objectDetectionRunning) return;
  2466. //Update the runtime parameters in case the user made changes.
  2467. od_runtime_params.object_confidence_threshold = new int[(int)sl.OBJECT_CLASS.LAST];
  2468. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.PERSON] = (objectDetectionModel == sl.DETECTION_MODEL.HUMAN_BODY_ACCURATE || objectDetectionModel == sl.DETECTION_MODEL.HUMAN_BODY_FAST) ? SK_personDetectionConfidenceThreshold : OD_personDetectionConfidenceThreshold;
  2469. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.VEHICLE] = vehicleDetectionConfidenceThreshold;
  2470. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.BAG] = bagDetectionConfidenceThreshold;
  2471. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.ANIMAL] = animalDetectionConfidenceThreshold;
  2472. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.ELECTRONICS] = electronicsDetectionConfidenceThreshold;
  2473. od_runtime_params.object_confidence_threshold[(int)sl.OBJECT_CLASS.FRUIT_VEGETABLE] = fruitVegetableDetectionConfidenceThreshold;
  2474. od_runtime_params.objectClassFilter = new int[(int)sl.OBJECT_CLASS.LAST];
  2475. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.PERSON] = Convert.ToInt32(objectClassPersonFilter);
  2476. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.VEHICLE] = Convert.ToInt32(objectClassVehicleFilter);
  2477. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.BAG] = Convert.ToInt32(objectClassBagFilter);
  2478. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.ANIMAL] = Convert.ToInt32(objectClassAnimalFilter);
  2479. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.ELECTRONICS] = Convert.ToInt32(objectClassElectronicsFilter);
  2480. od_runtime_params.objectClassFilter[(int)sl.OBJECT_CLASS.FRUIT_VEGETABLE] = Convert.ToInt32(objectClassFruitVegetableFilter);
  2481. if (objectDetectionImageSyncMode == false) RetrieveObjectDetectionFrame(); //If true, this is called in the AcquireImages function in the image acquisition thread.
  2482. if (newobjectsframeready)
  2483. {
  2484. lock (zedCamera.grabLock)
  2485. {
  2486. float objdetect_fps = 1000000000.0f / (objectsFrameSDK.timestamp - lastObjectFrameTimeStamp);
  2487. objDetectionModuleFPS = (objDetectionModuleFPS + objdetect_fps) / 2.0f;
  2488. objectDetectionFPS = objDetectionModuleFPS.ToString("F1") + " FPS";
  2489. lastObjectFrameTimeStamp = objectsFrameSDK.timestamp;
  2490. ///Trigger the event that holds the raw data, and pass the whole objects frame.
  2491. if (OnObjectDetection_SDKData != null)
  2492. {
  2493. OnObjectDetection_SDKData(objectsFrameSDK);
  2494. }
  2495. //If there are any subscribers to the non-raw data, create that data and publish the event.
  2496. if (OnObjectDetection != null)
  2497. {
  2498. DetectionFrame oldoframe = detectionFrame; //Cache so we can clean it up once we're done setting up the new one.
  2499. //DetectionFrame oframe = new DetectionFrame(objectsFrame, this);
  2500. detectionFrame = new DetectionFrame(objectsFrameSDK, this);
  2501. OnObjectDetection(detectionFrame);
  2502. if (oldoframe != null) oldoframe.CleanUpAllObjects();
  2503. }
  2504. //Now that all events have been sent out, it's safe to let the image acquisition thread detect more objects.
  2505. requestobjectsframe = true;
  2506. newobjectsframeready = false;
  2507. }
  2508. }
  2509. }
  2510. /// <summary>
  2511. /// Requests the latest object detection frame information. If it's new, it'll fill the objectsFrame object
  2512. /// with the new frame info, set requestobjectsframe to false, and set newobjectsframeready to true.
  2513. /// </summary>
  2514. private void RetrieveObjectDetectionFrame()
  2515. {
  2516. sl.ObjectsFrameSDK oframebuffer = new sl.ObjectsFrameSDK();
  2517. sl.ERROR_CODE res = zedCamera.RetrieveObjectsDetectionData(ref od_runtime_params, ref oframebuffer);
  2518. if (res == sl.ERROR_CODE.SUCCESS && oframebuffer.isNew != 0)
  2519. {
  2520. if (objectDetection2DMask)
  2521. {
  2522. //Release memory from masks.
  2523. for (int i = 0; i < objectsFrameSDK.numObject; i++)
  2524. {
  2525. sl.ZEDMat oldmat = new sl.ZEDMat(objectsFrameSDK.objectData[i].mask);
  2526. oldmat.Free();
  2527. }
  2528. }
  2529. objectsFrameSDK = oframebuffer;
  2530. requestobjectsframe = false;
  2531. newobjectsframeready = true;
  2532. }
  2533. }
  2534. /// <summary>
  2535. /// Switchs the state of the object detection pause.
  2536. /// </summary>
  2537. /// <param name="state">If set to <c>true</c> state, the object detection will pause. It will resume otherwise</param>
  2538. public void SwitchObjectDetectionPauseState(bool state)
  2539. {
  2540. if (zedCamera != null)
  2541. {
  2542. if (objectDetectionRunning)
  2543. zedCamera.PauseObjectsDetection(state);
  2544. }
  2545. }
  2546. #endregion
  2547. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2548. ////////////////////////////////////////////////////////////////////// AR REGION //////////////////////////////////////////////////////////////////////////////
  2549. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2550. #region AR_CAMERAS
  2551. /// <summary>
  2552. /// Stereo rig that adjusts images from ZED_Rig_Stereo to look correct in the HMD.
  2553. /// <para>Hidden by default as it rarely needs to be changed.</para>
  2554. /// </summary>
  2555. [HideInInspector]
  2556. public GameObject zedRigDisplayer;
  2557. private ZEDMixedRealityPlugin arRig;
  2558. /// <summary>
  2559. /// Create a GameObject to display the ZED in an headset (ZED-M Only).
  2560. /// </summary>
  2561. /// <returns></returns>
  2562. private GameObject CreateZEDRigDisplayer()
  2563. {
  2564. //Make sure we don't already have one, such as if the camera disconnected and reconnected.
  2565. if (zedRigDisplayer != null) Destroy(zedRigDisplayer);
  2566. zedRigDisplayer = new GameObject("ZEDRigDisplayer");
  2567. arRig = zedRigDisplayer.AddComponent<ZEDMixedRealityPlugin>();
  2568. /*Screens left and right */
  2569. GameObject centerScreen = GameObject.CreatePrimitive(PrimitiveType.Quad);
  2570. centerScreen.name = "Quad";
  2571. MeshRenderer meshCenterScreen = centerScreen.GetComponent<MeshRenderer>();
  2572. meshCenterScreen.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
  2573. meshCenterScreen.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
  2574. meshCenterScreen.receiveShadows = false;
  2575. meshCenterScreen.motionVectorGenerationMode = MotionVectorGenerationMode.ForceNoMotion;
  2576. meshCenterScreen.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
  2577. meshCenterScreen.sharedMaterial = Resources.Load("Materials/Unlit/Mat_ZED_Unlit") as Material;
  2578. centerScreen.layer = arLayer;
  2579. GameObject.Destroy(centerScreen.GetComponent<MeshCollider>());
  2580. /*Camera left and right*/
  2581. GameObject camCenter = new GameObject("camera");
  2582. camCenter.transform.SetParent(zedRigDisplayer.transform);
  2583. Camera cam = camCenter.AddComponent<Camera>();
  2584. cam.renderingPath = RenderingPath.Forward;//Minimal overhead
  2585. cam.clearFlags = CameraClearFlags.Color;
  2586. cam.backgroundColor = Color.black;
  2587. cam.stereoTargetEye = StereoTargetEyeMask.Both; //Temporary setting to fix loading screen issue.
  2588. cam.cullingMask = 1 << arLayer;
  2589. cam.allowHDR = false;
  2590. cam.allowMSAA = false;
  2591. cam.depth = camRightTransform.GetComponent<Camera>().depth;
  2592. HideFromWrongCameras.RegisterZEDCam(cam);
  2593. HideFromWrongCameras hider = centerScreen.AddComponent<HideFromWrongCameras>();
  2594. hider.SetRenderCamera(cam);
  2595. hider.showInNonZEDCameras = false;
  2596. SetLayerRecursively(camCenter, arLayer);
  2597. //Hide camera in editor.
  2598. #if UNITY_EDITOR
  2599. if (!showarrig)
  2600. {
  2601. LayerMask layerNumberBinary = (1 << arLayer); //Convert layer index into binary number.
  2602. LayerMask flippedVisibleLayers = ~UnityEditor.Tools.visibleLayers;
  2603. UnityEditor.Tools.visibleLayers = ~(flippedVisibleLayers | layerNumberBinary);
  2604. }
  2605. #endif
  2606. centerScreen.transform.SetParent(zedRigDisplayer.transform);
  2607. arRig.finalCameraCenter = camCenter;
  2608. arRig.ZEDEyeLeft = camLeftTransform.gameObject;
  2609. arRig.ZEDEyeRight = camRightTransform.gameObject;
  2610. arRig.quadCenter = centerScreen.transform;
  2611. ZEDMixedRealityPlugin.OnHmdCalibChanged += CalibrationHasChanged;
  2612. if (hasXRDevice())
  2613. {
  2614. #if UNITY_2019_1_OR_NEWER
  2615. HMDDevice = XRSettings.loadedDeviceName;
  2616. #else
  2617. HMDDevice = XRDevice.model;
  2618. #endif
  2619. }
  2620. return zedRigDisplayer;
  2621. }
  2622. #endregion
  2623. #region MIRROR
  2624. private ZEDMirror mirror = null;
  2625. private GameObject mirrorContainer = null;
  2626. void CreateMirror()
  2627. {
  2628. GameObject camLeft;
  2629. Camera camL;
  2630. if (mirrorContainer == null)
  2631. {
  2632. mirrorContainer = new GameObject("Mirror");
  2633. mirrorContainer.hideFlags = HideFlags.HideInHierarchy;
  2634. camLeft = new GameObject("MirrorCamera");
  2635. camLeft.hideFlags = HideFlags.HideInHierarchy;
  2636. mirror = camLeft.AddComponent<ZEDMirror>();
  2637. mirror.manager = this;
  2638. camL = camLeft.AddComponent<Camera>();
  2639. }
  2640. else
  2641. {
  2642. camLeft = mirror.gameObject;
  2643. camL = camLeft.GetComponent<Camera>();
  2644. }
  2645. camLeft.transform.parent = mirrorContainer.transform;
  2646. camL.stereoTargetEye = StereoTargetEyeMask.None;
  2647. camL.renderingPath = RenderingPath.Forward;//Minimal overhead
  2648. camL.clearFlags = CameraClearFlags.Color;
  2649. camL.backgroundColor = Color.black;
  2650. camL.cullingMask = 0; //It should see nothing. It gets its final image entirely from a Graphics.Blit call in ZEDMirror.
  2651. camL.allowHDR = false;
  2652. camL.allowMSAA = false;
  2653. camL.useOcclusionCulling = false;
  2654. camL.depth = cameraLeft.GetComponent<Camera>().depth; //Make sure it renders after the left cam so we can copy texture from latest frame.
  2655. }
  2656. #endregion
  2657. /// <summary>
  2658. /// Closes out the current stream, then starts it up again while maintaining tracking data.
  2659. /// Used when the zed becomes unplugged, or you want to change a setting at runtime that
  2660. /// requires re-initializing the camera.
  2661. /// </summary>
  2662. public void Reset()
  2663. {
  2664. //Save tracking
  2665. if (enableTracking && isTrackingEnable)
  2666. {
  2667. zedCamera.GetPosition(ref zedOrientation, ref zedPosition);
  2668. }
  2669. CloseManager();
  2670. openingLaunched = false;
  2671. running = false;
  2672. numberTriesOpening = 0;
  2673. forceCloseInit = false;
  2674. Awake();
  2675. }
  2676. public void Reboot()
  2677. {
  2678. //Save tracking
  2679. if (enableTracking && isTrackingEnable)
  2680. {
  2681. zedCamera.GetPosition(ref zedOrientation, ref zedPosition);
  2682. }
  2683. int sn = zedCamera.GetZEDSerialNumber();
  2684. CloseManager();
  2685. openingLaunched = false;
  2686. running = false;
  2687. numberTriesOpening = 0;
  2688. forceCloseInit = false;
  2689. bool isCameraAvailable = false;
  2690. Thread.Sleep(1000);
  2691. sl.ERROR_CODE err = sl.ZEDCamera.Reboot(sn);
  2692. if (err == sl.ERROR_CODE.SUCCESS)
  2693. {
  2694. int count = 0;
  2695. // Check if the camera is available before trying to re open it
  2696. while (!isCameraAvailable && count < 30)
  2697. {
  2698. count++;
  2699. sl.DeviceProperties[] devices = sl.ZEDCamera.GetDeviceList(out int nbDevices);
  2700. for (int i = 0; i < nbDevices; i++)
  2701. {
  2702. if (sn == devices[i].sn)
  2703. {
  2704. isCameraAvailable = true;
  2705. break;
  2706. }
  2707. }
  2708. Thread.Sleep(500);
  2709. }
  2710. }
  2711. if (isCameraAvailable)
  2712. {
  2713. Debug.LogWarning("Reboot successful.");
  2714. Awake();
  2715. }
  2716. else
  2717. {
  2718. Debug.LogWarning("Unable to reboot correctly.");
  2719. #if UNITY_EDITOR
  2720. UnityEditor.EditorApplication.isPlaying = false;
  2721. #else
  2722. Application.Quit();
  2723. #endif
  2724. }
  2725. }
  2726. public void InitVideoSettings(VideoSettingsInitMode mode)
  2727. {
  2728. if (!zedCamera.IsCameraReady)
  2729. {
  2730. Debug.LogError("Tried to apply camera settings before ZED camera was ready.");
  2731. return;
  2732. }
  2733. switch (mode)
  2734. {
  2735. case VideoSettingsInitMode.Custom:
  2736. ApplyLocalVideoSettingsToZED();
  2737. return;
  2738. case VideoSettingsInitMode.LoadFromSDK:
  2739. default:
  2740. //This is the SDK's default behavior, so we don't need to specify anything. Just apply the ZED's values locally.
  2741. GetCurrentVideoSettings();
  2742. return;
  2743. case VideoSettingsInitMode.Default:
  2744. zedCamera.ResetCameraSettings();
  2745. GetCurrentVideoSettings();
  2746. return;
  2747. }
  2748. }
  2749. private void GetCurrentVideoSettings()
  2750. {
  2751. //Sets all the video setting values to the ones currently applied to the ZED.
  2752. videoBrightness = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.BRIGHTNESS);
  2753. videoContrast = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.CONTRAST);
  2754. videoHue = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.HUE);
  2755. videoSaturation = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.SATURATION);
  2756. videoSharpness = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.SHARPNESS);
  2757. videoGamma = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.GAMMA);
  2758. videoAutoGainExposure = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.AEC_AGC) == 1 ? true : false;
  2759. if (!videoAutoGainExposure)
  2760. {
  2761. videoGain = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.GAIN);
  2762. videoExposure = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.EXPOSURE);
  2763. }
  2764. videoAutoWhiteBalance = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.AUTO_WHITEBALANCE) == 1 ? true : false;
  2765. if (!videoAutoWhiteBalance)
  2766. {
  2767. videoWhiteBalance = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.WHITEBALANCE);
  2768. }
  2769. videoLEDStatus = zedCamera.GetCameraSettings(sl.CAMERA_SETTINGS.LED_STATUS) == 1 ? true : false;
  2770. }
  2771. private void ApplyLocalVideoSettingsToZED()
  2772. {
  2773. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.BRIGHTNESS, videoBrightness);
  2774. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.CONTRAST, videoContrast);
  2775. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.HUE, videoHue);
  2776. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.SATURATION, videoSaturation);
  2777. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.SHARPNESS, videoSharpness);
  2778. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.GAMMA, videoGamma);
  2779. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.AEC_AGC, videoAutoGainExposure ? 1 : 0);
  2780. if (!videoAutoGainExposure)
  2781. {
  2782. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.GAIN, videoGain);
  2783. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.EXPOSURE, videoExposure);
  2784. }
  2785. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.AUTO_WHITEBALANCE, videoAutoWhiteBalance ? 1 : 0);
  2786. if (!videoAutoWhiteBalance)
  2787. {
  2788. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.WHITEBALANCE, videoWhiteBalance);
  2789. }
  2790. zedCamera.SetCameraSettings(sl.CAMERA_SETTINGS.LED_STATUS, 1);
  2791. }
  2792. #region EventHandler
  2793. /// <summary>
  2794. /// Changes the real-world brightness by setting the brightness value in the shaders.
  2795. /// </summary>
  2796. /// <param name="newVal">New brightness value to be applied. Should be between 0 and 100.</param>
  2797. public void SetCameraBrightness(int newVal)
  2798. {
  2799. SetFloatValueOnPlaneMaterials("_ZEDFactorAffectReal", newVal / 100f);
  2800. }
  2801. #if ZED_HDRP
  2802. public void SetSelfIllumination(float newVal)
  2803. {
  2804. SetFloatValueOnPlaneMaterials("_SelfIllumination", newVal);
  2805. }
  2806. #endif
  2807. /// <summary>
  2808. /// Sets the maximum depth range of real-world objects. Pixels further than this range are discarded.
  2809. /// </summary>
  2810. /// <param name="newVal">Furthest distance, in meters, that the camera will display pixels for. Should be between 0 and 20.</param>
  2811. public void SetMaxDepthRange(float newVal)
  2812. {
  2813. if (newVal < 0 || newVal > 40)
  2814. {
  2815. Debug.LogWarning("Tried to set max depth range to " + newVal + "m. Must be within 0m and 40m.");
  2816. newVal = Mathf.Clamp(newVal, 0, 40);
  2817. }
  2818. SetFloatValueOnPlaneMaterials("_MaxDepth", newVal);
  2819. }
  2820. /// <summary>
  2821. /// Sets a value of a float property on the material(s) rendering the ZED image.
  2822. /// Used to set things like brightness and maximum depth.
  2823. /// </summary>
  2824. /// <param name="propertyname">Name of value/property within Shader. </param>
  2825. /// <param name="newvalue">New value for the specified property.</param>
  2826. private void SetFloatValueOnPlaneMaterials(string propertyname, float newvalue)
  2827. {
  2828. foreach (ZEDRenderingPlane renderPlane in GetComponentsInChildren<ZEDRenderingPlane>())
  2829. {
  2830. Material rendmat;
  2831. if (renderPlane.ActualRenderingPath == RenderingPath.Forward) rendmat = renderPlane.canvas.GetComponent<Renderer>().material;
  2832. else if (renderPlane.ActualRenderingPath == RenderingPath.DeferredShading) rendmat = renderPlane.deferredMat;
  2833. else
  2834. {
  2835. Debug.LogError("Can't set " + propertyname + " value for Rendering Path " + renderPlane.ActualRenderingPath +
  2836. ": only Forward and DeferredShading are supported.");
  2837. return;
  2838. }
  2839. rendmat.SetFloat(propertyname, newvalue);
  2840. }
  2841. }
  2842. private void SetBoolValueOnPlaneMaterials(string propertyname, bool newvalue)
  2843. {
  2844. foreach (ZEDRenderingPlane renderPlane in GetComponentsInChildren<ZEDRenderingPlane>())
  2845. {
  2846. Material rendmat;
  2847. MeshRenderer rend = renderPlane.canvas.GetComponent<MeshRenderer>();
  2848. if (!rend) continue;
  2849. rendmat = rend.material;
  2850. rendmat.SetInt(propertyname, newvalue ? 1 : 0);
  2851. }
  2852. }
  2853. /// <summary>
  2854. /// Flag set to true when the HMD-to-ZED calibration file has changed during runtime.
  2855. /// Causes values from the new file to be applied during Update().
  2856. /// </summary>
  2857. private bool calibrationHasChanged = false;
  2858. /// <summary>
  2859. /// Sets the calibrationHasChanged flag to true, which causes the next Update() to
  2860. /// re-apply the HMD-to-ZED offsets.
  2861. /// </summary>
  2862. private void CalibrationHasChanged()
  2863. {
  2864. calibrationHasChanged = true;
  2865. }
  2866. #endregion
  2867. #if UNITY_EDITOR
  2868. /// <summary>
  2869. /// Handles changes to tracking or graphics settings changed from the Inspector.
  2870. /// </summary>
  2871. void OnValidate()
  2872. {
  2873. if (zedCamera != null)
  2874. {
  2875. // If tracking has been switched on
  2876. if (zedCamera.IsCameraReady && !isTrackingEnable && enableTracking)
  2877. {
  2878. //Enables tracking and initializes the first position of the camera.
  2879. if (!(enableTracking = (zedCamera.EnableTracking(ref zedOrientation, ref zedPosition, enableSpatialMemory, enablePoseSmoothing, estimateInitialPosition, trackingIsStatic,
  2880. enableIMUFusion, pathSpatialMemory) == sl.ERROR_CODE.SUCCESS)))
  2881. {
  2882. isZEDTracked = false;
  2883. throw new Exception(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.TRACKING_NOT_INITIALIZED));
  2884. }
  2885. else
  2886. {
  2887. isZEDTracked = true;
  2888. isTrackingEnable = true;
  2889. }
  2890. }
  2891. // If tracking has been switched off
  2892. if (isTrackingEnable && !enableTracking)
  2893. {
  2894. isZEDTracked = false;
  2895. lock (zedCamera.grabLock)
  2896. {
  2897. zedCamera.DisableTracking();
  2898. }
  2899. isTrackingEnable = false;
  2900. }
  2901. // If streaming has been switched on
  2902. if (enableStreaming && !isStreamingEnable)
  2903. {
  2904. lock (zedCamera.grabLock)
  2905. {
  2906. sl.ERROR_CODE err = zedCamera.EnableStreaming(streamingCodec, (uint)bitrate, (ushort)streamingPort, gopSize, adaptativeBitrate, chunkSize, streamingTargetFramerate);
  2907. if (err == sl.ERROR_CODE.SUCCESS)
  2908. {
  2909. isStreamingEnable = true;
  2910. }
  2911. else
  2912. {
  2913. enableStreaming = false;
  2914. isStreamingEnable = false;
  2915. }
  2916. }
  2917. }
  2918. // If streaming has been switched off
  2919. if (!enableStreaming && isStreamingEnable)
  2920. {
  2921. lock (zedCamera.grabLock)
  2922. {
  2923. zedCamera.DisableStreaming();
  2924. isStreamingEnable = false;
  2925. }
  2926. }
  2927. //Reapplies graphics settings based on current values.
  2928. setRenderingSettings();
  2929. }
  2930. }
  2931. #endif
  2932. }