/
unity-util.ts
2109 lines (1861 loc) · 65.2 KB
/
unity-util.ts
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
/**
* Copyright (C) 2017 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* eslint-disable no-underscore-dangle */
/* eslint-enable no-var */
import { IndexedDbCache } from './unity-indexedbcache';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
declare let SendMessage;
declare let createUnityInstance;
export class UnityUtil {
/** @hidden */
private static errorCallback: any;
/** @hidden */
private static progressCallback: any;
/** @hidden */
private static modelLoaderProgressCallback: any;
/**
* viewer can be assigned, containing any callback function the user wishes to hook onto.
* The following functions are supported:
*
* **viewer.clipBroadcast(**_object_**)**: Called when a clipping plane broadcast occurs with
* the new clipping plane information
*
* **viewer.numClipPlanesUpdated(**_int_**)**: Called when the number of clipping planes changed,
* with the latest number of clipping planes in place
*
* **viewer.objectSelected(**_object_**)**: Notify the user which object/pin is clicked after a mouse event
*
* **viewer.objectsSelected(**_object_**)**: Notify the user which objects is selected after
* a rectangular select event
*
* **viewer.pickPointEvent(**_object_**)**: Notify the user what position within the 3D world was
* clicked after a mouse event.
*
* @example UnityUtil.viewer = {
* numClipPlanesUpdated = (nPlanes) => console.log(\`Current no. planes: ${nPlanes}\`}
*/
public static viewer: any;
/** @hidden */
public static LoadingState = {
VIEWER_READY: 1, // Viewer has been loaded
MODEL_LOADING: 2, // model information has been fetched, world offset determined, model starts loading
MODEL_LOADED: 3, // Models
};
/** @hidden */
public static unityInstance;
/** A URL pointing to the domain hosting a Unity distribution. E.g. www.3drepo.io/.
* This is where the Unity Build folder and the IndexedDb worker can be found. */
/** @hidden */
public static unityDomain: URL;
/** A URL containing the subfolder under unityUrl where the Unity build and
* its associated dependencies can be found.
* This should usually be set to "/unity/Build" */
public static unityBuildSubdirectory : any;
/** @hidden */
public static readyPromise: Promise<void>;
/** @hidden */
public static readyResolve;
/** @hidden */
public static loadedPromise;
/** @hidden */
public static loadedResolve;
/** @hidden */
public static loadingPromise;
/** @hidden */
public static loadingResolve;
// Diff promises
/** @hidden */
public static loadComparatorResolve;
/** @hidden */
public static loadComparatorPromise;
/** @hidden */
public static unityHasErrored = false;
/** @hidden */
public static screenshotPromises = [];
/** @hidden */
public static viewpointsPromises = [];
/** @hidden */
public static objectStatusPromises = [];
/** @hidden */
public static loadedFlag = false;
/** @hidden */
public static UNITY_GAME_OBJECT = 'WebGLInterface';
/** @hidden */
public static defaultHighlightColor = [1, 1, 0];
public static verbose = false;
public static usingBetaViewer = false;
/**
* Contains a list of calls to make during the Unity Update method. One
* call is made per Unity frame.
*/
public static unityOnUpdateActions = [];
/**
* Initialise Unity.
* @category Configurations
* @param errorCallback - function to call when an error occurs.
* This function should take a string(message), boolean(requires reload), boolean(came from unity).
* @param progressCallback
* @param modelLoaderProgressCallback
*/
public static init(errorCallback: any, progressCallback: any, modelLoaderProgressCallback: any, useBetaViewer = false) {
UnityUtil.errorCallback = errorCallback;
UnityUtil.progressCallback = progressCallback;
UnityUtil.modelLoaderProgressCallback = modelLoaderProgressCallback;
UnityUtil.usingBetaViewer = useBetaViewer;
UnityUtil.unityBuildSubdirectory = useBetaViewer ? '/unity/beta/Build' : '/unity/Build'; // These directories are determined by webpack.common.config.js
UnityUtil.setUnityMemory(0); // This forces the browser to update the viewer with the autodetected memory. If the user has set it explicitly in viewer settings, it will be overridden later when they are processed.
}
/** @hidden */
public static onProgress(progress: number) {
requestAnimationFrame(() => {
if (UnityUtil.progressCallback) {
UnityUtil.progressCallback(progress);
}
});
}
/**
* Removes the IndexedDb database /idbfs, which emulates a synchronous
* filesystem.
* The viewer should not store anything use the File API between runs.
*/
private static clearIdbfs(): Promise<void> {
// The following snippet makes sure only one tab ever attempts to clear
// the cache. This is because the cache only needs to be cleared once,
// and simultaneous attempts can cause stalls.
// This function uses the shared localstorage to store whether the cache
// has been cleared.
// localstorage does not have a CAS operation, but reads and writes are
// atomic.
// Below, each tab that encounters an uncleared cache will first write
// a unique id, and then attempt to read it back. Only the tab whose id
// matches will embark on the clear operation.
const clearedFlagKey = 'repoV1CacheCleared';
try {
if (!window.localStorage.getItem(clearedFlagKey)) {
const id = (Math.floor(Math.random() * 100000)).toString();
window.localStorage.setItem(clearedFlagKey, id);
if (window.localStorage.getItem(clearedFlagKey) === id) {
const deleteRequest = indexedDB.deleteDatabase('/idbfs');
return new Promise((resolve) => {
deleteRequest.onsuccess = () => {
resolve();
};
deleteRequest.onerror = () => {
console.error('Failed to delete /idbfs. Consider clearing the cache or deleting this database manually.');
resolve();
};
deleteRequest.onblocked = () => { // If the request was blocked its most likely because another tab has idbfs open, so leave it alone
resolve();
};
deleteRequest.onupgradeneeded = () => {
resolve();
};
});
}
}
} catch (error) {
console.error('Unable to clear IndexDbFs', error);
}
return Promise.resolve();
}
/**
* Returns the relative path of the Unity Loader to the current domain
*/
public static unityLoaderPath(): string {
return `${this.unityBuildSubdirectory}/unity.loader.js`;
}
/**
* Launch the Unity Game.
* @category Configurations
* @param canvas - the html dom of the unity canvas
* @param host - host server URL (e.g. https://www.3drepo.io)
* @return returns a promise which resolves when the game is loaded.
*
*/
public static loadUnity(canvas: any, host): Promise<void> {
let canvasDom = canvas;
let domainURL = host;
if (Object.prototype.toString.call(canvas) === '[object String]') {
// The user is calling it like Unity 2019. Convert it to a dom an create a canvas
console.warn('[DEPRECATED WARNING] loadUnity() no longer takes in a string and a URL to the unity config. Please check the API documentation and update your function.');
const divDom = document.getElementById(canvas);
canvasDom = document.createElement('canvas');
canvasDom.id = 'unity';
divDom.appendChild(canvasDom);
if (host) {
// Old schema asks for a json file location, we now take the domain url
// and generate the object at run time.
// eslint-disable-next-line no-useless-escape
domainURL = host.match('^https?:\/\/[^\/]+');
}
}
return this.clearIdbfs().then(() => UnityUtil._loadUnity(canvasDom, domainURL));
}
/** @hidden */
public static _loadUnity(canvas: any, domainURL): Promise<void> {
if (!window.Module) {
// Add withCredentials to XMLHttpRequest prototype to allow unity game to
// do CORS request. We used to do this with a .jspre on the unity side but it's no longer supported
// as of Unity 2019.1
(XMLHttpRequest.prototype as any).originalOpen = XMLHttpRequest.prototype.open;
// eslint-disable-next-line func-names
const newOpen = function () {
// eslint-disable-next-line
const original = this.originalOpen.apply(this, arguments);
this.withCredentials = true;
return original;
};
XMLHttpRequest.prototype.open = newOpen;
}
UnityUtil.unityDomain = new URL(domainURL || window.location.origin);
const buildUrl = new URL(UnityUtil.unityBuildSubdirectory, UnityUtil.unityDomain);
const config = {
dataUrl: `${buildUrl}/unity.data.unityweb`,
frameworkUrl: `${buildUrl}/unity.framework.js.unityweb`,
codeUrl: `${buildUrl}/unity.wasm.unityweb`,
streamingAssetsUrl: 'StreamingAssets',
companyName: '3D Repo Ltd',
productName: '3D Repo Unity',
productVersion: '1.0',
errorHandler: (e) => {
// This member is not part of the documented API, but the current version of loader.js checks for it
UnityUtil.onUnityError(e);
return true; // Returning true suppresses loader.js' alert call
},
};
createUnityInstance(canvas, config, (progress) => {
this.onProgress(progress);
}).then((unityInstance) => {
UnityUtil.unityInstance = unityInstance;
}).catch(UnityUtil.onUnityError);
return UnityUtil.onReady();
}
/**
* @category Configurations
* Quits unity instance & reset all custom callback and promises
*/
public static quitUnity() {
this.reset();
UnityUtil.errorCallback = null;
UnityUtil.progressCallback = null;
UnityUtil.modelLoaderProgressCallback = null;
UnityUtil.readyPromise = null;
UnityUtil.unityInstance.Quit();
}
/**
* Called from within the viewer on each Unity frame.
*/
public static onUpdate() {
if (this.unityOnUpdateActions.length > 0) {
const action = this.unityOnUpdateActions.shift();
action();
}
}
/**
* @hidden
* @category To Unity
* Cancels any model that is currently loading. This will reject any model promises with "cancel" as the message
*/
public static cancelLoadModel() {
if (!UnityUtil.loadedFlag && UnityUtil.loadedResolve) {
// If the previous model is being loaded but hasn't finished yet
UnityUtil.loadedResolve.reject('cancel');
}
if (UnityUtil.loadingResolve) {
UnityUtil.loadingResolve.reject('cancel');
}
}
/**
* @hidden
* Check if an error is Unity related
*/
public static isUnityError(err) {
const checks = [
'Array buffer allocation failed', 'Invalid typed array length',
'Unity', 'unity', 'emscripten', 'blob:http',
];
const hasUnityError = !checks.every((check) => err.indexOf(check) === -1);
return hasUnityError;
}
/**
* @hidden
* Handle a error from Unity
*/
public static onUnityError(message) {
let reload = false;
let conf;
if (UnityUtil.isUnityError(message)) {
reload = true;
conf = `Your browser has failed to load 3D Repo's model viewer. The following occured:
<br><br> <code>${message}</code>
<br><br> This may due to insufficient memory. Please ensure you are using a modern 64bit web browser
(such as Chrome or Firefox), reduce your memory usage and try again.
If you are unable to resolve this problem, please contact support@3drepo.com referencing the above error.
<br><md-container>`;
} else {
conf = `Something went wrong :( <br><br> <code>${message}</code><br><br>
If you are unable to resolve this problem, please contact support@3drepo.com referencing the above error
<br><br> Click OK to refresh this page<md-container>`;
}
const isUnityError = reload;
UnityUtil.userAlert(conf, reload, isUnityError);
return true;
}
/**
* Returns a promise that lets you know when the model has finished loading.
* @Category State Queries
* @return returns a Promise that resolves when the model has finished loading.
* The Promise returns the bounding box of the model.
*/
public static onLoaded(): Promise<object> {
if (!UnityUtil.loadedPromise) {
UnityUtil.loadedPromise = new Promise((resolve, reject) => {
UnityUtil.loadedResolve = { resolve, reject };
});
}
return UnityUtil.loadedPromise;
}
/**
* Returns a promise that lets you know when the model has started to load
* @Category State Queries
* @return returns a Promise that resolves when the model has started to load
*/
public static onLoading(): Promise<void> {
if (!UnityUtil.loadingPromise) {
UnityUtil.loadingPromise = new Promise((resolve, reject) => {
UnityUtil.loadingResolve = { resolve, reject };
});
}
return UnityUtil.loadingPromise;
}
/**
* Returns a promise that lets you know when the game is loaded.
* @Category State Queries
* @return returns a Promise that resolves when the game is loaded.
*/
public static onReady(): Promise<void> {
if (!UnityUtil.readyPromise) {
UnityUtil.readyPromise = new Promise((resolve, reject) => {
UnityUtil.readyResolve = { resolve, reject };
});
}
return UnityUtil.readyPromise;
}
/** @hidden */
public static userAlert(message, reload, isUnity) {
if (!UnityUtil.unityHasErrored) {
// Unity can error multiple times, we don't want
// to keep annoying the user
UnityUtil.unityHasErrored = true;
if (UnityUtil.errorCallback) {
UnityUtil.errorCallback(message, reload, isUnity);
}
}
}
/** @hidden */
public static toUnity(methodName, requireStatus?, params?) {
if (UnityUtil.verbose) {
console.debug('[TO UNITY]', methodName, requireStatus, params);
}
if (requireStatus === UnityUtil.LoadingState.MODEL_LOADED) {
// Requires model to be loaded
UnityUtil.onLoaded().then(() => {
if (UnityUtil.unityInstance) {
UnityUtil.unityInstance.SendMessage(UnityUtil.UNITY_GAME_OBJECT, methodName, params);
}
}).catch((error) => {
if (error !== 'cancel') {
console.error('UnityUtil.onLoaded() failed: ', error);
UnityUtil.userAlert(error, true, true);
}
});
} else if (requireStatus === UnityUtil.LoadingState.MODEL_LOADING) {
// Requires model to be loading
UnityUtil.onLoading().then(() => {
if (UnityUtil.unityInstance) {
UnityUtil.unityInstance.SendMessage(UnityUtil.UNITY_GAME_OBJECT, methodName, params);
}
}).catch((error) => {
if (error !== 'cancel') {
UnityUtil.userAlert(error, true, true);
console.error('UnityUtil.onLoading() failed: ', error);
}
});
} else {
UnityUtil.onReady().then(() => {
if (UnityUtil.unityInstance) {
UnityUtil.unityInstance.SendMessage(UnityUtil.UNITY_GAME_OBJECT, methodName, params);
}
}).catch((error) => {
if (error !== 'cancel') {
UnityUtil.userAlert(error, true, true);
console.error('UnityUtil.onReady() failed: ', error);
}
});
}
}
/*
* =============== FROM UNITY ====================
*/
/**
* @hidden
* This function is called to notify the viewer what is the state of the current clipping planes.
* @param clipInfo an object containing an array of clipping plane information
*/
public static clipBroadcast(clipInfo: string) {
if (UnityUtil.viewer && UnityUtil.viewer.clipBroadcast) {
UnityUtil.viewer.clipBroadcast(JSON.parse(clipInfo));
}
}
/** @hidden */
public static clipUpdated(nPlanes) {
if (UnityUtil.viewer && UnityUtil.viewer.numClipPlanesUpdated) {
UnityUtil.viewer.numClipPlanesUpdated(nPlanes);
}
}
/** @hidden */
public static currentPointInfo(pointInfo) {
const point = JSON.parse(pointInfo);
if (UnityUtil.viewer && UnityUtil.viewer.objectSelected) {
UnityUtil.viewer.objectSelected(point);
}
}
/** @hidden */
public static comparatorLoaded() {
UnityUtil.loadComparatorResolve.resolve();
UnityUtil.loadComparatorPromise = null;
UnityUtil.loadComparatorResolve = null;
}
/** @hidden */
public static loaded(bboxStr) {
// eslint-disable-next-line no-console
console.log(`[${new Date()}]Loading model done. `);
const res = {
bbox: JSON.parse(bboxStr),
};
UnityUtil.loadedResolve.resolve(res);
UnityUtil.loadedFlag = true;
}
/** @hidden */
public static loading() {
UnityUtil.loadingResolve.resolve();
}
/** @hidden */
public static loadingProgress(progress) {
if (UnityUtil.modelLoaderProgressCallback) {
UnityUtil.modelLoaderProgressCallback(progress);
}
}
/** @hidden */
public static navMethodChanged(newNavMode) {
if (UnityUtil.viewer && UnityUtil.viewer.navMethodChanged) {
UnityUtil.viewer.navMethodChanged(newNavMode);
}
}
/** @hidden */
public static objectsSelectedAlert(nodeInfo) {
UnityUtil.viewer.objectsSelected(JSON.parse(nodeInfo).nodes);
}
/** @hidden */
public static objectStatusBroadcast(nodeInfo) {
try {
UnityUtil.objectStatusPromises.forEach((promise) => {
promise.resolve(JSON.parse(nodeInfo));
});
} catch (error) {
UnityUtil.objectStatusPromises.forEach((promise) => {
promise.resolve({});
});
}
UnityUtil.objectStatusPromises = [];
}
/** @hidden */
public static ready() {
// Overwrite the Send Message function to make it run quicker
// This shouldn't need to be done in the future when the
// readyoptimisation in added into unity.
UnityUtil.readyResolve.resolve();
}
/** @hidden */
public static pickPointAlert(pointInfo) {
const point = JSON.parse(pointInfo);
if (UnityUtil.viewer && UnityUtil.viewer.pickPointEvent) {
UnityUtil.viewer.pickPointEvent(point);
}
}
/** @hidden */
public static screenshotReady(screenshot) {
try {
const ssJSON = JSON.parse(screenshot);
UnityUtil.screenshotPromises.forEach((promise) => {
promise.resolve(ssJSON.ssBytes);
});
} catch (error) {
UnityUtil.screenshotPromises.forEach((promise) => {
promise.reject(error);
});
}
UnityUtil.screenshotPromises = [];
}
/** @hidden */
public static viewpointReturned(vpInfo) {
try {
const viewpoint = JSON.parse(vpInfo);
UnityUtil.viewpointsPromises.forEach((promise) => {
promise.resolve(viewpoint);
});
} catch (error) {
console.error('Failed to parse viewpoint', vpInfo);
UnityUtil.viewpointsPromises.forEach((promise) => {
promise.resolve({});
});
}
UnityUtil.viewpointsPromises = [];
}
/** @hidden */
public static measurementAlert(strMeasurement) {
try {
const measurement = JSON.parse(strMeasurement);
if (UnityUtil.viewer && UnityUtil.viewer.measurementAlertEvent) {
UnityUtil.viewer.measurementAlertEvent(measurement);
}
} catch (error) {
console.error('Failed to parse measurement alert', strMeasurement);
}
}
/** @hidden */
public static measurementRemoved(measurmentId) {
if (UnityUtil.viewer && UnityUtil.viewer.measurementRemoved) {
UnityUtil.viewer.measurementRemoved(measurmentId);
}
}
/** @hidden */
public static measurementsCleared() {
if (UnityUtil.viewer && UnityUtil.viewer.measurementsCleared) {
UnityUtil.viewer.measurementsCleared();
}
}
/*
* =============== TO UNITY ====================
*/
/**
* Tells the viewer the maximum amount of memory it can expect to be able
* to allocate for its heap. 0 means the maximum amount that the browser
* can handle, determined by hueristics in this method.
*/
public static setUnityMemory(maxMemoryInMb: number) {
// This method is only supported on the 4GB viewer. The previous viewer
// will always use 2GB.
if (!this.usingBetaViewer) {
return;
}
let memory = Number(maxMemoryInMb);
if (memory === 0) {
// If the user has not set the memory explicitly, then attempt to
// determine it automatically
// The new viewer can handle 4GB on most browsers.
memory = 4032;
// Firefox currently has a bug in its WebGL APIs,
// https://bugzilla.mozilla.org/show_bug.cgi?id=1838218
// that causes a crash when the viewer uses more than 2GB. This snippet
// tells the viewer not to attempt to consume more than 2GB, even though
// the heap could grow into it. When Mozilla fixes the bug this can be
// removed, or masked based on the version string.
const match = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
if (match) {
memory = 2032;
}
}
UnityUtil.toUnity('SetUnityMemory', UnityUtil.LoadingState.VIEWER_READY, memory);
}
/**
* Move the pivot point to eh centre of the objects provided
* @category Navigations
* @param meshIDs - array of json objects each recording { model: <account.modelID>, meshID: [array of mesh IDs] }
*/
public static centreToPoint(meshIDs: [object]) {
const params = {
groups: meshIDs,
};
UnityUtil.toUnity('CentreToObject', UnityUtil.LoadingState.MODEL_LOADING, JSON.stringify(params));
}
/**
* Change the colour of an existing pin
* @category Pins
* @param id - ID of the pin
* @param colour - colour RGB value of the colour to change to. e.g. [1, 0, 0]
*/
public static changePinColour(id: string, colour: number[]) {
const params = {
color: colour,
pinName: id,
};
UnityUtil.toUnity('ChangePinColor', UnityUtil.LoadingState.MODEL_LOADING, JSON.stringify(params));
}
/**
* Clear all highlighting on currently highlighted objects
* @category Object Highlighting
*/
public static clearHighlights() {
UnityUtil.toUnity('ClearHighlighting', UnityUtil.LoadingState.MODEL_LOADED, undefined);
}
/**
* When Compare tool is enabled, visalise in differencing view
* Models will be rendered in greyscale, detailing the difference/clash
* @category Compare Tool
*/
public static diffToolDiffView() {
UnityUtil.toUnity('DiffToolShowDiff', undefined, undefined);
}
/**
* Disable compare tool
* This also unloads the comparator models
* @category Compare Tool
*/
public static diffToolDisableAndClear() {
UnityUtil.toUnity('DiffToolDisable', UnityUtil.LoadingState.MODEL_LOADED, undefined);
}
/**
* Enable compare tool
* This starts the compare tool in diff mode
* @category Compare Tool
*/
public static diffToolEnableWithDiffMode() {
UnityUtil.toUnity('DiffToolStartDiffMode', UnityUtil.LoadingState.MODEL_LOADED, undefined);
}
/**
* Enable compare tool
* This starts the compare tool in clash mode
* @category Compare Tool
*/
public static diffToolEnableWithClashMode() {
UnityUtil.toUnity('DiffToolStartClashMode', UnityUtil.LoadingState.MODEL_LOADED, undefined);
}
/**
* Load comparator model for compare tool
* This returns a promise which will be resolved when the comparator model is loaded
* @category Compare Tool
* @param account - teamspace
* @param model - model ID
* @param revision - Specific revision ID/tag to load
* @return returns a promise that resolves upon comparator model finished loading.
*/
public static diffToolLoadComparator(account: string, model: string, revision = 'head'): Promise<void> {
const params: any = {
database: account,
model,
};
if (revision !== 'head') {
params.revID = revision;
}
UnityUtil.toUnity('DiffToolLoadComparator', UnityUtil.LoadingState.MODEL_LOADED, JSON.stringify(params));
if (!UnityUtil.loadComparatorPromise) {
UnityUtil.loadComparatorPromise = new Promise((resolve, reject) => {
UnityUtil.loadComparatorResolve = { resolve, reject };
});
}
return UnityUtil.loadComparatorPromise;
}
/**
* Set an existing submodel/model as a comparator model
* This will return as a base model when you have cleared the comparator (i.e. disabled diff)
* @category Compare Tool
* @param account - name of teamspace
* @param model - model ID
*/
public static diffToolSetAsComparator(account: string, model: string) {
const params: any = {
database: account,
model,
};
UnityUtil.toUnity('DiffToolAssignAsComparator', UnityUtil.LoadingState.MODEL_LOADED, JSON.stringify(params));
}
/**
* Set tolerance threshold.
* In general you should not need to tweak this, but if the differencing looks off, this is the value to tweak
* @category Compare Tool
* @param theshold - tolerance level for diffing/clashing
*/
public static diffToolSetThreshold(theshold: number) {
UnityUtil.toUnity('DiffToolSetThreshold', UnityUtil.LoadingState.MODEL_LOADED, theshold);
}
/**
* Only show the comparator model
* i.e. Only show the model you are trying to compare with, not the base model
* @category Compare Tool
*/
public static diffToolShowComparatorModel() {
UnityUtil.toUnity('DiffToolShowComparatorModel', undefined, undefined);
}
/**
* Only show the base model
* i.e. It will show only the original model, not the comparator nor the diff view
* @category Compare Tool
*/
public static diffToolShowBaseModel() {
UnityUtil.toUnity('DiffToolShowBaseModel', undefined, undefined);
}
/**
* Compare transparent objects as if they are opaque objects
* @category Compare Tool
*/
public static diffToolRenderTransAsOpaque() {
UnityUtil.toUnity('DiffToolRenderTransAsOpaque', undefined, undefined);
}
/**
* Ignore semi-transparent objects in diff
* @category Compare Tool
*/
public static diffToolRenderTransAsInvisible() {
UnityUtil.toUnity('DiffToolRenderTransAsInvisible', undefined, undefined);
}
/**
* Compare transparent objects as of normal
* @category Compare Tool
*/
public static diffToolRenderTransAsDefault() {
UnityUtil.toUnity('DiffToolRenderTransAsDefault', undefined, undefined);
}
/**
* Start clip editing in single plane mode
* @category Clipping Plane
*/
public static startSingleClip() {
UnityUtil.toUnity('StartSingleClip', undefined, undefined);
}
/**
* Start clip editing in box mode
* @category Clipping Plane
*/
public static startBoxClip() {
UnityUtil.toUnity('StartBoxClip', undefined, undefined);
}
/**
* Start editing mode with current clip plane state
* @category Clipping Plane
*/
public static startClipEdit() {
UnityUtil.toUnity('StartClipEdit', undefined, undefined);
}
/**
* Stop editing mode
* @category Clipping Plane
*/
public static stopClipEdit() {
UnityUtil.toUnity('StopClipEdit', undefined, undefined);
}
/**
* Disable the Measuring tool.
* @category Measuring tool
*/
public static disableMeasuringTool() {
UnityUtil.toUnity('StopMeasuringTool', UnityUtil.LoadingState.MODEL_LOADING, undefined);
}
/**
* Enable the measure tool toolbar.
* @category Measuring tool
*/
public static enableMeasureToolToolbar() {
UnityUtil.toUnity('EnableMeasureToolToolbar', undefined, undefined);
}
/**
* Enable the measure tool toolbar.
* @category Measuring tool
*/
public static disableMeasureToolToolbar() {
UnityUtil.toUnity('DisableMeasureToolToolbar', undefined, undefined);
}
/**
* Set the measure tool mode.
* @category Measuring tool
* @param mode - The measuring mode, accepted values are "Point", "Raycast", "MinimumDistance",
* "SurfaceArea" or "PolygonArea".
*/
public static setMeasureToolMode(mode) {
UnityUtil.toUnity('SetMeasureToolMode', undefined, mode);
}
/**
* Set the measure tool units.
* @category Measuring tool
* @param units - The measuring units accepted values are "cm", "mm", "m"
*/
public static setMeasureToolUnits(units) {
UnityUtil.toUnity('SetMeasureToolUnits', undefined, units);
}
/**
* Enable snapping to snap the cursor to the closest edge
* @category Configurations
*/
public static enableSnapping() {
UnityUtil.toUnity('EnableSnapping', undefined, undefined);
}
/**
* Disable Snapping
* @category Configurations
*/
public static disableSnapping() {
UnityUtil.toUnity('DisableSnapping', undefined, undefined);
}
/**
* Clear all measurements
* @category Measuring tool
*/
public static clearAllMeasurements() {
UnityUtil.toUnity('ClearMeasureToolMeasurements', undefined, undefined);
}
/**
* Remove a particular measurement.
* @param uuid - The measurement id of the measurement to be removed
*/
public static clearMeasureToolMeasurement(uuid) {
UnityUtil.toUnity('ClearMeasureToolMeasurement', undefined, uuid);
}
/**
* Set color of a particular measurement.
* @param uuid - The measurement id of the measurement that will change color
*/
public static setMeasureToolMeasurementColor(uuid, color) {
UnityUtil.toUnity('SetMeasureToolMeasurementColor', undefined, JSON.stringify({ uuid, color }));
}
/**
* Set color of a particular measurement.
* @param uuid - The measurement id of the measurement that will change name
*/
public static setMeasureToolMeasurementName(uuid, name) {
UnityUtil.toUnity('SetMeasureToolMeasurementName', undefined, JSON.stringify({ uuid, name }));
}
/**
* Enable measure display mode to xyz.
* @category Measuring tool
*/
public static enableMeasureToolXYZDisplay() {
UnityUtil.toUnity('EnableMeasureToolXYZDisplay');
}
/**
* Disnable measure display mode to xyz.
* @category Measuring tool
*/
public static disableMeasureToolXYZDisplay() {
UnityUtil.toUnity('DisableMeasureToolXYZDisplay');
}
public static addMeasurement(measurement) {
UnityUtil.toUnity('AddMeasurement', UnityUtil.LoadingState.MODEL_LOADING, JSON.stringify(measurement));
}
public static hideNewMeasurementsLabels() {
UnityUtil.toUnity('HideNewMeasurementsLabels');
}
public static showNewMeasurementsLabels() {
UnityUtil.toUnity('ShowNewMeasurementsLabels');
}
public static selectMeasurement(id: string) {
UnityUtil.toUnity('SelectMeasurement', UnityUtil.LoadingState.MODEL_LOADING, id);
}
public static deselectMeasurement(id: string) {
UnityUtil.toUnity('DeselectMeasurement', UnityUtil.LoadingState.MODEL_LOADING, id);
}
public static setStreamingModelPriority(modelNamespace: string, priority: number) {