previewManager.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. import { DirectionalLight } from 'babylonjs/Lights/directionalLight';
  18. import { LogEntry } from '../log/logComponent';
  19. import { PointerEventTypes } from 'babylonjs/Events/pointerEvents';
  20. import { Color3 } from 'babylonjs/Maths/math.color';
  21. export class PreviewManager {
  22. private _nodeMaterial: NodeMaterial;
  23. private _onBuildObserver: Nullable<Observer<NodeMaterial>>;
  24. private _onPreviewCommandActivatedObserver: Nullable<Observer<void>>;
  25. private _onAnimationCommandActivatedObserver: Nullable<Observer<void>>;
  26. private _onUpdateRequiredObserver: Nullable<Observer<void>>;
  27. private _onPreviewBackgroundChangedObserver: Nullable<Observer<void>>;
  28. private _onBackFaceCullingChangedObserver: Nullable<Observer<void>>;
  29. private _onDepthPrePassChangedObserver: Nullable<Observer<void>>;
  30. private _onLightUpdatedObserver: Nullable<Observer<void>>;
  31. private _engine: Engine;
  32. private _scene: Scene;
  33. private _meshes: AbstractMesh[];
  34. private _camera: ArcRotateCamera;
  35. private _material: NodeMaterial;
  36. private _globalState: GlobalState;
  37. private _currentType: number;
  38. private _lightParent: TransformNode;
  39. public constructor(targetCanvas: HTMLCanvasElement, globalState: GlobalState) {
  40. this._nodeMaterial = globalState.nodeMaterial;
  41. this._globalState = globalState;
  42. this._onBuildObserver = this._nodeMaterial.onBuildObservable.add((nodeMaterial) => {
  43. let serializationObject = nodeMaterial.serialize();
  44. this._updatePreview(serializationObject);
  45. });
  46. this._onPreviewCommandActivatedObserver = globalState.onPreviewCommandActivated.add(() => {
  47. this._refreshPreviewMesh();
  48. });
  49. this._onLightUpdatedObserver = globalState.onLightUpdated.add(() => {
  50. this._prepareLights();
  51. });
  52. this._onUpdateRequiredObserver = globalState.onUpdateRequiredObservable.add(() => {
  53. let serializationObject = this._nodeMaterial.serialize();
  54. this._updatePreview(serializationObject);
  55. });
  56. this._onPreviewBackgroundChangedObserver = globalState.onPreviewBackgroundChanged.add(() => {
  57. this._scene.clearColor = this._globalState.backgroundColor;
  58. });
  59. this._onAnimationCommandActivatedObserver = globalState.onAnimationCommandActivated.add(() => {
  60. this._handleAnimations();
  61. });
  62. this._onBackFaceCullingChangedObserver = globalState.onBackFaceCullingChanged.add(() => {
  63. this._material.backFaceCulling = this._globalState.backFaceCulling;
  64. });
  65. this._onDepthPrePassChangedObserver = globalState.onDepthPrePassChanged.add(() => {
  66. this._material.needDepthPrePass = this._globalState.depthPrePass;
  67. });
  68. this._engine = new Engine(targetCanvas, true);
  69. this._scene = new Scene(this._engine);
  70. this._camera = new ArcRotateCamera("Camera", 0, 0.8, 4, Vector3.Zero(), this._scene);
  71. this._camera.lowerRadiusLimit = 3;
  72. this._camera.upperRadiusLimit = 10;
  73. this._camera.wheelPrecision = 20;
  74. this._camera.minZ = 0.1;
  75. this._camera.attachControl(targetCanvas, false);
  76. this._lightParent = new TransformNode("LightParent", this._scene);
  77. this._refreshPreviewMesh();
  78. this._engine.runRenderLoop(() => {
  79. this._engine.resize();
  80. this._scene.render();
  81. });
  82. // let cameraLastRotation = 0;
  83. let lastOffsetX:number | undefined = undefined;
  84. // const lightRotationParallaxSpeed = 0.5;
  85. const lightRotationSpeed = 0.01;
  86. this._scene.onPointerObservable.add(evt => {
  87. if (this._globalState.controlCamera) {
  88. return;
  89. }
  90. if (evt.type === PointerEventTypes.POINTERUP) {
  91. lastOffsetX = undefined;
  92. return;
  93. }
  94. if (evt.event.buttons !== 1) {
  95. return;
  96. }
  97. if (lastOffsetX === undefined) {
  98. lastOffsetX = evt.event.offsetX;
  99. }
  100. var rotateLighting = (lastOffsetX - evt.event.offsetX) * lightRotationSpeed;
  101. this._lightParent.rotation.y += rotateLighting;
  102. lastOffsetX = evt.event.offsetX;
  103. });
  104. // this._scene.registerBeforeRender(() => {
  105. // if (this._camera.alpha === cameraLastRotation) {
  106. // return;
  107. // }
  108. // if (!this._globalState.controlCamera) {
  109. // return;
  110. // }
  111. // var rotateLighting = (this._camera.alpha - cameraLastRotation) * lightRotationParallaxSpeed;
  112. // this._lightParent.rotate(Vector3.Up(), rotateLighting);
  113. // cameraLastRotation = this._camera.alpha;
  114. // });
  115. }
  116. private _handleAnimations() {
  117. this._scene.stopAllAnimations();
  118. if (this._globalState.rotatePreview) {
  119. for (var root of this._scene.rootNodes) {
  120. let transformNode = root as TransformNode;
  121. if (transformNode.getClassName() === "TransformNode" || transformNode.getClassName() === "Mesh" || transformNode.getClassName() === "GroundMesh") {
  122. if (transformNode.rotationQuaternion) {
  123. transformNode.rotation = transformNode.rotationQuaternion.toEulerAngles();
  124. transformNode.rotationQuaternion = null;
  125. }
  126. Animation.CreateAndStartAnimation("turnTable", root, "rotation.y", 60, 1200, transformNode.rotation.y, transformNode.rotation.y + 2 * Math.PI, 1);
  127. }
  128. }
  129. }
  130. }
  131. private _prepareLights() {
  132. // Remove current lights
  133. let currentLights = this._scene.lights.slice(0);
  134. for (var light of currentLights) {
  135. light.dispose();
  136. }
  137. // Create new lights based on settings
  138. if (this._globalState.hemisphericLight) {
  139. new HemisphericLight("Hemispheric light", new Vector3(0, 1, 0), this._scene);
  140. }
  141. if (this._globalState.directionalLight0) {
  142. let dir0 = new DirectionalLight("Directional light #0", new Vector3(0.841626576496605, -0.2193391004130599, -0.49351298337996535), this._scene);
  143. dir0.intensity = 0.9;
  144. dir0.diffuse = new Color3(0.9294117647058824, 0.9725490196078431, 0.996078431372549);
  145. dir0.specular = new Color3(0.9294117647058824, 0.9725490196078431, 0.996078431372549);
  146. dir0.parent = this._lightParent;
  147. }
  148. if (this._globalState.directionalLight1) {
  149. let dir1 = new DirectionalLight("Directional light #1", new Vector3(-0.9519937437504213, -0.24389315636999764, -0.1849974057546125), this._scene);
  150. dir1.intensity = 1.2;
  151. dir1.specular = new Color3(0.9803921568627451, 0.9529411764705882, 0.7725490196078432);
  152. dir1.diffuse = new Color3(0.9803921568627451, 0.9529411764705882, 0.7725490196078432);
  153. dir1.parent = this._lightParent;
  154. }
  155. }
  156. private _prepareMeshes() {
  157. this._prepareLights();
  158. // Framing
  159. this._camera.useFramingBehavior = true;
  160. var framingBehavior = this._camera.getBehaviorByName("Framing") as FramingBehavior;
  161. setTimeout(() => { // Let the behavior activate first
  162. framingBehavior.framingTime = 0;
  163. framingBehavior.elevationReturnTime = -1;
  164. if (this._scene.meshes.length) {
  165. var worldExtends = this._scene.getWorldExtends();
  166. this._camera.lowerRadiusLimit = null;
  167. this._camera.upperRadiusLimit = null;
  168. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  169. }
  170. this._camera.pinchPrecision = 200 / this._camera.radius;
  171. this._camera.upperRadiusLimit = 5 * this._camera.radius;
  172. });
  173. this._camera.wheelDeltaPercentage = 0.01;
  174. this._camera.pinchDeltaPercentage = 0.01;
  175. // Animations
  176. this._handleAnimations();
  177. // Material
  178. let serializationObject = this._nodeMaterial.serialize();
  179. this._updatePreview(serializationObject);
  180. }
  181. private _refreshPreviewMesh() {
  182. if (this._currentType !== this._globalState.previewMeshType || this._currentType === PreviewMeshType.Custom) {
  183. this._currentType = this._globalState.previewMeshType;
  184. if (this._meshes && this._meshes.length) {
  185. for (var mesh of this._meshes) {
  186. mesh.dispose();
  187. }
  188. }
  189. this._meshes = [];
  190. let lights = this._scene.lights.slice(0);
  191. for (var light of lights) {
  192. light.dispose();
  193. }
  194. this._engine.releaseEffects();
  195. SceneLoader.ShowLoadingScreen = false;
  196. this._globalState.onIsLoadingChanged.notifyObservers(true);
  197. switch (this._globalState.previewMeshType) {
  198. case PreviewMeshType.Box:
  199. SceneLoader.AppendAsync("https://models.babylonjs.com/", "roundedCube.glb", this._scene).then(() => {
  200. this._meshes.push(...this._scene.meshes);
  201. this._prepareMeshes();
  202. });
  203. break;
  204. case PreviewMeshType.Sphere:
  205. this._meshes.push(Mesh.CreateSphere("dummy-sphere", 32, 2, this._scene));
  206. break;
  207. case PreviewMeshType.Torus:
  208. this._meshes.push(Mesh.CreateTorus("dummy-torus", 2, 0.5, 32, this._scene));
  209. break;
  210. case PreviewMeshType.Cylinder:
  211. SceneLoader.AppendAsync("https://models.babylonjs.com/", "roundedCylinder.glb", this._scene).then(() => {
  212. this._meshes.push(...this._scene.meshes);
  213. this._prepareMeshes();
  214. });
  215. return;
  216. case PreviewMeshType.Plane:
  217. let plane = Mesh.CreateGround("dummy-plane", 2, 2, 128, this._scene);
  218. plane.scaling.y = -1;
  219. plane.rotation.x = Math.PI;
  220. this._meshes.push(plane);
  221. break;
  222. case PreviewMeshType.ShaderBall:
  223. SceneLoader.AppendAsync("https://models.babylonjs.com/", "shaderBall.glb", this._scene).then(() => {
  224. this._meshes.push(...this._scene.meshes);
  225. this._prepareMeshes();
  226. });
  227. return;
  228. case PreviewMeshType.Custom:
  229. SceneLoader.AppendAsync("file:", this._globalState.previewMeshFile, this._scene).then(() => {
  230. this._meshes.push(...this._scene.meshes);
  231. this._prepareMeshes();
  232. });
  233. return;
  234. }
  235. this._prepareMeshes();
  236. }
  237. }
  238. private _forceCompilationAsync(material: NodeMaterial, mesh: AbstractMesh): Promise<void> {
  239. return material.forceCompilationAsync(mesh);
  240. }
  241. private _updatePreview(serializationObject: any) {
  242. try {
  243. let tempMaterial = NodeMaterial.Parse(serializationObject, this._scene);
  244. tempMaterial.backFaceCulling = this._globalState.backFaceCulling;
  245. tempMaterial.needDepthPrePass = this._globalState.depthPrePass;
  246. if (this._meshes.length) {
  247. let tasks = this._meshes.map(m => this._forceCompilationAsync(tempMaterial, m));
  248. Promise.all(tasks).then(() => {
  249. for (var mesh of this._meshes) {
  250. mesh.material = tempMaterial;
  251. }
  252. if (this._material) {
  253. this._material.dispose();
  254. }
  255. this._material = tempMaterial;
  256. this._globalState.onIsLoadingChanged.notifyObservers(false);
  257. }).catch(reason => {
  258. this._globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Shader compilation error:\r\n" + reason, true));
  259. this._globalState.onIsLoadingChanged.notifyObservers(false);
  260. });
  261. } else {
  262. this._material = tempMaterial;
  263. }
  264. } catch(err) {
  265. // Ignore the error
  266. }
  267. }
  268. public dispose() {
  269. this._nodeMaterial.onBuildObservable.remove(this._onBuildObserver);
  270. this._globalState.onPreviewCommandActivated.remove(this._onPreviewCommandActivatedObserver);
  271. this._globalState.onUpdateRequiredObservable.remove(this._onUpdateRequiredObserver);
  272. this._globalState.onAnimationCommandActivated.remove(this._onAnimationCommandActivatedObserver);
  273. this._globalState.onPreviewBackgroundChanged.remove(this._onPreviewBackgroundChangedObserver);
  274. this._globalState.onBackFaceCullingChanged.remove(this._onBackFaceCullingChangedObserver);
  275. this._globalState.onDepthPrePassChanged.remove(this._onDepthPrePassChangedObserver);
  276. this._globalState.onLightUpdated.remove(this._onLightUpdatedObserver);
  277. if (this._material) {
  278. this._material.dispose();
  279. }
  280. this._camera.dispose();
  281. for (var mesh of this._meshes) {
  282. mesh.dispose();
  283. }
  284. this._scene.dispose();
  285. this._engine.dispose();
  286. }
  287. }