defaultViewer.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. import { ViewerConfiguration, IModelConfiguration, ILightConfiguration } from './../configuration';
  2. import { Template, EventCallback, TemplateManager } from '../templating/templateManager';
  3. import { AbstractViewer } from './viewer';
  4. import { SpotLight, MirrorTexture, Plane, ShadowGenerator, Texture, BackgroundMaterial, Observable, ShadowLight, CubeTexture, BouncingBehavior, FramingBehavior, Behavior, Light, Engine, Scene, AutoRotationBehavior, AbstractMesh, Quaternion, StandardMaterial, ArcRotateCamera, ImageProcessingConfiguration, Color3, Vector3, SceneLoader, Mesh, HemisphericLight, FilesInput } from 'babylonjs';
  5. import { CameraBehavior } from '../interfaces';
  6. import { ViewerModel } from '../model/viewerModel';
  7. import { extendClassWithConfig } from '../helper';
  8. import { IModelAnimation, AnimationState } from '../model/modelAnimation';
  9. /**
  10. * The Default viewer is the default implementation of the AbstractViewer.
  11. * It uses the templating system to render a new canvas and controls.
  12. */
  13. export class DefaultViewer extends AbstractViewer {
  14. /**
  15. * Create a new default viewer
  16. * @param containerElement the element in which the templates will be rendered
  17. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  18. */
  19. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = { extends: 'default' }) {
  20. super(containerElement, initialConfiguration);
  21. this.onModelLoadedObservable.add(this._onModelLoaded);
  22. this.onModelRemovedObservable.add(() => {
  23. this._configureTemplate();
  24. })
  25. this.onEngineInitObservable.add(() => {
  26. this.sceneManager.onLightsConfiguredObservable.add((data) => {
  27. this._configureLights(data.newConfiguration, data.model!);
  28. })
  29. });
  30. }
  31. /**
  32. * This will be executed when the templates initialize.
  33. */
  34. protected _onTemplatesLoaded() {
  35. this.showLoadingScreen();
  36. // navbar
  37. this._initNavbar();
  38. // close overlay button
  39. let template = this.templateManager.getTemplate('overlay');
  40. if (template) {
  41. let closeButton = template.parent.querySelector('.close-button');
  42. if (closeButton) {
  43. closeButton.addEventListener('pointerdown', () => {
  44. this.hideOverlayScreen();
  45. });
  46. }
  47. }
  48. if (this.configuration.templates && this.configuration.templates.viewer) {
  49. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  50. let filesInput = new FilesInput(this.engine, this.sceneManager.scene, () => {
  51. }, () => {
  52. }, () => {
  53. }, () => {
  54. }, function () {
  55. }, (file: File) => {
  56. this.loadModel(file);
  57. }, () => {
  58. });
  59. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas()!);
  60. }
  61. }
  62. return super._onTemplatesLoaded();
  63. }
  64. private _dropped(evt: EventCallback) {
  65. }
  66. private _initNavbar() {
  67. let navbar = this.templateManager.getTemplate('navBar');
  68. if (navbar) {
  69. this.onFrameRenderedObservable.add(this._updateProgressBar);
  70. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  71. // an example how to trigger the help button. publiclly available
  72. this.templateManager.eventManager.registerCallback("navBar", () => {
  73. // do your thing
  74. }, "pointerdown", ".help-button");
  75. this.templateManager.eventManager.registerCallback("navBar", (event: EventCallback) => {
  76. const evt = event.event;
  77. const element = <HTMLInputElement>(evt.target);
  78. if (!this._currentAnimation) return;
  79. const gotoFrame = +element.value / 100 * this._currentAnimation.frames;
  80. if (isNaN(gotoFrame)) return;
  81. this._currentAnimation.goToFrame(gotoFrame);
  82. }, "input");
  83. this.templateManager.eventManager.registerCallback("navBar", (e) => {
  84. if (this._resumePlay) {
  85. this._togglePlayPause(true);
  86. }
  87. this._resumePlay = false;
  88. }, "pointerup", ".progress-wrapper");
  89. }
  90. }
  91. private _animationList: string[];
  92. private _currentAnimation: IModelAnimation;
  93. private _isAnimationPaused: boolean;
  94. private _resumePlay: boolean;
  95. private _handlePointerDown = (event: EventCallback) => {
  96. let pointerDown = <PointerEvent>event.event;
  97. if (pointerDown.button !== 0) return;
  98. var element = (<HTMLElement>event.event.target);
  99. if (!element) {
  100. return;
  101. }
  102. let parentClasses = element.parentElement!.classList;
  103. let elementClasses = element.classList;
  104. let elementName = ""; 0
  105. for (let i = 0; i < elementClasses.length; ++i) {
  106. let className = elementClasses[i];
  107. if (className.indexOf("-button") !== -1 || className.indexOf("-wrapper") !== -1) {
  108. elementName = className;
  109. break;
  110. }
  111. }
  112. switch (elementName) {
  113. case "speed-button":
  114. case "types-button":
  115. if (parentClasses.contains("open")) {
  116. parentClasses.remove("open");
  117. } else {
  118. parentClasses.add("open");
  119. }
  120. break;
  121. case "play-pause-button":
  122. this._togglePlayPause();
  123. break;
  124. case "label-option-button":
  125. var label = element.dataset["value"];
  126. if (label) {
  127. this._updateAnimationType(label);
  128. }
  129. break;
  130. case "speed-option-button":
  131. if (!this._currentAnimation) {
  132. return;
  133. }
  134. var speed = element.dataset["value"];
  135. if (speed)
  136. this._updateAnimationSpeed(speed);
  137. break;
  138. case "progress-wrapper":
  139. this._resumePlay = !this._isAnimationPaused;
  140. if (this._resumePlay) {
  141. this._togglePlayPause(true);
  142. }
  143. break;
  144. case "fullscreen-button":
  145. this.toggleFullscreen();
  146. break;
  147. case "hd-button":
  148. this.toggleHD();
  149. break;
  150. default:
  151. return;
  152. }
  153. }
  154. /**
  155. * Plays or Pauses animation
  156. */
  157. private _togglePlayPause = (noUiUpdate?: boolean) => {
  158. if (!this._currentAnimation) {
  159. return;
  160. }
  161. if (this._isAnimationPaused) {
  162. this._currentAnimation.restart();
  163. } else {
  164. this._currentAnimation.pause();
  165. }
  166. this._isAnimationPaused = !this._isAnimationPaused;
  167. if (noUiUpdate) return;
  168. let navbar = this.templateManager.getTemplate('navBar');
  169. if (!navbar) return;
  170. navbar.updateParams({
  171. paused: this._isAnimationPaused,
  172. });
  173. }
  174. private _oldIdleRotationValue: number;
  175. /**
  176. * Control progress bar position based on animation current frame
  177. */
  178. private _updateProgressBar = () => {
  179. let navbar = this.templateManager.getTemplate('navBar');
  180. if (!navbar) return;
  181. var progressSlider = <HTMLInputElement>navbar.parent.querySelector("input.progress-wrapper");
  182. if (progressSlider && this._currentAnimation) {
  183. const progress = this._currentAnimation.currentFrame / this._currentAnimation.frames * 100;
  184. var currentValue = progressSlider.valueAsNumber;
  185. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  186. progressSlider.value = '' + progress;
  187. }
  188. if (this._currentAnimation.state === AnimationState.PLAYING) {
  189. if (this.sceneManager.camera.autoRotationBehavior && !this._oldIdleRotationValue) {
  190. this._oldIdleRotationValue = this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  191. this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  192. }
  193. } else {
  194. if (this.sceneManager.camera.autoRotationBehavior && this._oldIdleRotationValue) {
  195. this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = this._oldIdleRotationValue;
  196. this._oldIdleRotationValue = 0;
  197. }
  198. }
  199. }
  200. }
  201. /**
  202. * Update Current Animation Speed
  203. */
  204. private _updateAnimationSpeed = (speed: string, paramsObject?: any) => {
  205. let navbar = this.templateManager.getTemplate('navBar');
  206. if (!navbar) return;
  207. if (speed && this._currentAnimation) {
  208. this._currentAnimation.speedRatio = parseFloat(speed);
  209. if (!this._isAnimationPaused) {
  210. this._currentAnimation.restart();
  211. }
  212. if (paramsObject) {
  213. paramsObject.selectedSpeed = speed + "x"
  214. } else {
  215. navbar.updateParams({
  216. selectedSpeed: speed + "x",
  217. });
  218. }
  219. }
  220. }
  221. /**
  222. * Update Current Animation Type
  223. */
  224. private _updateAnimationType = (label: string, paramsObject?: any) => {
  225. let navbar = this.templateManager.getTemplate('navBar');
  226. if (!navbar) return;
  227. if (label) {
  228. this._currentAnimation = this.sceneManager.models[0].setCurrentAnimationByName(label);
  229. }
  230. if (paramsObject) {
  231. paramsObject.selectedAnimation = (this._animationList.indexOf(label) + 1);
  232. paramsObject.selectedAnimationName = label;
  233. } else {
  234. navbar.updateParams({
  235. selectedAnimation: (this._animationList.indexOf(label) + 1),
  236. selectedAnimationName: label
  237. });
  238. }
  239. this._updateAnimationSpeed("1.0", paramsObject);
  240. }
  241. public toggleHD() {
  242. super.toggleHD();
  243. // update UI element
  244. let navbar = this.templateManager.getTemplate('navBar');
  245. if (!navbar) return;
  246. if (navbar.configuration.params) {
  247. navbar.configuration.params.hdEnabled = this._hdToggled;
  248. }
  249. let span = navbar.parent.querySelector("button.hd-button span");
  250. if (span) {
  251. span.classList.remove(this._hdToggled ? "hd-icon" : "sd-icon");
  252. span.classList.add(!this._hdToggled ? "hd-icon" : "sd-icon")
  253. }
  254. }
  255. /**
  256. * Toggle fullscreen of the entire viewer
  257. */
  258. public toggleFullscreen = () => {
  259. let viewerTemplate = this.templateManager.getTemplate('viewer');
  260. let viewerElement = viewerTemplate && viewerTemplate.parent;
  261. if (viewerElement) {
  262. let fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || (<any>document).mozFullScreenElement || (<any>document).msFullscreenElement;
  263. if (!fullscreenElement) {
  264. let requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || (<any>viewerElement).msRequestFullscreen || (<any>viewerElement).mozRequestFullScreen;
  265. requestFullScreen.call(viewerElement);
  266. } else {
  267. let exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || (<any>document).msExitFullscreen || (<any>document).mozCancelFullScreen
  268. exitFullscreen.call(document);
  269. }
  270. }
  271. }
  272. /**
  273. * Preparing the container element to present the viewer
  274. */
  275. protected _prepareContainerElement() {
  276. this.containerElement.style.position = 'relative';
  277. this.containerElement.style.height = '100%';
  278. this.containerElement.style.display = 'flex';
  279. }
  280. /**
  281. * This function will configure the templates and update them after a model was loaded
  282. * It is mainly responsible to changing the title and subtitle etc'.
  283. * @param model the model to be used to configure the templates by
  284. */
  285. protected _configureTemplate(model?: ViewerModel) {
  286. let navbar = this.templateManager.getTemplate('navBar');
  287. if (!navbar) return;
  288. let newParams: any = navbar.configuration.params || {};
  289. if (!model) {
  290. newParams.animations = null;
  291. } else {
  292. let animationNames = model.getAnimationNames();
  293. newParams.animations = animationNames;
  294. if (animationNames.length) {
  295. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  296. this._animationList = animationNames;
  297. newParams.paused = this._isAnimationPaused;
  298. let animationIndex = 0;
  299. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  300. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  301. if (animationIndex === -1) {
  302. animationIndex = 0;
  303. }
  304. }
  305. this._updateAnimationType(animationNames[animationIndex], newParams);
  306. } else {
  307. newParams.animations = null;
  308. }
  309. if (model.configuration.thumbnail) {
  310. newParams.logoImage = model.configuration.thumbnail
  311. }
  312. }
  313. navbar.updateParams(newParams, false);
  314. }
  315. /**
  316. * This will load a new model to the default viewer
  317. * overriding the AbstractViewer's loadModel.
  318. * The scene will automatically be cleared of the old models, if exist.
  319. * @param model the configuration object (or URL) to load.
  320. */
  321. public loadModel(model?: string | File | IModelConfiguration): Promise<ViewerModel> {
  322. if (!model) {
  323. model = this.configuration.model;
  324. }
  325. this.showLoadingScreen();
  326. return super.loadModel(model!, true).catch((error) => {
  327. console.log(error);
  328. this.hideLoadingScreen();
  329. this.showOverlayScreen('error');
  330. return Promise.reject(error);
  331. });
  332. }
  333. private _onModelLoaded = (model: ViewerModel) => {
  334. this._configureTemplate(model);
  335. // with a short timeout, making sure everything is there already.
  336. let hideLoadingDelay = 20;
  337. if (this.configuration.lab && this.configuration.lab.hideLoadingDelay !== undefined) {
  338. hideLoadingDelay = this.configuration.lab.hideLoadingDelay;
  339. }
  340. setTimeout(() => {
  341. this.sceneManager.scene.executeWhenReady(() => {
  342. this.hideLoadingScreen();
  343. });
  344. }, hideLoadingDelay);
  345. return;
  346. }
  347. /**
  348. * Show the overlay and the defined sub-screen.
  349. * Mainly used for help and errors
  350. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  351. */
  352. public showOverlayScreen(subScreen: string) {
  353. let template = this.templateManager.getTemplate('overlay');
  354. if (!template) return Promise.resolve('Overlay template not found');
  355. return template.show((template => {
  356. var canvasRect = this.containerElement.getBoundingClientRect();
  357. template.parent.style.display = 'flex';
  358. template.parent.style.width = canvasRect.width + "px";
  359. template.parent.style.height = canvasRect.height + "px";
  360. template.parent.style.opacity = "1";
  361. let subTemplate = this.templateManager.getTemplate(subScreen);
  362. if (!subTemplate) {
  363. return Promise.reject(subScreen + ' template not found');
  364. }
  365. return subTemplate.show((template => {
  366. template.parent.style.display = 'flex';
  367. return Promise.resolve(template);
  368. }));
  369. }));
  370. }
  371. /**
  372. * Hide the overlay screen.
  373. */
  374. public hideOverlayScreen() {
  375. let template = this.templateManager.getTemplate('overlay');
  376. if (!template) return Promise.resolve('Overlay template not found');
  377. return template.hide((template => {
  378. template.parent.style.opacity = "0";
  379. let onTransitionEnd = () => {
  380. template.parent.removeEventListener("transitionend", onTransitionEnd);
  381. template.parent.style.display = 'none';
  382. }
  383. template.parent.addEventListener("transitionend", onTransitionEnd);
  384. let overlays = template.parent.querySelectorAll('.overlay');
  385. if (overlays) {
  386. for (let i = 0; i < overlays.length; ++i) {
  387. let htmlElement = <HTMLElement>overlays.item(i);
  388. htmlElement.style.display = 'none';
  389. }
  390. }
  391. return Promise.resolve(template);
  392. }));
  393. }
  394. /**
  395. * show the viewer (in case it was hidden)
  396. *
  397. * @param visibilityFunction an optional function to execute in order to show the container
  398. */
  399. public show(visibilityFunction?: ((template: Template) => Promise<Template>)): Promise<Template> {
  400. let template = this.templateManager.getTemplate('main');
  401. //not possible, but yet:
  402. if (!template) return Promise.reject('Main template not found');
  403. return template.show(visibilityFunction);
  404. }
  405. /**
  406. * hide the viewer (in case it is visible)
  407. *
  408. * @param visibilityFunction an optional function to execute in order to hide the container
  409. */
  410. public hide(visibilityFunction?: ((template: Template) => Promise<Template>)) {
  411. let template = this.templateManager.getTemplate('main');
  412. //not possible, but yet:
  413. if (!template) return Promise.reject('Main template not found');
  414. return template.hide(visibilityFunction);
  415. }
  416. /**
  417. * Show the loading screen.
  418. * The loading screen can be configured using the configuration object
  419. */
  420. public showLoadingScreen() {
  421. let template = this.templateManager.getTemplate('loadingScreen');
  422. if (!template) return Promise.resolve('Loading Screen template not found');
  423. return template.show((template => {
  424. var canvasRect = this.containerElement.getBoundingClientRect();
  425. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  426. template.parent.style.display = 'flex';
  427. template.parent.style.width = canvasRect.width + "px";
  428. template.parent.style.height = canvasRect.height + "px";
  429. template.parent.style.opacity = "1";
  430. // from the configuration!!!
  431. let color = "black";
  432. if (this.configuration.templates && this.configuration.templates.loadingScreen) {
  433. color = (this.configuration.templates.loadingScreen.params &&
  434. <string>this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  435. }
  436. template.parent.style.backgroundColor = color;
  437. return Promise.resolve(template);
  438. }));
  439. }
  440. /**
  441. * Hide the loading screen
  442. */
  443. public hideLoadingScreen() {
  444. let template = this.templateManager.getTemplate('loadingScreen');
  445. if (!template) return Promise.resolve('Loading Screen template not found');
  446. return template.hide((template => {
  447. template.parent.style.opacity = "0";
  448. let onTransitionEnd = () => {
  449. template.parent.removeEventListener("transitionend", onTransitionEnd);
  450. template.parent.style.display = 'none';
  451. }
  452. template.parent.addEventListener("transitionend", onTransitionEnd);
  453. return Promise.resolve(template);
  454. }));
  455. }
  456. public dispose() {
  457. this.templateManager.dispose();
  458. super.dispose();
  459. }
  460. protected _onConfigurationLoaded(configuration: ViewerConfiguration) {
  461. super._onConfigurationLoaded(configuration);
  462. // initialize the templates
  463. let templateConfiguration = this.configuration.templates || {};
  464. this.templateManager.initTemplate(templateConfiguration);
  465. // when done, execute onTemplatesLoaded()
  466. this.templateManager.onAllLoaded.add(() => {
  467. let canvas = this.templateManager.getCanvas();
  468. if (canvas) {
  469. this._canvas = canvas;
  470. }
  471. this._onTemplateLoaded();
  472. });
  473. }
  474. /**
  475. * An extension of the light configuration of the abstract viewer.
  476. * @param lightsConfiguration the light configuration to use
  477. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  478. */
  479. private _configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean | number } = {}, model?: ViewerModel) {
  480. // labs feature - flashlight
  481. if (this.configuration.lab && this.configuration.lab.flashlight) {
  482. let pointerPosition = Vector3.Zero();
  483. let lightTarget;
  484. let angle = 0.5;
  485. let exponent = Math.PI / 2;
  486. if (typeof this.configuration.lab.flashlight === "object") {
  487. exponent = this.configuration.lab.flashlight.exponent || exponent;
  488. angle = this.configuration.lab.flashlight.angle || angle;
  489. }
  490. var flashlight = new SpotLight("flashlight", Vector3.Zero(),
  491. Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  492. if (typeof this.configuration.lab.flashlight === "object") {
  493. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  494. if (this.configuration.lab.flashlight.diffuse) {
  495. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  496. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  497. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  498. }
  499. if (this.configuration.lab.flashlight.specular) {
  500. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  501. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  502. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  503. }
  504. }
  505. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  506. this.sceneManager.scene.onPointerObservable.add((eventData, eventState) => {
  507. if (eventData.type === 4 && eventData.pickInfo) {
  508. lightTarget = (eventData.pickInfo.pickedPoint);
  509. } else {
  510. lightTarget = undefined;
  511. }
  512. });
  513. let updateFlashlightFunction = () => {
  514. if (this.sceneManager.camera && flashlight) {
  515. flashlight.position.copyFrom(this.sceneManager.camera.position);
  516. if (lightTarget) {
  517. lightTarget.subtractToRef(flashlight.position, flashlight.direction);
  518. }
  519. }
  520. }
  521. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  522. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  523. }
  524. }
  525. }