viewer.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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();
  364. const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  365. const sceneDiagonalLenght = sceneDiagonal.length();
  366. if (isFinite(sceneDiagonalLenght))
  367. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  368. }
  369. protected configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean } = {}, focusMeshes: Array<AbstractMesh> = this.scene.meshes) {
  370. // sanity check!
  371. if (!Object.keys(lightsConfiguration).length) return;
  372. let lightsAvailable: Array<string> = this.scene.lights.map(light => light.name);
  373. // compare to the global (!) configuration object and dispose unneeded:
  374. let lightsToConfigure = Object.keys(this.configuration.lights || []);
  375. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  376. lightsAvailable.forEach(lName => {
  377. if (lightsToConfigure.indexOf(lName) === -1) {
  378. this.scene.getLightByName(lName)!.dispose()
  379. }
  380. });
  381. }
  382. Object.keys(lightsConfiguration).forEach((name, idx) => {
  383. let lightConfig: ILightConfiguration = { type: 0 };
  384. if (typeof lightsConfiguration[name] === 'object') {
  385. lightConfig = <ILightConfiguration>lightsConfiguration[name];
  386. }
  387. lightConfig.name = name;
  388. let light: Light;
  389. // light is not already available
  390. if (lightsAvailable.indexOf(name) === -1) {
  391. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  392. if (!constructor) return;
  393. light = constructor();
  394. } else {
  395. // available? get it from the scene
  396. light = <Light>this.scene.getLightByName(name);
  397. lightsAvailable = lightsAvailable.filter(ln => ln !== name);
  398. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  399. light.dispose();
  400. let constructor = Light.GetConstructorFromName(lightConfig.type, lightConfig.name, this.scene);
  401. if (!constructor) return;
  402. light = constructor();
  403. }
  404. }
  405. // if config set the light to false, dispose it.
  406. if (lightsConfiguration[name] === false) {
  407. light.dispose();
  408. return;
  409. }
  410. //enabled
  411. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  412. light.setEnabled(enabled);
  413. this.extendClassWithConfig(light, lightConfig);
  414. //position. Some lights don't support shadows
  415. if (light instanceof ShadowLight) {
  416. if (lightConfig.target) {
  417. if (light.setDirectionToTarget) {
  418. let target = Vector3.Zero().copyFrom(lightConfig.target as Vector3);
  419. light.setDirectionToTarget(target);
  420. }
  421. } else if (lightConfig.direction) {
  422. let direction = Vector3.Zero().copyFrom(lightConfig.direction as Vector3);
  423. light.direction = direction;
  424. }
  425. let shadowGenerator = light.getShadowGenerator();
  426. if (lightConfig.shadowEnabled && this.maxShadows) {
  427. if (!shadowGenerator) {
  428. shadowGenerator = new ShadowGenerator(512, light);
  429. // TODO blur kernel definition
  430. }
  431. this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  432. // add the focues meshes to the shadow list
  433. let shadownMap = shadowGenerator.getShadowMap();
  434. if (!shadownMap) return;
  435. let renderList = shadownMap.renderList;
  436. for (var index = 0; index < focusMeshes.length; index++) {
  437. if (Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  438. renderList && renderList.push(focusMeshes[index]);
  439. }
  440. }
  441. } else if (shadowGenerator) {
  442. shadowGenerator.dispose();
  443. }
  444. }
  445. });
  446. // remove the unneeded lights
  447. /*lightsAvailable.forEach(name => {
  448. let light = this.scene.getLightByName(name);
  449. if (light && !Tags.MatchesQuery(light, "fixed")) {
  450. light.dispose();
  451. }
  452. });*/
  453. }
  454. protected configureModel(modelConfiguration: Partial<IModelConfiguration>, focusMeshes: Array<AbstractMesh> = this.scene.meshes) {
  455. let meshesWithNoParent: Array<AbstractMesh> = focusMeshes.filter(m => !m.parent);
  456. let updateMeshesWithNoParent = (variable: string, value: any, param?: string) => {
  457. meshesWithNoParent.forEach(mesh => {
  458. if (param) {
  459. mesh[variable][param] = value;
  460. } else {
  461. mesh[variable] = value;
  462. }
  463. });
  464. }
  465. let updateXYZ = (variable: string, configValues: { x: number, y: number, z: number, w?: number }) => {
  466. if (configValues.x !== undefined) {
  467. updateMeshesWithNoParent(variable, configValues.x, 'x');
  468. }
  469. if (configValues.y !== undefined) {
  470. updateMeshesWithNoParent(variable, configValues.y, 'y');
  471. }
  472. if (configValues.z !== undefined) {
  473. updateMeshesWithNoParent(variable, configValues.z, 'z');
  474. }
  475. if (configValues.w !== undefined) {
  476. updateMeshesWithNoParent(variable, configValues.w, 'w');
  477. }
  478. }
  479. // position?
  480. if (modelConfiguration.position) {
  481. updateXYZ('position', modelConfiguration.position);
  482. }
  483. if (modelConfiguration.rotation) {
  484. if (modelConfiguration.rotation.w) {
  485. meshesWithNoParent.forEach(mesh => {
  486. if (!mesh.rotationQuaternion) {
  487. mesh.rotationQuaternion = new Quaternion();
  488. }
  489. })
  490. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  491. } else {
  492. updateXYZ('rotation', modelConfiguration.rotation);
  493. }
  494. }
  495. if (modelConfiguration.scaling) {
  496. updateXYZ('scaling', modelConfiguration.scaling);
  497. }
  498. if (modelConfiguration.castShadow) {
  499. focusMeshes.forEach(mesh => {
  500. Tags.AddTagsTo(mesh, 'castShadow');
  501. });
  502. }
  503. if (modelConfiguration.normalize) {
  504. let center = false;
  505. let unitSize = false;
  506. let parentIndex;
  507. if (modelConfiguration.normalize === true) {
  508. center = true;
  509. unitSize = true;
  510. parentIndex = 0;
  511. } else {
  512. center = !!modelConfiguration.normalize.center;
  513. unitSize = !!modelConfiguration.normalize.unitSize;
  514. parentIndex = modelConfiguration.normalize.parentIndex;
  515. }
  516. let meshesToNormalize: Array<AbstractMesh> = [];
  517. if (parentIndex !== undefined) {
  518. meshesToNormalize.push(focusMeshes[parentIndex]);
  519. } else {
  520. meshesToNormalize = meshesWithNoParent;
  521. }
  522. if (unitSize) {
  523. meshesToNormalize.forEach(mesh => {
  524. console.log(mesh.scaling.x)
  525. mesh.normalizeToUnitCube(true);
  526. mesh.computeWorldMatrix(true);
  527. console.log(mesh.scaling.x)
  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. public loadModel(model: any = this.configuration.model, clearScene: boolean = true): Promise<Scene> {
  645. // no model was provided? Do nothing!
  646. if (!model.url) {
  647. return Promise.resolve(this.scene);
  648. }
  649. this.configuration.model = model;
  650. let modelUrl = (typeof model === 'string') ? model : model.url;
  651. let parts = modelUrl.split('/');
  652. let filename = parts.pop();
  653. let base = parts.join('/') + '/';
  654. let plugin = (typeof model === 'string') ? undefined : model.loader;
  655. return Promise.resolve(this.scene).then((scene) => {
  656. if (!scene) return this.initScene();
  657. if (clearScene) {
  658. scene.meshes.forEach(mesh => {
  659. mesh.dispose();
  660. });
  661. }
  662. return scene!;
  663. }).then(() => {
  664. return new Promise<Array<AbstractMesh>>((resolve, reject) => {
  665. this.lastUsedLoader = SceneLoader.ImportMesh(undefined, base, filename, this.scene, (meshes) => {
  666. resolve(meshes);
  667. }, (progressEvent) => {
  668. this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  669. }, (e, m, exception) => {
  670. // console.log(m, exception);
  671. this.onModelLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception }).then(() => {
  672. reject(exception);
  673. });
  674. }, plugin)!;
  675. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  676. });
  677. }).then((meshes: Array<AbstractMesh>) => {
  678. return this.onModelLoadedObservable.notifyObserversWithPromise(meshes)
  679. .then(() => {
  680. // update the models' configuration
  681. this.configureModel(model, meshes);
  682. this.configureLights(this.configuration.lights);
  683. if (this.configuration.camera) {
  684. this.configureCamera(this.configuration.camera, meshes);
  685. }
  686. return this.initEnvironment(meshes);
  687. }).then(() => {
  688. return this.scene;
  689. });
  690. });
  691. }
  692. protected initEnvironment(focusMeshes: Array<AbstractMesh> = []): Promise<Scene> {
  693. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  694. return Promise.resolve(this.scene);
  695. }
  696. /**
  697. * Alters render settings to reduce features based on hardware feature limitations
  698. * @param options Viewer options to modify
  699. */
  700. protected handleHardwareLimitations() {
  701. //flip rendering settings switches based on hardware support
  702. let maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  703. let maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  704. //shadows are disabled if there's not enough varyings for a single shadow
  705. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  706. this.maxShadows = 0;
  707. } else {
  708. this.maxShadows = 3;
  709. }
  710. //can we render to any >= 16-bit targets (required for HDR)
  711. let caps = this.engine.getCaps();
  712. let linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  713. let linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  714. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  715. if (linearHalfFloatTargets) {
  716. this.defaultHighpTextureType = Engine.TEXTURETYPE_HALF_FLOAT;
  717. this.shadowGeneratorBias = 0.002;
  718. } else if (linearFloatTargets) {
  719. this.defaultHighpTextureType = Engine.TEXTURETYPE_FLOAT;
  720. this.shadowGeneratorBias = 0.001;
  721. } else {
  722. this.defaultHighpTextureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  723. this.shadowGeneratorBias = 0.001;
  724. }
  725. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : Engine.TEXTURETYPE_UNSIGNED_INT;
  726. }
  727. /**
  728. * Injects all the spectre shader in the babylon shader store
  729. */
  730. protected injectCustomShaders(): void {
  731. let customShaders = this.configuration.customShaders;
  732. // Inject all the spectre shader in the babylon shader store.
  733. if (!customShaders) {
  734. return;
  735. }
  736. if (customShaders.shaders) {
  737. Object.keys(customShaders.shaders).forEach(key => {
  738. // typescript considers a callback "unsafe", so... '!'
  739. Effect.ShadersStore[key] = customShaders!.shaders![key];
  740. });
  741. }
  742. if (customShaders.includes) {
  743. Object.keys(customShaders.includes).forEach(key => {
  744. // typescript considers a callback "unsafe", so... '!'
  745. Effect.IncludesShadersStore[key] = customShaders!.includes![key];
  746. });
  747. }
  748. }
  749. protected extendClassWithConfig(object: any, config: any) {
  750. if (!config) return;
  751. Object.keys(config).forEach(key => {
  752. if (key in object && typeof object[key] !== 'function') {
  753. // if (typeof object[key] === 'function') return;
  754. // if it is an object, iterate internally until reaching basic types
  755. if (typeof object[key] === 'object') {
  756. this.extendClassWithConfig(object[key], config[key]);
  757. } else {
  758. if (config[key] !== undefined) {
  759. object[key] = config[key];
  760. }
  761. }
  762. }
  763. });
  764. }
  765. private setCameraBehavior(behaviorConfig: number | {
  766. type: number;
  767. [propName: string]: any;
  768. }, payload: any) {
  769. let behavior: Behavior<ArcRotateCamera> | null;
  770. let type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  771. let config: { [propName: string]: any } = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  772. // constructing behavior
  773. switch (type) {
  774. case CameraBehavior.AUTOROTATION:
  775. this.camera.useAutoRotationBehavior = true;
  776. behavior = this.camera.autoRotationBehavior;
  777. break;
  778. case CameraBehavior.BOUNCING:
  779. this.camera.useBouncingBehavior = true;
  780. behavior = this.camera.bouncingBehavior;
  781. break;
  782. case CameraBehavior.FRAMING:
  783. this.camera.useFramingBehavior = true;
  784. behavior = this.camera.framingBehavior;
  785. break;
  786. default:
  787. behavior = null;
  788. break;
  789. }
  790. if (behavior) {
  791. if (typeof behaviorConfig === "object") {
  792. this.extendClassWithConfig(behavior, behaviorConfig);
  793. }
  794. //this.camera.addBehavior(behavior);
  795. }
  796. // post attach configuration. Some functionalities require the attached camera.
  797. switch (type) {
  798. case CameraBehavior.AUTOROTATION:
  799. break;
  800. case CameraBehavior.BOUNCING:
  801. break;
  802. case CameraBehavior.FRAMING:
  803. if (config.zoomOnBoundingInfo) {
  804. //payload is an array of meshes
  805. let meshes = <Array<AbstractMesh>>payload;
  806. let bounding = meshes[0].getHierarchyBoundingVectors();
  807. (<FramingBehavior>behavior).zoomOnBoundingInfo(bounding.min, bounding.max);
  808. }
  809. break;
  810. }
  811. }
  812. }