defaultViewer.ts 21 KB

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