-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathMainBehavior.cs
More file actions
1057 lines (831 loc) · 30.3 KB
/
MainBehavior.cs
File metadata and controls
1057 lines (831 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using IngameDebugConsole;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using TMPro;
#if UNITY_WEBGL
using System.Runtime.InteropServices; //Dllimport
using UnityEngine.Networking; //UnityWebRequest
#endif
public enum FileTypes {
NotExists, Dir, Unsupported,
Img, Vid, Depth, //These 3 are heavily dependent on Unity components and interwined
Online,
Gif,
Pgm,
Zmq,
ImgZmq, VidZmq, //Image/Video files that `zmq_id` (ffmpeg) can handle - but UnityPlayer can't
};
public class MainBehavior : MonoBehaviour {
//TODO: seperate the file selection
//TODO: seperate the UI (Toggle, ...)
public TMP_InputField FilepathInputField;
public Toggle OutputSaveToggle;
public Toggle SearchCacheToggle;
public GameObject UI;
public GameObject WorldTextPlane;
public GameObject BrowseDirPanel;
public TMP_Text BrowseDirText;
public Toggle BrowseDirRandomToggle;
public Toggle BrowseDirGifToggle;
public GameObject OptionsScrollView; //To check if it is active; if it is, mousewheel will not be used for traversing files for BrowseDir
public GameObject WebXRSet; //same as above
private FileTypes _currentFileType = FileTypes.NotExists;
private TexInputs _texInputs;
private MeshBehavior _meshBehav;
private DepthModelBehavior _depthModelBehav;
private DepthModel _donnx;
private VRRecordBehavior _vrRecordBehav;
private ServerConnectBehavior _serverBehav;
private VideoPlayer _vp;
private bool _searchCache;
private bool _canUpdateArchive; //User option, toggled in UI; can be ignored
private KeyCode[] _sendMsgKeyCodes; //When a key in the array is pressed, it is sent to _texInputs using SendMsg().
private FileSelecter _fileSelecter;
private string[] _dirFilenames; //set by BrowseDir()
private int _dirFileIdx;
private List<int> _dirRandomIdxList;
private int _dirGifCount; //number of gif files of the dir.
private bool _dirRandom = false;
private ZmqTexInputs _zmqTexInputs = null; //If this is set, pass some inputs (vid/gif) to this.
private float _zmqTimeout = 2;
private int _zmqFailTolerance = 3;
private bool _hasExecutedInitCmds = false;
private Queue<string> _cmdQ; //executed by one by each Update()
private bool _forceStopOnLoop = false; //See ImgVid...
public bool DirRandom {
get => _dirRandom;
set {
//Avoid the recursive call
if (_dirRandom == value) return;
_dirRandom = value;
if (value) {//reshuffle
Debug.Log("Shuffle is on.");
ShuffleBrowseDirRandomIdxList();
}
else {
Debug.Log("Shuffle is off.");
//shuffle -> noshuffle: set the index to be what is currently being shown
if (_dirFilenames != null && _dirFilenames.Length >= 0) {
int idx = System.Array.FindIndex(_dirFilenames, (x) => x == FilepathInputField.text);
if (idx >= 0)
_dirFileIdx = idx;
}
}
if (BrowseDirRandomToggle.isOn != value)
BrowseDirRandomToggle.isOn = value;
}
}
void Start() {
_meshBehav = GameObject.Find("DepthPlane").GetComponent<MeshBehavior>();
_depthModelBehav = GameObject.Find("DepthModel").GetComponent<DepthModelBehavior>();
_vrRecordBehav = GameObject.Find("VRRecord").GetComponent<VRRecordBehavior>();
_serverBehav = GameObject.Find("ServerConnect").GetComponent<ServerConnectBehavior>();
_vp = GameObject.Find("Video Player").GetComponent<VideoPlayer>();
ToggleOutputSave(); //initializing _canUpdateArchive
ToggleSearchCache(); //init. _searchCache
/* Check the first arguement */
_cmdQ = new Queue<string>();
string[] args = System.Environment.GetCommandLineArgs();
for (int i = 1; i < args.Length; i++) {
string arg = args[i];
EnqueueCmd($"select_file \"{arg}\"");
}
if (args.Length > 1) {
string arg = args[1];
FileTypes argFileType = GetFileType(arg);
if (argFileType == FileTypes.Img || argFileType == FileTypes.Vid) {
SelectFile(arg);
}
}
/* If this key is pressed, _texInputs is informed. */
//Not used anymore.
_sendMsgKeyCodes = new KeyCode[] {
};
_fileSelecter = new StandaloneFileSelecter();
#if UNITY_WEBGL && !UNITY_EDITOR
_canUpdateArchive = false;
_searchCache = false;
/* File browsing for WebGL */
IsVideoToggle.gameObject.SetActive(true);
WebXRSet.SetActive(true);
#elif UNITY_ANDROID && !UNITY_EDITOR
FileBrowser.SetFilters(false, new FileBrowser.Filter("Image/Video/Depth Files", Exts.AllExtsWithoutDot));
Screen.sleepTimeout = SleepTimeout.NeverSleep;
Screen.brightness = 1.0f;
#endif
/*Console methods*/
AddCommandDelegate addcmd = DebugLogConsole.AddCommandInstance;
addcmd("httpinput", "Get images from a url", "HttpOnlineTexStart", this);
addcmd("load_builtin", "Load the built-in model", "LoadBuiltIn", this);
addcmd("load_model", "Load ONNX model from path", "LoadModel", this);
addcmd("send_msg", "Send a message to _texInputs", "SendMsgToTexInputs", this);
addcmd("set_mousemove", "Whether the mesh would follow the mouse", "SetMoveMeshByMouse", this);
addcmd("set_fileselecter", "Select the file selecter (standalone, simple)", "SetFileSelecter", this);
addcmd("set_dof", "Set the DoF [3, 6]", "SetDof", this);
addcmd("zmq", "Load the ZeroMQ model", "LoadZmqModel", this);
addcmd("zmq_id", "Connect to the ZeroMQ for image & depth (ffpymq.py)", "SetZmqTexInputs", this);
addcmd("set_zmq_timeout", "Set the timeout value for ZMQ", "SetZmqTimeout", this);
addcmd("set_zmq_fail_tol", "Set the fail tolerance value for ZMQ", "SetZmqFailTolerance", this);
addcmd("enqcmd", "Queue a command to be popped by each Update.", "EnqueueCmd", this);
addcmd("enqcmd_after", "Queue a command after the set seconds", "EnqueueCmdAfter", this);
addcmd("select_file", "Load the target file.", "SelectFile", this);
addcmd("scroll_dir", "Scroll thru the open dir", "ScrollDir", this);
addcmd("set_video_speed", "Set the speed of the video player", "SetVideoSpeed", this);
addcmd("wiggle", "Rotate the mesh in a predefined manner", "Wiggle", this);
addcmd("wiggle4", "Rotate the mesh in a predefined manner (4 vars)", "Wiggle4", this);
addcmd("stopwiggle", "Stop wiggling", "StopWiggle", this);
addcmd("e", "Save the parameters for image/video inputs (on the first frame, force) (shorthand for `send_msg e`)", "SendMsgE", this);
addcmd("ec", "Save the parameters for image/video inputs (on the current frame) (shorthand for `send_msg ec`)", "SendMsgEc", this);
addcmd("ecf", "Save the parameters for image/video inputs (on the current frame, force) (shorthand for `send_msg ecf`)", "SendMsgEcf", this);
addcmd("eclear", "Clear the parameters for image/video inputs (shorthand for `send_msg eclear`)", "SendMsgEclear", this);
addcmd("print_model_metadata", "Print the metadata of the current model (only supports ORT)", "PrintCurrentModelMetadata", this);
addcmd("set_ort_gpuid", "Set the id of the GPU. default: 0", "SetOrtGpuId", this);
addcmd("set_ort_gpu_provider", "Set the provider of the GPU accel. for ORT (try: `cuda`)", "SetOrtGpuProvider", this);
addcmd("set_ort_settings", "Set the settings string for GPU execution provider. default: null. Type \"null\" for the null value.", "SetOrtGpuSettings", this);
addcmd("set_wh_fallback", "Set the fallback value of the model inference size.", "SetModelWHFallback", this);
addcmd("dbg", "Temporary method for debugging.", "DebugTmp", this);
addcmd("force_stop_on_loop", "On native video inputs, force reload the video instead of pause on the loop points. Defaults to false.", "SetForceStopOnLoop", this); //See ImgVid...
addcmd("vrmode", "Enter VR mode (incomplete, controls won't work)", "EnterVrMode", this);
#if UNITY_EDITOR
addcmd("sa", "Save the mesh as an asset (Editor only)", "SaveMeshAsAsset", this);
#endif
//Load the built-in model: Not using the LoadBuiltIn() since that needs other components to be loaded
_donnx = _depthModelBehav.GetBuiltIn();
//Try to load the options
try {
MeshSliderParents.ImportMinMax();
bool searchCache, saveOutput;
Utils.ReadOptionsString(out searchCache, out saveOutput);
SearchCacheToggle.isOn = searchCache;
OutputSaveToggle.isOn = saveOutput;
}
catch (Exception exc) {
Debug.LogError($"Failed to load the options: {exc}");
}
}
void Update() {
/* Hide the UI */
if (Input.GetMouseButtonDown(1) || Input.GetKeyDown(Keymapper.Inst.HideUI))
HideUI();
/* Scroll the directory */
//Check if the scroll key is in
bool shouldScroll = false;
bool scrollDirection = true;
if (Keymapper.Inst.UseMouseWheel && Input.mouseScrollDelta.y != 0) {
shouldScroll = true;
scrollDirection = Input.mouseScrollDelta.y < 0;
}
else if (Input.GetKeyDown(Keymapper.Inst.PrevFileInDir)) {
shouldScroll = true;
scrollDirection = false;
}
else if (Input.GetKeyDown(Keymapper.Inst.NextFileInDir)) {
shouldScroll = true;
scrollDirection = true;
}
else {
shouldScroll = false; //not needed
}
if (_dirFilenames != null && shouldScroll && (OptionsScrollView == null || !UI.activeSelf || !OptionsScrollView.activeSelf)) //null check for OptionsScrollView is not needed
SetBrowseDir(scrollDirection);
/* Toggle shuffle */
if (Input.GetKeyDown(Keymapper.Inst.ToggleShuffle))
DirRandom = !DirRandom;
string statusText = null;
/* Check if the model got disposed */
if (_donnx == null)
statusText = "Model is not set!";
else if (_donnx.IsDisposed) {
Cleanup();
statusText = "Model got disposed!";
}
else if (_texInputs != null) {
_texInputs.UpdateTex();
/* Send the key to _texInputs (Not used anymore) */
foreach (var key in _sendMsgKeyCodes)
if (Input.GetKeyDown(key))
SendMsgToTexInputs(key.ToString());
}
else
statusText = "Input is not set. (See console `)";
if (statusText != null)
UITextSet.StatusText.text = statusText;
//This can't be a async'd since some needs to be on the main thread
//Also can't be on Start() since some needs to be loaded initially
if (!_hasExecutedInitCmds) {
_hasExecutedInitCmds = true; //Don't care if the code below crashes
ExecuteInitCmds();
}
if (_cmdQ.Count > 0) {
string cmdFromQ = _cmdQ.Dequeue();
Utils.ExecuteCmd(cmdFromQ);
}
}
private void Cleanup() {
/* Called by SelectFile(), DesktopRenderingStart() */
if (_texInputs != _zmqTexInputs) { //_zmqTexInputs is handled elsewhere
_texInputs?.Dispose();
_texInputs = null;
}
else if (_zmqTexInputs != null && _zmqTexInputs.IsConnected) {
_zmqTexInputs.RequestStop();
}
DepthFileUtils.Dispose(); //not needed, should be handled at _texInputs.Dispose()
_currentFileType = FileTypes.Unsupported;
UITextSet.OutputSaveText.text = "";
UITextSet.StatusText.text = "";
UITextSet.FilepathResultText.text = "";
_meshBehav.ShouldUpdateDepth = false; //only true in images
}
void OnApplicationQuit() {
#if UNITY_WEBGL
StatusText.text = "Quitting.";
#endif
Cleanup();
if (_zmqTexInputs != null) {
_zmqTexInputs.Dispose();
_zmqTexInputs = null;
}
if (_vp != null)
Destroy(_vp);
_donnx?.Dispose();
_donnx = null;
if (_meshBehav != null)
Destroy(_meshBehav);
//Try to save the options
try {
MeshSliderParents.ExportMinMax();
Utils.WriteOptionsString(SearchCacheToggle.isOn, OutputSaveToggle.isOn);
}
catch (Exception e) {
//will not be shown on the build
Debug.LogError($"Error saving the options: {e}");
}
Debug.Log("Disposed.");
}
public void Quit() =>
Application.Quit();
public void CheckFileExists() {
string filepath = FilepathInputField.text;
FileTypes ftype = GetFileType(filepath);
string output = $"Type: {ftype}";
UITextSet.FilepathResultText.text = output;
}
public void OnFilepathEntered() =>
SelectFile(FilepathInputField.text);
public void SelectFile(string filepath) {
/*
Check if the depth file exists & load it if if exists.
If new image/video was selected and the previous one was a video, save it.
*/
//TODO: Uncouple tihs with `FilepathInputField`
if (_serverBehav.IsWaiting) {
UITextSet.StatusText.text = "Waiting for the server...";
return;
}
FilepathInputField.text = filepath;
FileTypes ftype = GetFileType(filepath);
if (_texInputs != null && _texInputs.WaitingSequentialInput) {
/* Selecting the texture for depthfile */
_texInputs.SequentialInput(filepath, ftype);
return;
}
bool isSupportedType = false;
var supportedFileTypes = new List<FileTypes>(new FileTypes[] {FileTypes.Img, FileTypes.Vid, FileTypes.Depth, FileTypes.Gif, FileTypes.Pgm});
//Add `zmq_id`-supported exts
if (_zmqTexInputs != null && _zmqTexInputs.IsConnected) {
supportedFileTypes.Add(FileTypes.ImgZmq);
supportedFileTypes.Add(FileTypes.VidZmq);
}
//Check if the `ftype` is in `supportedFileTypes`
foreach (var t in supportedFileTypes)
if (ftype == t) {
isSupportedType = true;
break;
}
if (!isSupportedType) {
UITextSet.FilepathResultText.text = $"Unsupported type: {ftype}";
return;
}
Cleanup();
//Pass to ZmqTexInputs if it is connected
if (_zmqTexInputs != null && _zmqTexInputs.IsConnected)
foreach (var forzmq in new FileTypes[] {FileTypes.Vid, FileTypes.Img, FileTypes.Gif, FileTypes.ImgZmq, FileTypes.VidZmq})
if (ftype == forzmq)
ftype = FileTypes.Zmq;
_currentFileType = ftype;
UITextSet.FilepathResultText.text = $"Current Type: {ftype}";
switch (ftype) {
case FileTypes.Img:
case FileTypes.Vid:
case FileTypes.Depth:
_texInputs = new ImgVidDepthTexInputs(_currentFileType, _meshBehav, _donnx, filepath, _searchCache, _canUpdateArchive, _vp, _vrRecordBehav, _serverBehav, forceStopNotPauseOnLoopPoints: _forceStopOnLoop);
break;
case FileTypes.Gif:
_texInputs = new GifTexInputs(filepath, _donnx, _meshBehav);
break;
case FileTypes.Pgm:
_texInputs = new PgmTexInputs(filepath, _meshBehav);
break;
case FileTypes.Zmq:
FileTypes ext = Exts.FileTypeCheck(filepath);
bool isImage = (ext == FileTypes.Img || ext == FileTypes.ImgZmq);
_zmqTexInputs.RequestPlay(filepath, isImage: isImage);
_texInputs = _zmqTexInputs;
break;
default:
UITextSet.StatusText.text = "DEBUG: SelectFile(): something messed up :(";
Debug.LogError($"SelectFile(): ftype {ftype} is in supportedFileTypes but not implemented");
break;
}
}
public static FileTypes GetFileType(string filepath) {
bool file_exists = File.Exists(filepath);
bool dir_exists = Directory.Exists(filepath);
if (!file_exists && !dir_exists)
return FileTypes.NotExists;
if (dir_exists)
return FileTypes.Dir;
return Exts.FileTypeCheck(filepath);
}
public void DesktopRenderingStart() =>
OnlineTexStart(GameObject.Find("DesktopRender").GetComponent<DesktopRenderBehavior>()); //deprecated
public void HttpOnlineTexStart(string url) =>
OnlineTexStart(new HttpOnlineTex(url));
private void OnlineTexStart(OnlineTex otex) {
if (!otex.Supported) {
Debug.LogError("OnlineTexStart() called when !otex.Supported");
return;
}
if (_serverBehav.IsWaiting) { //TODO: REMOVE ALL REFERENCES FOR ServerBehavior (DEPRECATED) AND ALL LINES INVOLVING "Waiting for the server", HERE AND ALSO IN `Img...Behav`.
UITextSet.StatusText.text = "Waiting for the server.";
return;
}
Cleanup(); //This sets _currentFileType. All tasks needed for stopping is handled here.
ClearBrowseDir();
_currentFileType = FileTypes.Online;
_texInputs = new OnlineTexInputs(_donnx, _meshBehav, otex);
}
private void SetZmqTexInputs(int port=5556) {
if (port < 0) {
Debug.Log($"Disconnecting from port {port}...");
_zmqTexInputs?.Dispose();
_zmqTexInputs = null;
return;
}
Debug.Log($"Setting the ZmqTexInputs port to {port}...");
_zmqTexInputs?.Dispose();
_zmqTexInputs = new ZmqTexInputs(_meshBehav, port, timeout: _zmqTimeout, failTolerance: _zmqFailTolerance);
if (!_zmqTexInputs.IsConnected) {
Debug.LogWarning($"Counldn't connect to the port {port}.");
_zmqTexInputs.Dispose();
_zmqTexInputs = null;
}
else {
Debug.Log($"Connected to the port {port}! Passing Video/Gif/Img inputs to this.");
Cleanup();
_texInputs = _zmqTexInputs;
}
}
public void LoadBuiltIn() {
Cleanup();
_donnx?.Dispose();
UITextSet.StatusText.text = "RELOAD"; //Not effective anymore (TODO: delete this line)
_donnx = _depthModelBehav.GetBuiltIn();
Debug.Log("Loaded the built-in model.");
}
//Mant to be used with the console
public void LoadModel(string onnxpath, bool useOnnxRuntime=false) {
Cleanup();
_donnx?.Dispose();
UITextSet.StatusText.text = "RELOAD"; //Not effective anymore (TODO: delete this line)
Debug.Log($"Loading model: {onnxpath}");
string modelTypeStr = Path.GetFileNameWithoutExtension(onnxpath);
try {
_donnx = _depthModelBehav.GetDepthModel(onnxpath, modelTypeStr, useOnnxRuntime: useOnnxRuntime);
}
catch (Exception exc) {
_donnx?.Dispose();
_donnx = null;
Debug.LogError("LoadModel(): Got exception: " + exc);
}
//Failure
if (_donnx == null) {
Debug.LogError($"Failed to load: {modelTypeStr}");
return;
}
Debug.Log($"Loaded the model: {modelTypeStr}");
}
public void LoadZmqModel(int port=5555) {
Cleanup();
_donnx?.Dispose();
UITextSet.StatusText.text = "RELOAD";
_donnx = _depthModelBehav.GetZmqDepthModel(port, timeout: _zmqTimeout, failTolerance: _zmqFailTolerance);
}
public void SetZmqTimeout(float sec) {
_zmqTimeout = sec;
Debug.Log($"Zmq Timeout set to {sec}.");
}
public void SetZmqFailTolerance(int tries) {
_zmqFailTolerance = tries;
Debug.Log($"Zmq Fail Tolerance set to {tries}");
}
public void HideUI() {
UI.SetActive(!UI.activeSelf);
WorldTextPlane.SetActive(!WorldTextPlane.activeSelf);
}
public void ToggleFullscreen() {
if (Screen.fullScreenMode == FullScreenMode.Windowed)
Screen.fullScreenMode = FullScreenMode.MaximizedWindow;
else
Screen.fullScreenMode = FullScreenMode.Windowed;
}
public void ToggleOutputSave() {
_canUpdateArchive = OutputSaveToggle.isOn;
if (_canUpdateArchive) { //turn on _searchCache too
SearchCacheToggle.isOn = true;
SearchCacheToggle.interactable = false;
}
else {
SearchCacheToggle.interactable = true;
}
}
public void ToggleSearchCache() {
_searchCache = SearchCacheToggle.isOn;
}
public void OpenOutputFolder() {
Application.OpenURL(DepthFileUtils.SaveDir);
}
/* Implementations of BrowseFiles() */
#if !(UNITY_WEBGL && !UNITY_EDITOR)
public void BrowseFiles() =>
_fileSelecter.SelectFile((path) => {
ClearBrowseDir();
SelectFile(path);
});
#elif UNITY_WEBGL && !UNITY_EDITOR //#else
public void BrowseFiles() =>
_fileSelecter.SelectFile((path) => {
Cleanup();
_currentFileType = FileTypes.Img;
StartCoroutine(GetRequest(new System.Uri(url).AbsoluteUri));
});
IEnumerator GetRequest(string uri) {
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri)) {
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
switch (webRequest.result) {
case UnityWebRequest.Result.ConnectionError:
case UnityWebRequest.Result.DataProcessingError:
StatusText.text = ("Error: " + webRequest.error);
break;
case UnityWebRequest.Result.ProtocolError:
StatusText.text = ("HTTP Error: " + webRequest.error);
break;
case UnityWebRequest.Result.Success:
StatusText.text = ("Received");
Texture2D texture = Utils.LoadImage(webRequest.downloadHandler.data);
Depth depth = _donnx.Run(texture);
_meshBehav.SetScene(depth, texture);
break;
}
}
}
#endif
public void ToggleBrowseDirPanel() =>
WindowManager.SetCurrentWindow(BrowseDirPanel);
public void OnBrowseDirRandomToggleValueChanged() {
//Called when the toggle on UI is changed
DirRandom = BrowseDirRandomToggle.isOn;
}
private void ShuffleBrowseDirRandomIdxList() {
if (_dirFilenames == null) return;
if (_dirRandomIdxList == null || _dirRandomIdxList.Count != _dirFilenames.Length) {
_dirRandomIdxList = new List<int>();
for (int i = 0; i < _dirFilenames.Length; i++)
_dirRandomIdxList.Add(i);
}
/* Shuffle */
for (int i = 0; i < _dirRandomIdxList.Count; i++) {
int randomidx = UnityEngine.Random.Range(i, _dirRandomIdxList.Count);
int tmp = _dirRandomIdxList[i];
_dirRandomIdxList[i] = _dirRandomIdxList[randomidx];
_dirRandomIdxList[randomidx] = tmp;
}
}
public void ClearBrowseDir() {
_dirFilenames = null;
_dirRandomIdxList = null;
BrowseDirText.text = "";
}
public void ScrollDir(bool next=true) {
if (_dirFilenames != null)
SetBrowseDir(next);
}
private void SetBrowseDir(bool next=true) {
if (_dirFilenames == null) {
Debug.LogError("SetBrowseDir() called when _dirFilenames == null");
return;
}
if (_dirFilenames.Length == 0)
return;
if (_serverBehav.IsWaiting) {
UITextSet.StatusText.text = "Waiting the server.";
return;
}
_dirFileIdx += (next) ? +1 : -1;
_dirFileIdx = (_dirFileIdx % _dirFilenames.Length);
if (_dirFileIdx < 0) _dirFileIdx += _dirFilenames.Length;
int idx = (_dirRandom) ? _dirRandomIdxList[_dirFileIdx] : _dirFileIdx;
string newfilename = _dirFilenames[idx];
if (!BrowseDirGifToggle.isOn && Exts.FileTypeCheck(newfilename) == FileTypes.Gif) {
/* Skip GIF files */
/* When the directory only has Gif files */
if (_dirGifCount == _dirFilenames.Length)
return;
SetBrowseDir(next);
return;
}
SelectFile(newfilename);
}
public void SetBrowseDirName(string dirname) {
if (!Directory.Exists(dirname)) {
Debug.LogError($"BrowseDirs() callback: dir {dirname} does not exist. This shouldn't be seen when using the file browser...");
return;
}
int gifcount = 0; //number of the gif files in the directory.
//Add only: img, vid, gif
List<string> filenames_list = new List<string>();
foreach (string filename in Directory.GetFiles(dirname)) {
FileTypes ftype = Exts.FileTypeCheck(filename);
if (ftype == FileTypes.Img || ftype == FileTypes.Vid || ftype == FileTypes.Gif) {
filenames_list.Add(filename);
if (ftype == FileTypes.Gif)
gifcount++;
}
}
if (filenames_list.Count == 0)
return;
if (!BrowseDirGifToggle.isOn && (gifcount == filenames_list.Count)) //directory with only gif files
return;
BrowseDirText.text = dirname;
_dirFilenames = filenames_list.ToArray();
_dirFileIdx = 0;
_dirGifCount = gifcount;
ShuffleBrowseDirRandomIdxList();
SetBrowseDir();
}
/* Implementations of BrowseDirs() */
#if UNITY_STANDALONE || UNITY_EDITOR
//Also used by Keymapper.cs
public void BrowseDirs() =>
_fileSelecter.SelectDir(SetBrowseDirName);
#else
public void BrowseDirs() {
Debug.LogError("Not implemented.");
return;
}
#endif
public void SetVideoSpeed(float mult) {
if (_vp == null) {
Debug.LogError("SetVideoSpeed() called when _vp == null");
return;
}
_vp.playbackSpeed = mult;
}
public void SendMsgToTexInputs(string msg) {
if (_texInputs == null) {
Debug.LogError("_texInputs == null");
return;
}
_texInputs.SendMsg(msg);
}
public void SendMsgE() => SendMsgToTexInputs("e");
public void SendMsgEc() => SendMsgToTexInputs("ec");
public void SendMsgEcf() => SendMsgToTexInputs("ecf");
public void SendMsgEclear() => SendMsgToTexInputs("eclear");
public void MeshToDefault() =>
_meshBehav.ToDefault();
public void SetTargetValToNaN() =>
_meshBehav.TargetVal = System.Single.NaN;
public void SetMeshShader(string shadername) {
MeshShaders meshShader;
switch (shadername) {
case "standard":
meshShader = MeshShaders.GetStandard();
break;
case "pointCloudDisk":
meshShader = MeshShaders.GetPointCloudDisk();
break;
case "pointCloudPoint":
meshShader = MeshShaders.GetPointCloudPoint();
break;
default:
Debug.LogError($"SetMeshShader(): Got unknown shader name {shadername}");
return;
}
_meshBehav.SetShader(meshShader);
}
public void SetPointCloudSize(float val) =>
_meshBehav.SetMaterialFloat("_PointSize", val);
/* Where are these here */
public void SetOrtGpuProvider(string provider) =>
_depthModelBehav.OnnxRuntimeGpuProvider = provider;
public void SetOrtGpuId(int gpuId) =>
_depthModelBehav.OnnxRuntimeGpuId = gpuId;
public void SetOrtGpuSettings(string settings) =>
_depthModelBehav.OnnxRuntimeGpuSettings = (settings == "null") ? null : settings;
public void SetModelWHFallback(int w, int h) {
Debug.Log($"Setting the fallback size to {w}x{h}");
_depthModelBehav.WidthFallback = w;
_depthModelBehav.HeightFallback = h;
}
/* */
public string GetCurrentModelType() {
if (_donnx == null)
return "null";
return _donnx.ModelType;
}
public void PrintCurrentModelMetadata() =>
_donnx?.PrintMetadata();
public void SetMoveMeshByMouse(bool value) {
Debug.Log($"Setting MoveMeshByMouse = {value}");
_meshBehav.MoveMeshByMouse = value;
}
public void SetMeshTextureSetCallback(bool val, System.Action<Texture> callback=null) {
/*
Set the callback the mesh will call when the texture is ready.
Used for the skybox.
*/
if (val) {
Debug.Log("Setting the skybox.");
//Have the camera see the skybox
Camera camera = GameObject.Find("MainCamera").GetComponent<Camera>();
camera.clearFlags = CameraClearFlags.Skybox;
_meshBehav.OnTextureSet = callback;
}
else {
Debug.Log("Disabling the skybox.");
Camera camera = GameObject.Find("MainCamera").GetComponent<Camera>();
camera.clearFlags = CameraClearFlags.SolidColor;
_meshBehav.OnTextureSet = null;
RenderSettings.skybox = null;
}
}
public bool IsMeshTextureCallbackSet() =>
_meshBehav.OnTextureSet != null;
public Depth GetCurrentDepth(DepthMapType type) =>
_meshBehav.GetDepth(type);
public void GetCurrentTextureSize(out int w, out int h) =>
_meshBehav.GetTextureSize(out w, out h);
public void Wiggle(float intervalScale, float horAngle, float verAngle) {
Debug.Log($"Wiggling: {intervalScale}, ({horAngle}, {verAngle})");
_meshBehav.MeshWiggler = new Wiggler(intervalScale, horAngle, verAngle);
}
public void Wiggle4(float intervalScale, float leftAngle, float rightAngle, float upAngle, float downAngle) {
Debug.Log($"Wiggling: {intervalScale}, ({leftAngle}, {rightAngle}, {upAngle} {downAngle})");
_meshBehav.MeshWiggler = new Wiggler(intervalScale, leftAngle, rightAngle, upAngle, downAngle);
}
public void StopWiggle() {
Debug.Log("Stopping the wiggling movement...");
_meshBehav.MeshWiggler = null;
}
public void SetFileSelecter(string fileSelecter) {
Debug.Log($"SetFileSelecter: {fileSelecter}");
switch (fileSelecter) {
case "standalone":
_fileSelecter = new StandaloneFileSelecter();
return;
case "simple":
_fileSelecter = new SimpleFileSelecter();
return;
default:
Debug.LogError($"Got unknown fileSelecter {fileSelecter}");
return;
}
}
public void EnterVrMode() {
Debug.Log("VR mode (incomplete)");
SetFileSelecter("simple");
GameObject.Find("Canvas").GetComponent<TempCanvasBehavior>().VrMode();
}
public void SetDof(int dof) {
Camera camera = GameObject.Find("MainCamera").GetComponent<Camera>();
UnityEngine.SpatialTracking.TrackedPoseDriver tpd = GameObject.Find("MainCamera").GetComponent<UnityEngine.SpatialTracking.TrackedPoseDriver>();
switch (dof) {
case 3:
camera.transform.localPosition = new Vector3(0, 0, 0);
tpd.trackingType = UnityEngine.SpatialTracking.TrackedPoseDriver.TrackingType.RotationOnly;
break;
case 6:
tpd.trackingType = UnityEngine.SpatialTracking.TrackedPoseDriver.TrackingType.RotationAndPosition;
break;
default:
Debug.LogError($"Invalid DoF: {dof}");
return;
}
Debug.Log($"DoF: {dof}");
}
public void SaveMeshAsAsset() =>
_meshBehav.SaveAsAsset();
public void SetForceStopOnLoop(bool val) {
Debug.Log($"Setting _forceStopOnLoop as: {val}");
_forceStopOnLoop = val;
}
public void ExecuteInitCmds() {
try {
string[] initcmds = Utils.GetInitCmds();
if (initcmds != null)
foreach (string cmd in initcmds) {
if (cmd.StartsWith('#')) continue;
Utils.ExecuteCmd(cmd);
}
}
catch (Exception exc) {
Debug.LogError($"Exception while parsing the initcmds: {exc}");
}
}
public void EnqueueCmd(string cmd) =>
_cmdQ.Enqueue(cmd);
public void EnqueueCmdAfter(string cmd, int msec) {
Debug.Log($"Inserting \"{cmd}\" after {msec} msecs.");
Task.Run(() => {
System.Threading.Thread.Sleep(msec);
Debug.Log($"OK, Inserting \"{cmd}\"");
EnqueueCmd(cmd);
});
}
/* A method for debugging, called by the console method `dbg` */
public void DebugTmp() {
Debug.Log("DebugTmp() called.");
Debug.Log("Nothing here...");
Debug.Log("DebugTmp() exiting.");
}
}
public static class Exts {
public static Dictionary<FileTypes, string[]> ExtsDict {get; private set;}
//with no '.'
public static string[] AllExtsWithoutDot {get; private set;}
public static string[] AllExtsWithDot {get; private set;}
static Exts() {
ExtsDict = new Dictionary<FileTypes, string[]>();
ExtsDict.Add(FileTypes.Img, new string[] {".jpg", ".jpeg", ".png"});
ExtsDict.Add(FileTypes.Vid, new string[] {
".mp4",
".asf", ".avi", ".dv", ".m4v", ".mov", ".mpg", ".mpeg", ".ogv", ".vp8", ".webm", ".wmv"
});
ExtsDict.Add(FileTypes.Depth, new string[] {DepthFileUtils.DepthExt});
ExtsDict.Add(FileTypes.Gif, new string[] {".gif"});
ExtsDict.Add(FileTypes.Pgm, new string[] {".pgm"});