previewManager.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { GlobalState } from '../../globalState';
  2. import { NodeMaterial } from 'babylonjs/Materials/Node/nodeMaterial';
  3. import { Nullable } from 'babylonjs/types';
  4. import { Observer } from 'babylonjs/Misc/observable';
  5. import { Engine } from 'babylonjs/Engines/engine';
  6. import { Scene } from 'babylonjs/scene';
  7. import { Mesh } from 'babylonjs/Meshes/mesh';
  8. import { Vector3 } from 'babylonjs/Maths/math.vector';
  9. import { HemisphericLight } from 'babylonjs/Lights/hemisphericLight';
  10. import { ArcRotateCamera } from 'babylonjs/Cameras/arcRotateCamera';
  11. import { PreviewMeshType } from './previewMeshType';
  12. import { Animation } from 'babylonjs/Animations/animation';
  13. import { SceneLoader } from 'babylonjs/Loading/sceneLoader';
  14. import { TransformNode } from 'babylonjs/Meshes/transformNode';
  15. import { AbstractMesh } from 'babylonjs/Meshes/abstractMesh';
  16. import { FramingBehavior } from 'babylonjs/Behaviors/Cameras/framingBehavior';
  17. export class PreviewManager {
  18. private _nodeMaterial: NodeMaterial;
  19. private _onBuildObserver: Nullable<Observer<NodeMaterial>>;
  20. private _onPreviewCommandActivatedObserver: Nullable<Observer<void>>;
  21. private _onAnimationCommandActivatedObserver: Nullable<Observer<void>>;
  22. private _onUpdateRequiredObserver: Nullable<Observer<void>>;
  23. private _onPreviewBackgroundChangedObserver: Nullable<Observer<void>>;
  24. private _engine: Engine;
  25. private _scene: Scene;
  26. private _light: HemisphericLight;
  27. private _meshes: AbstractMesh[];
  28. private _camera: ArcRotateCamera;
  29. private _material: NodeMaterial;
  30. private _globalState: GlobalState;
  31. private _currentType: number;
  32. public constructor(targetCanvas: HTMLCanvasElement, globalState: GlobalState) {
  33. this._nodeMaterial = globalState.nodeMaterial;
  34. this._globalState = globalState;
  35. this._onBuildObserver = this._nodeMaterial.onBuildObservable.add((nodeMaterial) => {
  36. let serializationObject = nodeMaterial.serialize();
  37. this._updatePreview(serializationObject);
  38. });
  39. this._onPreviewCommandActivatedObserver = globalState.onPreviewCommandActivated.add(() => {
  40. this._refreshPreviewMesh();
  41. });
  42. this._onUpdateRequiredObserver = globalState.onUpdateRequiredObservable.add(() => {
  43. let serializationObject = this._nodeMaterial.serialize();
  44. this._updatePreview(serializationObject);
  45. });
  46. this._onPreviewBackgroundChangedObserver = globalState.onPreviewBackgroundChanged.add(() => {
  47. this._scene.clearColor = this._globalState.backgroundColor;
  48. });
  49. this._onAnimationCommandActivatedObserver = globalState.onAnimationCommandActivated.add(() => {
  50. this._handleAnimations();
  51. });
  52. this._engine = new Engine(targetCanvas, true);
  53. this._scene = new Scene(this._engine);
  54. this._camera = new ArcRotateCamera("Camera", 0, 0.8, 4, Vector3.Zero(), this._scene);
  55. this._camera.lowerRadiusLimit = 3;
  56. this._camera.upperRadiusLimit = 10;
  57. this._camera.wheelPrecision = 20;
  58. this._camera.minZ = 0.1;
  59. this._camera.attachControl(targetCanvas, false);
  60. this._refreshPreviewMesh();
  61. this._engine.runRenderLoop(() => {
  62. this._engine.resize();
  63. this._scene.render();
  64. });
  65. let serializationObject = this._nodeMaterial.serialize();
  66. this._updatePreview(serializationObject);
  67. }
  68. private _handleAnimations() {
  69. this._scene.stopAllAnimations();
  70. if (this._globalState.rotatePreview) {
  71. for (var root of this._scene.rootNodes) {
  72. let transformNode = root as TransformNode;
  73. if (transformNode.getClassName() === "TransformNode" || transformNode.getClassName() === "Mesh") {
  74. if (transformNode.rotationQuaternion) {
  75. transformNode.rotation = transformNode.rotationQuaternion.toEulerAngles();
  76. transformNode.rotationQuaternion = null;
  77. }
  78. Animation.CreateAndStartAnimation("turnTable", root, "rotation.y", 60, 1200, transformNode.rotation.y, transformNode.rotation.y + 2 * Math.PI, 1);
  79. }
  80. }
  81. }
  82. }
  83. private _prepareMeshes() {
  84. // Material
  85. for (var mesh of this._meshes) {
  86. mesh.material = this._material;
  87. }
  88. // Light
  89. if (!this._scene.lights.length) {
  90. this._light = new HemisphericLight("light", new Vector3(0, 1, 0), this._scene);
  91. }
  92. // Framing
  93. this._camera.useFramingBehavior = true;
  94. var framingBehavior = this._camera.getBehaviorByName("Framing") as FramingBehavior;
  95. framingBehavior.framingTime = 0;
  96. framingBehavior.elevationReturnTime = -1;
  97. if (this._scene.meshes.length) {
  98. var worldExtends = this._scene.getWorldExtends();
  99. this._camera.lowerRadiusLimit = null;
  100. this._camera.upperRadiusLimit = null;
  101. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  102. }
  103. this._camera.pinchPrecision = 200 / this._camera.radius;
  104. this._camera.upperRadiusLimit = 5 * this._camera.radius;
  105. this._camera.wheelDeltaPercentage = 0.01;
  106. this._camera.pinchDeltaPercentage = 0.01;
  107. // Animations
  108. this._handleAnimations();
  109. }
  110. private _refreshPreviewMesh() {
  111. if (this._currentType !== this._globalState.previewMeshType || this._currentType === PreviewMeshType.Custom) {
  112. this._currentType = this._globalState.previewMeshType;
  113. if (this._meshes && this._meshes.length) {
  114. for (var mesh of this._meshes) {
  115. mesh.dispose();
  116. }
  117. }
  118. this._meshes = [];
  119. let lights = this._scene.lights.slice(0);
  120. for (var light of lights) {
  121. light.dispose();
  122. }
  123. switch (this._globalState.previewMeshType) {
  124. case PreviewMeshType.Box:
  125. this._meshes.push(Mesh.CreateBox("dummy-box", 2, this._scene));
  126. break;
  127. case PreviewMeshType.Sphere:
  128. this._meshes.push(Mesh.CreateSphere("dummy-sphere", 32, 2, this._scene));
  129. break;
  130. case PreviewMeshType.Torus:
  131. this._meshes.push(Mesh.CreateTorus("dummy-torus", 2, 0.5, 32, this._scene));
  132. break;
  133. case PreviewMeshType.Cylinder:
  134. SceneLoader.AppendAsync("https://models.babylonjs.com/", "roundedCylinder.glb", this._scene).then(() => {
  135. this._meshes.push(...this._scene.meshes);
  136. this._prepareMeshes();
  137. });
  138. return;
  139. case PreviewMeshType.Plane:
  140. this._meshes.push(Mesh.CreateGround("dummy-plane", 2, 2, 128, this._scene));
  141. break;
  142. case PreviewMeshType.ShaderBall:
  143. SceneLoader.AppendAsync("https://models.babylonjs.com/", "shaderBall.glb", this._scene).then(() => {
  144. this._meshes.push(...this._scene.meshes);
  145. this._prepareMeshes();
  146. });
  147. return;
  148. case PreviewMeshType.Custom:
  149. SceneLoader.AppendAsync("file:", this._globalState.previewMeshFile, this._scene).then(() => {
  150. this._meshes.push(...this._scene.meshes);
  151. this._prepareMeshes();
  152. });
  153. return;
  154. }
  155. this._prepareMeshes();
  156. }
  157. }
  158. private _forceCompilationAsync(material: NodeMaterial, mesh: AbstractMesh): Promise<void> {
  159. return material.forceCompilationAsync(mesh);
  160. }
  161. private _updatePreview(serializationObject: any) {
  162. try {
  163. let tempMaterial = NodeMaterial.Parse(serializationObject, this._scene);
  164. if (this._meshes.length) {
  165. let tasks = this._meshes.map(m => this._forceCompilationAsync(tempMaterial, m));
  166. Promise.all(tasks).then(() => {
  167. for (var mesh of this._meshes) {
  168. mesh.material = tempMaterial;
  169. }
  170. if (this._material) {
  171. this._material.dispose();
  172. }
  173. this._material = tempMaterial;
  174. });
  175. } else {
  176. this._material = tempMaterial;
  177. }
  178. } catch(err) {
  179. // Ignore the error
  180. }
  181. }
  182. public dispose() {
  183. this._nodeMaterial.onBuildObservable.remove(this._onBuildObserver);
  184. this._globalState.onPreviewCommandActivated.remove(this._onPreviewCommandActivatedObserver);
  185. this._globalState.onUpdateRequiredObservable.remove(this._onUpdateRequiredObserver);
  186. this._globalState.onAnimationCommandActivated.remove(this._onAnimationCommandActivatedObserver);
  187. this._globalState.onPreviewBackgroundChanged.remove(this._onPreviewBackgroundChangedObserver);
  188. if (this._material) {
  189. this._material.dispose();
  190. }
  191. this._camera.dispose();
  192. for (var mesh of this._meshes) {
  193. mesh.dispose();
  194. }
  195. if (this._light) {
  196. this._light.dispose();
  197. }
  198. this._scene.dispose();
  199. this._engine.dispose();
  200. }
  201. }