viewer.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. import { viewerManager } from './viewerManager';
  2. import { TemplateManager } from './../templateManager';
  3. import configurationLoader from './../configuration/loader';
  4. import { CubeTexture, Color3, IEnvironmentHelperOptions, EnvironmentHelper, Effect, SceneOptimizer, SceneOptimizerOptions, Observable, Engine, Scene, ArcRotateCamera, Vector3, SceneLoader, AbstractMesh, Mesh, HemisphericLight, Database, SceneLoaderProgressEvent, ISceneLoaderPlugin, ISceneLoaderPluginAsync, Quaternion, Light, ShadowLight, ShadowGenerator, Tags, AutoRotationBehavior, BouncingBehavior, FramingBehavior, Behavior } from 'babylonjs';
  5. import { ViewerConfiguration, ISceneConfiguration, ISceneOptimizerConfiguration, IObserversConfiguration, IModelConfiguration, ISkyboxConfiguration, IGroundConfiguration, ILightConfiguration, ICameraConfiguration } from '../configuration/configuration';
  6. import * as deepmerge from '../../assets/deepmerge.min.js';
  7. import { CameraBehavior } from 'src/interfaces';
  8. export abstract class AbstractViewer {
  9. public templateManager: TemplateManager;
  10. public engine: Engine;
  11. public scene: Scene;
  12. public camera: ArcRotateCamera;
  13. public sceneOptimizer: SceneOptimizer;
  14. public baseId: string;
  15. /**
  16. * The last loader used to load a model.
  17. *
  18. * @type {(ISceneLoaderPlugin | ISceneLoaderPluginAsync)}
  19. * @memberof AbstractViewer
  20. */
  21. public lastUsedLoader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  22. protected configuration: ViewerConfiguration;
  23. public environmentHelper: EnvironmentHelper;
  24. protected defaultHighpTextureType: number;
  25. protected shadowGeneratorBias: number;
  26. protected defaultPipelineTextureType: number;
  27. protected maxShadows: number;
  28. private _hdrSupport: boolean;
  29. public get isHdrSupported() {
  30. return this._hdrSupport;
  31. }
  32. // observables
  33. public onSceneInitObservable: Observable<Scene>;
  34. public onEngineInitObservable: Observable<Engine>;
  35. public onModelLoadedObservable: Observable<AbstractMesh[]>;
  36. public onModelLoadProgressObservable: Observable<SceneLoaderProgressEvent>;
  37. public onModelLoadErrorObservable: Observable<{ message: string; exception: any }>;
  38. public onLoaderInitObservable: Observable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>;
  39. public onInitDoneObservable: Observable<AbstractViewer>;
  40. public canvas: HTMLCanvasElement;
  41. protected registeredOnBeforerenderFunctions: Array<() => void>;
  42. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = {}) {
  43. // if exists, use the container id. otherwise, generate a random string.
  44. if (containerElement.id) {
  45. this.baseId = containerElement.id;
  46. } else {
  47. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  48. }
  49. this.onSceneInitObservable = new Observable();
  50. this.onEngineInitObservable = new Observable();
  51. this.onModelLoadedObservable = new Observable();
  52. this.onModelLoadProgressObservable = new Observable();
  53. this.onModelLoadErrorObservable = new Observable();
  54. this.onInitDoneObservable = new Observable();
  55. this.onLoaderInitObservable = new Observable();
  56. this.registeredOnBeforerenderFunctions = [];
  57. // add this viewer to the viewer manager
  58. viewerManager.addViewer(this);
  59. // create a new template manager. TODO - singleton?
  60. this.templateManager = new TemplateManager(containerElement);
  61. this.prepareContainerElement();
  62. // extend the configuration
  63. configurationLoader.loadConfiguration(initialConfiguration, (configuration) => {
  64. this.configuration = deepmerge(this.configuration || {}, configuration);
  65. if (this.configuration.observers) {
  66. this.configureObservers(this.configuration.observers);
  67. }
  68. //this.updateConfiguration(configuration);
  69. // initialize the templates
  70. let templateConfiguration = this.configuration.templates || {};
  71. this.templateManager.initTemplate(templateConfiguration);
  72. // when done, execute onTemplatesLoaded()
  73. this.templateManager.onAllLoaded.add(() => {
  74. let canvas = this.templateManager.getCanvas();
  75. if (canvas) {
  76. this.canvas = canvas;
  77. }
  78. this._onTemplateLoaded();
  79. });
  80. });
  81. //this.onModelLoadedObservable.add(this.initEnvironment.bind(this));
  82. }
  83. public getBaseId(): string {
  84. return this.baseId;
  85. }
  86. public isCanvasInDOM(): boolean {
  87. return !!this.canvas && !!this.canvas.parentElement;
  88. }
  89. protected resize = (): void => {
  90. // Only resize if Canvas is in the DOM
  91. if (!this.isCanvasInDOM()) {
  92. return;
  93. }
  94. if (this.canvas.clientWidth <= 0 || this.canvas.clientHeight <= 0) {
  95. return;
  96. }
  97. this.engine.resize();
  98. }
  99. protected render = (): void => {
  100. this.scene && this.scene.activeCamera && this.scene.render();
  101. }
  102. /**
  103. * Update the current viewer configuration with new values.
  104. * Only provided information will be updated, old configuration values will be kept.
  105. * If this.configuration was manually changed, you can trigger this function with no parameters,
  106. * and the entire configuration will be updated.
  107. * @param newConfiguration
  108. */
  109. public updateConfiguration(newConfiguration: Partial<ViewerConfiguration> = this.configuration) {
  110. // update this.configuration with the new data
  111. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  112. // update scene configuration
  113. if (newConfiguration.scene) {
  114. this.configureScene(newConfiguration.scene);
  115. }
  116. // optimizer
  117. if (newConfiguration.optimizer) {
  118. this.configureOptimizer(newConfiguration.optimizer);
  119. }
  120. // observers in configuration
  121. if (newConfiguration.observers) {
  122. this.configureObservers(newConfiguration.observers);
  123. }
  124. // configure model
  125. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  126. this.configureModel(newConfiguration.model);
  127. }
  128. // lights
  129. if (newConfiguration.lights) {
  130. this.configureLights(newConfiguration.lights);
  131. }
  132. // environment
  133. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  134. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  135. }
  136. // camera
  137. if (newConfiguration.camera) {
  138. this.configureCamera(newConfiguration.camera);
  139. }
  140. }
  141. protected configureEnvironment(skyboxConifguration?: ISkyboxConfiguration | boolean, groundConfiguration?: IGroundConfiguration | boolean) {
  142. if (!skyboxConifguration && !groundConfiguration) {
  143. if (this.environmentHelper) {
  144. this.environmentHelper.dispose();
  145. delete this.environmentHelper;
  146. };
  147. return Promise.resolve(this.scene);
  148. }
  149. const options: Partial<IEnvironmentHelperOptions> = {
  150. createGround: !!groundConfiguration,
  151. createSkybox: !!skyboxConifguration,
  152. setupImageProcessing: false // will be done at the scene level!
  153. };
  154. if (groundConfiguration) {
  155. let groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  156. let groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  157. if (groundSize) {
  158. options.groundSize = groundSize;
  159. }
  160. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  161. if (groundConfig.shadowLevel !== undefined) {
  162. options.groundShadowLevel = groundConfig.shadowLevel;
  163. }
  164. options.enableGroundMirror = !!groundConfig.mirror;
  165. if (groundConfig.texture) {
  166. options.groundTexture = groundConfig.texture;
  167. }
  168. if (groundConfig.color) {
  169. options.groundColor = new Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b)
  170. }
  171. if (groundConfig.opacity !== undefined) {
  172. options.groundOpacity = groundConfig.opacity;
  173. }
  174. if (groundConfig.mirror) {
  175. options.enableGroundMirror = true;
  176. // to prevent undefines
  177. if (typeof groundConfig.mirror === "object") {
  178. if (groundConfig.mirror.amount !== undefined)
  179. options.groundMirrorAmount = groundConfig.mirror.amount;
  180. if (groundConfig.mirror.sizeRatio !== undefined)
  181. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  182. if (groundConfig.mirror.blurKernel !== undefined)
  183. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  184. if (groundConfig.mirror.fresnelWeight !== undefined)
  185. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  186. if (groundConfig.mirror.fallOffDistance !== undefined)
  187. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  188. if (this.defaultPipelineTextureType !== undefined)
  189. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  190. }
  191. }
  192. }
  193. let postInitSkyboxMaterial = false;
  194. if (skyboxConifguration) {
  195. let conf = skyboxConifguration === true ? {} : skyboxConifguration;
  196. if (conf.material && conf.material.imageProcessingConfiguration) {
  197. options.setupImageProcessing = false; // will be configured later manually.
  198. }
  199. let skyboxSize = conf.scale;
  200. if (skyboxSize) {
  201. options.skyboxSize = skyboxSize;
  202. }
  203. options.sizeAuto = !options.skyboxSize;
  204. if (conf.color) {
  205. options.skyboxColor = new Color3(conf.color.r, conf.color.g, conf.color.b)
  206. }
  207. if (conf.cubeTexture && conf.cubeTexture.url) {
  208. if (typeof conf.cubeTexture.url === "string") {
  209. options.skyboxTexture = conf.cubeTexture.url;
  210. } else {
  211. // init later!
  212. postInitSkyboxMaterial = true;
  213. }
  214. }
  215. if (conf.material && conf.material.imageProcessingConfiguration) {
  216. postInitSkyboxMaterial = true;
  217. }
  218. }
  219. options.setupImageProcessing = false; // TMP
  220. if (!this.environmentHelper) {
  221. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  222. } else {
  223. // there might be a new scene! we need to dispose.
  224. // get the scene used by the envHelper
  225. let scene: Scene = this.environmentHelper.rootMesh.getScene();
  226. // is it a different scene? Oh no!
  227. if (scene !== this.scene) {
  228. this.environmentHelper.dispose();
  229. this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  230. } else {
  231. this.environmentHelper.updateOptions(options)!;
  232. }
  233. }
  234. if (postInitSkyboxMaterial) {
  235. let skyboxMaterial = this.environmentHelper.skyboxMaterial;
  236. if (skyboxMaterial) {
  237. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  238. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  239. }
  240. }
  241. }
  242. }
  243. protected configureScene(sceneConfig: ISceneConfiguration, optimizerConfig?: ISceneOptimizerConfiguration) {
  244. // sanity check!
  245. if (!this.scene) {
  246. return;
  247. }
  248. if (sceneConfig.debug) {
  249. this.scene.debugLayer.show();
  250. } else {
  251. if (this.scene.debugLayer.isVisible()) {
  252. this.scene.debugLayer.hide();
  253. }
  254. }
  255. if (sceneConfig.clearColor) {
  256. let cc = sceneConfig.clearColor;
  257. let oldcc = this.scene.clearColor;
  258. if (cc.r !== undefined) {
  259. oldcc.r = cc.r;
  260. }
  261. if (cc.g !== undefined) {
  262. oldcc.g = cc.g
  263. }
  264. if (cc.b !== undefined) {
  265. oldcc.b = cc.b
  266. }
  267. if (cc.a !== undefined) {
  268. oldcc.a = cc.a
  269. }
  270. }
  271. // image processing configuration - optional.
  272. if (sceneConfig.imageProcessingConfiguration) {
  273. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  274. }
  275. if (sceneConfig.environmentTexture) {
  276. if (this.scene.environmentTexture) {
  277. this.scene.environmentTexture.dispose();
  278. }
  279. const environmentTexture = CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  280. this.scene.environmentTexture = environmentTexture;
  281. }
  282. if (sceneConfig.autoRotate) {
  283. this.camera.useAutoRotationBehavior = true;
  284. }
  285. }
  286. protected configureOptimizer(optimizerConfig: ISceneOptimizerConfiguration | boolean) {
  287. if (typeof optimizerConfig === 'boolean') {
  288. if (this.sceneOptimizer) {
  289. this.sceneOptimizer.stop();
  290. this.sceneOptimizer.dispose();
  291. delete this.sceneOptimizer;
  292. }
  293. if (optimizerConfig) {
  294. this.sceneOptimizer = new SceneOptimizer(this.scene);
  295. this.sceneOptimizer.start();
  296. }
  297. } else {
  298. let optimizerOptions: SceneOptimizerOptions = new SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  299. // check for degradation
  300. if (optimizerConfig.degradation) {
  301. switch (optimizerConfig.degradation) {
  302. case "low":
  303. optimizerOptions = SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  304. break;
  305. case "moderate":
  306. optimizerOptions = SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  307. break;
  308. case "hight":
  309. optimizerOptions = SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  310. break;
  311. }
  312. }
  313. if (this.sceneOptimizer) {
  314. this.sceneOptimizer.stop();
  315. this.sceneOptimizer.dispose()
  316. }
  317. this.sceneOptimizer = new SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  318. this.sceneOptimizer.start();
  319. }
  320. }
  321. protected configureObservers(observersConfiguration: IObserversConfiguration) {
  322. if (observersConfiguration.onEngineInit) {
  323. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  324. } else {
  325. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers!.onEngineInit) {
  326. this.onEngineInitObservable.removeCallback(window[this.configuration.observers!.onEngineInit!]);
  327. }
  328. }
  329. if (observersConfiguration.onSceneInit) {
  330. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  331. } else {
  332. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers!.onSceneInit) {
  333. this.onSceneInitObservable.removeCallback(window[this.configuration.observers!.onSceneInit!]);
  334. }
  335. }
  336. if (observersConfiguration.onModelLoaded) {
  337. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  338. } else {
  339. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers!.onModelLoaded) {
  340. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers!.onModelLoaded!]);
  341. }
  342. }
  343. }
  344. protected configureCamera(cameraConfig: ICameraConfiguration, focusMeshes: Array<AbstractMesh> = this.scene.meshes) {
  345. if (!this.scene.activeCamera) {
  346. this.scene.createDefaultCamera(true, true, true);
  347. this.camera = <ArcRotateCamera>this.scene.activeCamera!;
  348. }
  349. if (cameraConfig.position) {
  350. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  351. }
  352. if (cameraConfig.rotation) {
  353. this.camera.rotationQuaternion = new Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0)
  354. }
  355. this.extendClassWithConfig(this.camera, cameraConfig);
  356. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  357. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  358. if (cameraConfig.behaviors) {
  359. for (let name in cameraConfig.behaviors) {
  360. this.setCameraBehavior(cameraConfig.behaviors[name], focusMeshes);
  361. }
  362. };
  363. const sceneExtends = this.scene.getWorldExtends((mesh) => {
  364. return !this.environmentHelper || (mesh !== this.environmentHelper.ground && mesh !== this.environmentHelper.rootMesh && mesh !== this.environmentHelper.skybox);
  365. });
  366. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  367. const sceneDiagonalLenght = sceneDiagonal.length();
  368. if (isFinite(sceneDiagonalLenght))
  369. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  370. }
  371. protected configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, focusMeshes: Array<AbstractMesh> = this.scene.meshes) {
  372. // sanity check!
  373. if (!Object.keys(lightsConfiguration).length) return;
  374. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  375. // compare to the global (!) configuration object and dispose unneeded:
  376. let lightsToConfigure = Object.keys(this.configuration.lights || []);
  377. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  378. lightsAvailable.forEach(lName => {
  379. if (lightsToConfigure.indexOf(lName) === -1) {
  380. this.scene.getLightByName(lName)!.dispose()
  381. }
  382. });
  383. }
  384. Object.keys(lightsConfiguration).forEach((name, idx) => {
  385. let lightConfig: ILightConfiguration = { type: 0 };
  386. if (typeof lightsConfiguration[name] === 'object') {
  387. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  388. }
  389. lightConfig.name = name;
  390. let light: Light;
  391. // light is not already available
  392. if (lightsAvailable.indexOf(name) === -1) {
  393. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  394. if (!constructor) return;
  395. light = constructor();
  396. } else {
  397. // available? get it from the scene
  398. light = <Light>this.scene.getLightByName(name);
  399. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  400. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  401. light.dispose();
  402. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  403. if (!constructor) return;
  404. light = constructor();
  405. }
  406. }
  407. // if config set the light to false, dispose it.
  408. if (lightsConfiguration[name] === false) {
  409. light.dispose();
  410. return;
  411. }
  412. //enabled
  413. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  414. light.setEnabled(enabled);
  415. this.extendClassWithConfig(light, lightConfig);
  416. //position. Some lights don't support shadows
  417. if (light instanceof ShadowLight) {
  418. if (lightConfig.target) {
  419. if (light.setDirectionToTarget) {
  420. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  421. light.setDirectionToTarget(target);
  422. }
  423. } else if (lightConfig.direction) {
  424. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  425. light.direction = direction;
  426. }
  427. let shadowGenerator = light.getShadowGenerator();
  428. if (lightConfig.shadowEnabled && this.maxShadows) {
  429. if (!shadowGenerator) {
  430. shadowGenerator = new ShadowGenerator(512, light);
  431. // TODO blur kernel definition
  432. }
  433. this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  434. // add the focues meshes to the shadow list
  435. let shadownMap = shadowGenerator.getShadowMap();
  436. if (!shadownMap) return;
  437. let renderList = shadownMap.renderList;
  438. for (var index = 0; index < focusMeshes.length; index++) {
  439. if (Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  440. renderList && renderList.push(focusMeshes[index]);
  441. }
  442. }
  443. } else if (shadowGenerator) {
  444. shadowGenerator.dispose();
  445. }
  446. }
  447. });
  448. // remove the unneeded lights
  449. /*lightsAvailable.forEach(name => {
  450. let light = this.scene.getLightByName(name);
  451. if (light && !Tags.MatchesQuery(light, "fixed")) {
  452. light.dispose();
  453. }
  454. });*/
  455. }
  456. protected configureModel(modelConfiguration: Partial<IModelConfiguration>, focusMeshes: Array<AbstractMesh> = this.scene.meshes) {
  457. let meshesWithNoParent: Array<AbstractMesh> = focusMeshes.filter(m => !m.parent);
  458. let updateMeshesWithNoParent = (variable: string, value: any, param?: string) => {
  459. meshesWithNoParent.forEach(mesh => {
  460. if (param) {
  461. mesh[variable][param] = value;
  462. } else {
  463. mesh[variable] = value;
  464. }
  465. });
  466. }
  467. let updateXYZ = (variable: string, configValues: { x: number, y: number, z: number, w?: number }) => {
  468. if (configValues.x !== undefined) {
  469. updateMeshesWithNoParent(variable, configValues.x, 'x');
  470. }
  471. if (configValues.y !== undefined) {
  472. updateMeshesWithNoParent(variable, configValues.y, 'y');
  473. }
  474. if (configValues.z !== undefined) {
  475. updateMeshesWithNoParent(variable, configValues.z, 'z');
  476. }
  477. if (configValues.w !== undefined) {
  478. updateMeshesWithNoParent(variable, configValues.w, 'w');
  479. }
  480. }
  481. // position?
  482. if (modelConfiguration.position) {
  483. updateXYZ('position', modelConfiguration.position);
  484. }
  485. if (modelConfiguration.rotation) {
  486. if (modelConfiguration.rotation.w) {
  487. meshesWithNoParent.forEach(mesh => {
  488. if (!mesh.rotationQuaternion) {
  489. mesh.rotationQuaternion = new Quaternion();
  490. }
  491. })
  492. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  493. } else {
  494. updateXYZ('rotation', modelConfiguration.rotation);
  495. }
  496. }
  497. if (modelConfiguration.scaling) {
  498. updateXYZ('scaling', modelConfiguration.scaling);
  499. }
  500. if (modelConfiguration.castShadow) {
  501. focusMeshes.forEach(mesh => {
  502. Tags.AddTagsTo(mesh, 'castShadow');
  503. });
  504. }
  505. if (modelConfiguration.normalize) {
  506. let center = false;
  507. let unitSize = false;
  508. let parentIndex;
  509. if (modelConfiguration.normalize === true) {
  510. center = true;
  511. unitSize = true;
  512. parentIndex = 0;
  513. } else {
  514. center = !!modelConfiguration.normalize.center;
  515. unitSize = !!modelConfiguration.normalize.unitSize;
  516. parentIndex = modelConfiguration.normalize.parentIndex;
  517. }
  518. let meshesToNormalize: Array<AbstractMesh> = [];
  519. if (parentIndex !== undefined) {
  520. meshesToNormalize.push(focusMeshes[parentIndex]);
  521. } else {
  522. meshesToNormalize = meshesWithNoParent;
  523. }
  524. if (unitSize) {
  525. meshesToNormalize.forEach(mesh => {
  526. mesh.normalizeToUnitCube(true);
  527. mesh.computeWorldMatrix(true);
  528. });
  529. }
  530. if (center) {
  531. meshesToNormalize.forEach(mesh => {
  532. const boundingInfo = mesh.getHierarchyBoundingVectors(true);
  533. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  534. const halfSizeVec = sizeVec.scale(0.5);
  535. const center = boundingInfo.min.add(halfSizeVec);
  536. mesh.position = center.scale(-1);
  537. // Set on ground.
  538. mesh.position.y += halfSizeVec.y;
  539. // Recompute Info.
  540. mesh.computeWorldMatrix(true);
  541. });
  542. }
  543. }
  544. }
  545. public dispose() {
  546. window.removeEventListener('resize', this.resize);
  547. if (this.sceneOptimizer) {
  548. this.sceneOptimizer.stop();
  549. this.sceneOptimizer.dispose();
  550. }
  551. if (this.scene.activeCamera) {
  552. this.scene.activeCamera.detachControl(this.canvas);
  553. }
  554. this.scene.dispose();
  555. this.engine.dispose();
  556. this.templateManager.dispose();
  557. }
  558. protected abstract prepareContainerElement();
  559. /**
  560. * This function will execute when the HTML templates finished initializing.
  561. * It should initialize the engine and continue execution.
  562. *
  563. * @protected
  564. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  565. * @memberof AbstractViewer
  566. */
  567. protected onTemplatesLoaded(): Promise<AbstractViewer> {
  568. return Promise.resolve(this);
  569. }
  570. /**
  571. * This will force the creation of an engine and a scene.
  572. * It will also load a model if preconfigured.
  573. * But first - it will load the extendible onTemplateLoaded()!
  574. */
  575. private _onTemplateLoaded(): Promise<AbstractViewer> {
  576. return this.onTemplatesLoaded().then(() => {
  577. let autoLoadModel = !!this.configuration.model;
  578. return this.initEngine().then((engine) => {
  579. return this.onEngineInitObservable.notifyObserversWithPromise(engine);
  580. }).then(() => {
  581. if (autoLoadModel) {
  582. return this.loadModel();
  583. } else {
  584. return this.scene || this.initScene();
  585. }
  586. }).then((scene) => {
  587. return this.onSceneInitObservable.notifyObserversWithPromise(scene);
  588. }).then(() => {
  589. return this.onInitDoneObservable.notifyObserversWithPromise(this);
  590. }).then(() => {
  591. return this;
  592. });
  593. })
  594. }
  595. /**
  596. * Initialize the engine. Retruns a promise in case async calls are needed.
  597. *
  598. * @protected
  599. * @returns {Promise<Engine>}
  600. * @memberof Viewer
  601. */
  602. protected initEngine(): Promise<Engine> {
  603. // init custom shaders
  604. this.injectCustomShaders();
  605. let canvasElement = this.templateManager.getCanvas();
  606. if (!canvasElement) {
  607. return Promise.reject('Canvas element not found!');
  608. }
  609. let config = this.configuration.engine || {};
  610. // TDO enable further configuration
  611. this.engine = new Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  612. // Disable manifest checking
  613. Database.IDBStorageEnabled = false;
  614. if (!config.disableResize) {
  615. window.addEventListener('resize', this.resize);
  616. }
  617. this.engine.runRenderLoop(this.render);
  618. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  619. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  620. this.engine.setHardwareScalingLevel(scale);
  621. }
  622. // set hardware limitations for scene initialization
  623. this.handleHardwareLimitations();
  624. return Promise.resolve(this.engine);
  625. }
  626. protected initScene(): Promise<Scene> {
  627. // if the scen exists, dispose it.
  628. if (this.scene) {
  629. this.scene.dispose();
  630. }
  631. // create a new scene
  632. this.scene = new Scene(this.engine);
  633. // make sure there is a default camera and light.
  634. this.scene.createDefaultLight(true);
  635. if (this.configuration.scene) {
  636. this.configureScene(this.configuration.scene);
  637. // Scene optimizer
  638. if (this.configuration.optimizer) {
  639. this.configureOptimizer(this.configuration.optimizer);
  640. }
  641. }
  642. return Promise.resolve(this.scene);
  643. }
  644. private isLoading: boolean;
  645. private nextLoading: Function;
  646. public loadModel(model: any = this.configuration.model, clearScene: boolean = true): Promise<Scene> {
  647. // no model was provided? Do nothing!
  648. let modelUrl = (typeof model === 'string') ? model : model.url;
  649. if (!modelUrl) {
  650. return Promise.resolve(this.scene);
  651. }
  652. if (this.isLoading) {
  653. //another model is being model. Wait for it to finish, trigger the load afterwards
  654. this.nextLoading = () => {
  655. delete this.nextLoading;
  656. this.loadModel(model, clearScene);
  657. }
  658. return Promise.resolve(this.scene);
  659. }
  660. this.isLoading = true;
  661. if ((typeof model === 'string')) {
  662. if (this.configuration.model && typeof this.configuration.model === 'object') {
  663. this.configuration.model.url = model;
  664. }
  665. } else {
  666. if (this.configuration.model) {
  667. deepmerge(this.configuration.model, model)
  668. } else {
  669. this.configuration.model = model;
  670. }
  671. }
  672. let parts = modelUrl.split('/');
  673. let filename = parts.pop();
  674. let base = parts.join('/') + '/';
  675. let plugin = (typeof model === 'string') ? undefined : model.loader;
  676. return Promise.resolve(this.scene).then((scene) => {
  677. if (!scene) return this.initScene();
  678. if (clearScene) {
  679. scene.meshes.forEach(mesh => {
  680. if (Tags.MatchesQuery(mesh, "viewerMesh")) {
  681. mesh.dispose();
  682. }
  683. });
  684. }
  685. return scene!;
  686. }).then(() => {
  687. return new Promise<Array<AbstractMesh>>((resolve, reject) => {
  688. this.lastUsedLoader = SceneLoader.ImportMesh(undefined, base, filename, this.scene, (meshes) => {
  689. meshes.forEach(mesh => {
  690. Tags.AddTagsTo(mesh, "viewerMesh");
  691. });
  692. resolve(meshes);
  693. }, (progressEvent) => {
  694. this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  695. }, (e, m, exception) => {
  696. // console.log(m, exception);
  697. this.onModelLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception }).then(() => {
  698. reject(exception);
  699. });
  700. }, plugin)!;
  701. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  702. });
  703. }).then((meshes: Array<AbstractMesh>) => {
  704. return this.onModelLoadedObservable.notifyObserversWithPromise(meshes)
  705. .then(() => {
  706. // update the models' configuration
  707. this.configureModel(this.configuration.model || model, meshes);
  708. this.configureLights(this.configuration.lights);
  709. if (this.configuration.camera) {
  710. this.configureCamera(this.configuration.camera, meshes);
  711. }
  712. return this.initEnvironment(meshes);
  713. }).then(() => {
  714. this.isLoading = false;
  715. if (this.nextLoading) {
  716. return this.nextLoading();
  717. }
  718. return this.scene;
  719. });
  720. });
  721. }
  722. protected initEnvironment(focusMeshes: Array<AbstractMesh> = this.scene.meshes): Promise<Scene> {
  723. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  724. return Promise.resolve(this.scene);
  725. }
  726. /**
  727. * Alters render settings to reduce features based on hardware feature limitations
  728. * @param options Viewer options to modify
  729. */
  730. protected handleHardwareLimitations() {
  731. //flip rendering settings switches based on hardware support
  732. let maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  733. let maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  734. //shadows are disabled if there's not enough varyings for a single shadow
  735. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  736. this.maxShadows = 0;
  737. } else {
  738. this.maxShadows = 3;
  739. }
  740. //can we render to any >= 16-bit targets (required for HDR)
  741. let caps = this.engine.getCaps();
  742. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  743. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  744. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  745. if (linearHalfFloatTargets) {
  746. this.defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  747. this.shadowGeneratorBias = 0.002;
  748. } else if (linearFloatTargets) {
  749. this.defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  750. this.shadowGeneratorBias = 0.001;
  751. } else {
  752. this.defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  753. this.shadowGeneratorBias = 0.001;
  754. }
  755. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  756. }
  757. /**
  758. * Injects all the spectre shader in the babylon shader store
  759. */
  760. protected injectCustomShaders(): void {
  761. let customShaders = this.configuration.customShaders;
  762. // Inject all the spectre shader in the babylon shader store.
  763. if (!customShaders) {
  764. return;
  765. }
  766. if (customShaders.shaders) {
  767. Object.keys(customShaders.shaders).forEach(key => {
  768. // typescript considers a callback "unsafe", so... '!'
  769. Effect.ShadersStore[key] = customShaders!.shaders![key];
  770. });
  771. }
  772. if (customShaders.includes) {
  773. Object.keys(customShaders.includes).forEach(key => {
  774. // typescript considers a callback "unsafe", so... '!'
  775. Effect.IncludesShadersStore[key] = customShaders!.includes![key];
  776. });
  777. }
  778. }
  779. protected extendClassWithConfig(object: any, config: any) {
  780. if (!config) return;
  781. Object.keys(config).forEach(key => {
  782. if (key in object && typeof object[key] !== 'function') {
  783. // if (typeof object[key] === 'function') return;
  784. // if it is an object, iterate internally until reaching basic types
  785. if (typeof object[key] === 'object') {
  786. this.extendClassWithConfig(object[key], config[key]);
  787. } else {
  788. if (config[key] !== undefined) {
  789. object[key] = config[key];
  790. }
  791. }
  792. }
  793. });
  794. }
  795. private setCameraBehavior(behaviorConfig: number | {
  796. type: number;
  797. [propName: string]: any;
  798. }, payload: any) {
  799. let behavior: Behavior<ArcRotateCamera> | null;
  800. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  801. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  802. // constructing behavior
  803. switch (type) {
  804. case CameraBehavior.AUTOROTATION:
  805. this.camera.useAutoRotationBehavior = true;
  806. behavior = this.camera.autoRotationBehavior;
  807. break;
  808. case CameraBehavior.BOUNCING:
  809. this.camera.useBouncingBehavior = true;
  810. behavior = this.camera.bouncingBehavior;
  811. break;
  812. case CameraBehavior.FRAMING:
  813. this.camera.useFramingBehavior = true;
  814. behavior = this.camera.framingBehavior;
  815. break;
  816. default:
  817. behavior = null;
  818. break;
  819. }
  820. if (behavior) {
  821. if (typeof behaviorConfig === "object") {
  822. this.extendClassWithConfig(behavior, behaviorConfig);
  823. }
  824. //this.camera.addBehavior(behavior);
  825. }
  826. // post attach configuration. Some functionalities require the attached camera.
  827. switch (type) {
  828. case CameraBehavior.AUTOROTATION:
  829. break;
  830. case CameraBehavior.BOUNCING:
  831. break;
  832. case CameraBehavior.FRAMING:
  833. if (config.zoomOnBoundingInfo) {
  834. //payload is an array of meshes
  835. let meshes = <Array<AbstractMesh>>payload;
  836. let bounding = meshes[0].getHierarchyBoundingVectors();
  837. (<FramingBehavior>behavior).zoomOnBoundingInfo(bounding.min, bounding.max);
  838. }
  839. break;
  840. }
  841. }
  842. }