-
Notifications
You must be signed in to change notification settings - Fork 3
/
MultipleModelUtil.js
335 lines (283 loc) · 12.7 KB
/
MultipleModelUtil.js
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
//
// Copyright (c) Autodesk, Inc. All rights reserved
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Utility Class for loading models in sequence for Forge Viewer
// by Eason Kang - Autodesk Forge Partner Development (FPD)
//
(function (parent) {
const MultipleModelAlignmentType = {
CenterToCenter: 1,
OriginToOrigin: 2,
ShareCoordinates: 3,
Custom: 4
};
const AGGREGATE_GEOMETRY_LOADED_EVENT = 'aggregateGeometryLoaded';
const AGGREGATE_PROGRESS_CHANGED_EVENT = 'aggregateProgressChanged';
class MultipleModelUtil {
/**
* @type {Viewer3D} The Forge Viewer instance
* @private
*/
#viewer = null;
/**
* @type {Object} options The alignment setup
* @private
*/
#options = null;
/**
* @param {Viewer3D} viewer The Forge Viewer instance
* @param {Object} options The alignment setup
* @param {MultipleModelAlignmentType} [options.alignment] The alignment type: CenterToCenter, OriginToOrigin, ShareCoordinates, or Custom
* @param {function} [options.getCustomLoadOptions] Allows for applying custom options to be used for all model loading. The callback returns an options object that is applied by default in all model-load calls. The signature should look like: function(bubble, data) => Object
* @param {string} [options.viewerUnits] - If specified, all models are re-scaled from model units to this unit. Must be a GNU unit format string, e.g. "m".
* @constructor
*/
constructor(viewer, options) {
this.#viewer = viewer;
options = options || { alignment: MultipleModelAlignmentType.OriginToOrigin };
this.#validateOptions(options);
this.#options = options;
}
/**
* Check if input is valid
* @param {Object} opts The alignment setup
* @property {MultipleModelAlignmentType} [options.alignment] The alignment type: CenterToCenter, OriginToOrigin, ShareCoordinates, or Custom
* @property {function} [options.getCustomLoadOptions] Allows for applying custom options to be used for all model loading. The callback returns an options object that is applied by default in all model-load calls. The signature should look like: function(bubble, data) => Object
* @property {string} [options.viewerUnits] - If specified, all models are re-scale
* @returns {bool} False if the input options is invalid
* @private
*/
#isValidOptions(opts) {
if (!opts || !opts.alignment || !Object.values(MultipleModelAlignmentType).includes(opts.alignment)) return false;
if (opts.alignment === MultipleModelAlignmentType.Custom) {
if (!(opts.getCustomLoadOptions instanceof Function)) {
return false;
}
}
return true;
}
/**
* Check if input is valid
* @param {Object} opts The alignment setup
* @property {MultipleModelAlignmentType} [options.alignment] The alignment type: CenterToCenter, OriginToOrigin, ShareCoordinates, or Custom
* @property {function} [options.getCustomLoadOptions] Allows for applying custom options to be used for all model loading. The callback returns an options object that is applied by default in all model-load calls. The signature should look like: function(bubble, data) => Object
* @property {string} [options.viewerUnits] - If specified, all models are re-scale
* @throws Will throw an error if input is invalid
* @private
*/
#validateOptions(opts) {
if (!this.#isValidOptions(opts))
throw new Error(`[MultipleModelUtil]: Invalid options or invalid \`options.getCustomLoadOptions\` while using \`MultipleModelAlignmentType.Custom\``);
}
/**
* @type {Object} options The alignment setup
* @property {MultipleModelAlignmentType} [options.alignment] The alignment type: CenterToCenter, OriginToOrigin, ShareCoordinates, or Custom
* @property {function} [options.getCustomLoadOptions] Allows for applying custom options to be used for all model loading. The callback returns an options object that is applied by default in all model-load calls. The signature should look like: function(bubble, data) => Object
* @property {string} [options.viewerUnits] - If specified, all models are re-scale
*/
get options() {
return this.#options;
}
/**
* @param {Object} opts The alignment setup
* @property {MultipleModelAlignmentType} [options.alignment] The alignment type: CenterToCenter, OriginToOrigin, ShareCoordinates, or Custom
* @property {function} [options.getCustomLoadOptions] Allows for applying custom options to be used for all model loading. The callback returns an options object that is applied by default in all model-load calls. The signature should look like: function(bubble, data) => Object
* @property {string} [options.viewerUnits] - If specified, all models are re-scale
*/
set options(opts) {
this.#validateOptions(opts);
this.#options = opts;
}
/**
* Process Forge URNs
* @param {Object[]} data Model data to be loaded, e.g. [ { name: 'house.rvt', urn: 'dXJuOmFkc2sub2JqZWN0c....' } ]
* @returns {Promise}
*/
async processModels(data) {
//process each promise
//refer to http://jsfiddle.net/jfriend00/h3zaw8u8/
const promisesInSequence = (tasks, callback) => {
const results = [];
return tasks.reduce((p, item) => {
return p.then(() => {
return callback(item).then((data) => {
results.push(data);
return results;
});
});
}, Promise.resolve());
};
for (const d of data) {
d.percent = 0;
}
const progressUpdated = (event) => {
let modelDataIndex = data.findIndex(d => d.urn.includes(event.model.getData().urn));
if (modelDataIndex == -1) return;
if (event.state !== Autodesk.Viewing.ProgressState.LOADING) return;
if (data[modelDataIndex].percent >= 100) return;
data[modelDataIndex].percent = event.percent;
let rawPercents = data.map(d => d.percent)
let sumPercent = rawPercents.reduce((a, b) => a + b, 0);
let overallPercent = sumPercent / data.length;
//console.log('Debug Progress', event.model.getData().urn, event.percent, data.map(d => d.percent));
this.#viewer.fireEvent({
type: AGGREGATE_PROGRESS_CHANGED_EVENT,
percent: overallPercent,
rawPercents
});
if (overallPercent >= 100)
this.#viewer.removeEventListener(
Autodesk.Viewing.PROGRESS_UPDATE_EVENT,
progressUpdated
);
};
this.#viewer.addEventListener(
Autodesk.Viewing.PROGRESS_UPDATE_EVENT,
progressUpdated
);
//start to process
const results = await promisesInSequence(data, (d) => this.loadDocumentPromised(d));
this.#viewer.fireEvent({
type: AGGREGATE_GEOMETRY_LOADED_EVENT,
models: results
});
}
/**
* Promised function for loading Forge derivative manifest
* @param {Object} data Model data to be loaded, e.g. { name: 'house.rvt', urn: 'dXJuOmFkc2sub2JqZWN0c....' }
* @returns {Promise} Loaded viewer model
*/
loadDocumentPromised(data) {
return new Promise((resolve, reject) => {
const onDocumentLoadSuccess = (doc) => {
console.log(`%cDocument for \`${data.name}\` Load Succeeded!`, 'color: blue');
doc.downloadAecModelData(() => {
// Load model
this.loadModelPromised(
data,
doc,
onLoadModelSuccess,
onLoadModelError
);
});
}
const onDocumentLoadFailure = (error) => {
console.error(`Document for \`${data.name}\` Load Failure, error: \`${error}\``);
}
const onLoadModelSuccess = (model) => {
console.log(`%cModel for \`${data.name}\` Load Succeeded!`, 'color: blue');
this.#viewer.addEventListener(
Autodesk.Viewing.GEOMETRY_LOADED_EVENT,
onGeometriesLoaded
);
}
const onLoadModelError = (error) => {
const msg = `Model for \`${data.name}\` Load Failure, error: \`${error}\``;
console.error(msg);
reject(msg);
}
const onGeometriesLoaded = (event) => {
this.#viewer.removeEventListener(
Autodesk.Viewing.GEOMETRY_LOADED_EVENT,
onGeometriesLoaded
);
const msg = `Geometries for \`${data.name}\` Loaded`;
console.log(`%c${msg}`, 'color: blue');
resolve({ name: data.name, model: event.model });
}
// Main: Load Forge derivative manifest
Autodesk.Viewing.Document.load(
data.urn,
onDocumentLoadSuccess,
onDocumentLoadFailure
);
});
}
/**
* Promised function for loading model from the Forge derivative manifest.
* By default, it loads the first model only.
* @param {Document} doc Forge derivative manifest representing the model document
* @param {Function} onLoadModelSuccess Success callback function that will be called while the model was loaded by the Forge Viewer.
* @param {Function} onLoadModelError Error callback function that will be called while loading model was failed.
*/
loadModelPromised(data, doc, onLoadModelSuccess, onLoadModelError) {
let { viewRole, viewGuid, viewerUnits, useMasterView, name } = data;
let bubble = null;
const rootItem = doc.getRoot();
const viewer = this.#viewer;
if (useMasterView) {
bubble = rootItem.getDefaultGeometry(true);
} else {
viewRole = viewRole || '3d';
const filter = { type: 'geometry', role: viewRole };
if (viewGuid)
filter.viewableID = viewGuid;
const viewables = rootItem.search(filter);
if (viewables.length === 0) {
return onLoadModelError('Document contains no viewables.');
}
// Take the first viewable out as the loading target
bubble = viewables[0];
}
let loadOptions = {
modelNameOverride: name,
applyScaling: viewerUnits
};
let globalOffset = null;
switch (this.#options.alignment) {
case MultipleModelAlignmentType.ShareCoordinates:
globalOffset = viewer.model?.getData().globalOffset;
const aecModelData = bubble.getAecModelData();
if (aecModelData) {
let tf = aecModelData && aecModelData.refPointTransformation;
let refPoint = tf ? { x: tf[9], y: tf[10], z: 0.0 } : { x: 0, y: 0, z: 0 };
const MaxDistSqr = 4.0e6;
const distSqr = globalOffset && THREE.Vector3.prototype.distanceToSquared.call(refPoint, globalOffset);
if (!globalOffset || distSqr > MaxDistSqr) {
globalOffset = new THREE.Vector3().copy(refPoint);
}
}
loadOptions.applyRefPoint = true;
loadOptions.globalOffset = globalOffset;
break;
case MultipleModelAlignmentType.OriginToOrigin:
globalOffset = viewer.model?.getData().globalOffset;
loadOptions.globalOffset = globalOffset;
break;
case MultipleModelAlignmentType.Custom:
loadOptions = Object.assign({}, loadOptions, this.options.getCustomLoadOptions(bubble, data));
break;
}
// If no model was loaded, start the viewer and load model together
if (!viewer.model && !viewer.started) {
return viewer.startWithDocumentNode(doc, bubble, loadOptions)
.then(onLoadModelSuccess)
.catch(onLoadModelError);
}
if (viewer.model) {
loadOptions.keepCurrentModels = true;
}
viewer.loadDocumentNode(doc, bubble, loadOptions)
.then(onLoadModelSuccess)
.catch(onLoadModelError);
}
}
MultipleModelUtil.AGGREGATE_GEOMETRY_LOADED_EVENT = AGGREGATE_GEOMETRY_LOADED_EVENT;
MultipleModelUtil.AGGREGATE_PROGRESS_CHANGED_EVENT = AGGREGATE_PROGRESS_CHANGED_EVENT;
//Expose to global
parent.MultipleModelAlignmentType = MultipleModelAlignmentType;
parent.MultipleModelUtil = MultipleModelUtil;
})(window);