previewManager.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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, Color4 } from 'babylonjs/Maths/math.color';
  21. import { PostProcess } from 'babylonjs/PostProcesses/postProcess';
  22. import { Constants } from 'babylonjs/Engines/constants';
  23. import { CurrentScreenBlock } from 'babylonjs/Materials/Node/Blocks/Dual/currentScreenBlock';
  24. import { NodeMaterialModes } from 'babylonjs/Materials/Node/Enums/nodeMaterialModes';
  25. import { ParticleSystem } from 'babylonjs/Particles/particleSystem';
  26. import { ParticleHelper } from 'babylonjs/Particles/particleHelper';
  27. import { Texture } from 'babylonjs/Materials/Textures/texture';
  28. import { ParticleTextureBlock } from 'babylonjs/Materials/Node/Blocks/Particle/particleTextureBlock';
  29. import { Effect } from 'babylonjs/Materials/effect';
  30. import { FileTools } from 'babylonjs/Misc/fileTools';
  31. export class PreviewManager {
  32. private _nodeMaterial: NodeMaterial;
  33. private _onBuildObserver: Nullable<Observer<NodeMaterial>>;
  34. private _onPreviewCommandActivatedObserver: Nullable<Observer<boolean>>;
  35. private _onAnimationCommandActivatedObserver: Nullable<Observer<void>>;
  36. private _onUpdateRequiredObserver: Nullable<Observer<void>>;
  37. private _onPreviewBackgroundChangedObserver: Nullable<Observer<void>>;
  38. private _onBackFaceCullingChangedObserver: Nullable<Observer<void>>;
  39. private _onDepthPrePassChangedObserver: Nullable<Observer<void>>;
  40. private _onLightUpdatedObserver: Nullable<Observer<void>>;
  41. private _engine: Engine;
  42. private _scene: Scene;
  43. private _meshes: AbstractMesh[];
  44. private _camera: ArcRotateCamera;
  45. private _material: NodeMaterial;
  46. private _globalState: GlobalState;
  47. private _currentType: number;
  48. private _lightParent: TransformNode;
  49. private _postprocess: Nullable<PostProcess>;
  50. private _particleSystem: Nullable<ParticleSystem>;
  51. private _particleSystemDrawObserver: Nullable<Observer<Effect>>;
  52. public constructor(targetCanvas: HTMLCanvasElement, globalState: GlobalState) {
  53. this._nodeMaterial = globalState.nodeMaterial;
  54. this._globalState = globalState;
  55. this._particleSystemDrawObserver = null;
  56. this._onBuildObserver = this._nodeMaterial.onBuildObservable.add((nodeMaterial) => {
  57. let serializationObject = nodeMaterial.serialize();
  58. this._updatePreview(serializationObject);
  59. });
  60. this._onPreviewCommandActivatedObserver = globalState.onPreviewCommandActivated.add((forceRefresh: boolean) => {
  61. if (forceRefresh) {
  62. this._currentType = -1;
  63. }
  64. this._refreshPreviewMesh();
  65. });
  66. this._onLightUpdatedObserver = globalState.onLightUpdated.add(() => {
  67. this._prepareLights();
  68. });
  69. this._onUpdateRequiredObserver = globalState.onUpdateRequiredObservable.add(() => {
  70. let serializationObject = this._nodeMaterial.serialize();
  71. this._updatePreview(serializationObject);
  72. });
  73. this._onPreviewBackgroundChangedObserver = globalState.onPreviewBackgroundChanged.add(() => {
  74. this._scene.clearColor = this._globalState.backgroundColor;
  75. });
  76. this._onAnimationCommandActivatedObserver = globalState.onAnimationCommandActivated.add(() => {
  77. this._handleAnimations();
  78. });
  79. this._onBackFaceCullingChangedObserver = globalState.onBackFaceCullingChanged.add(() => {
  80. this._material.backFaceCulling = this._globalState.backFaceCulling;
  81. });
  82. this._onDepthPrePassChangedObserver = globalState.onDepthPrePassChanged.add(() => {
  83. this._material.needDepthPrePass = this._globalState.depthPrePass;
  84. });
  85. this._engine = new Engine(targetCanvas, true);
  86. this._scene = new Scene(this._engine);
  87. this._scene.clearColor = this._globalState.backgroundColor;
  88. this._camera = new ArcRotateCamera("Camera", 0, 0.8, 4, Vector3.Zero(), this._scene);
  89. this._camera.lowerRadiusLimit = 3;
  90. this._camera.upperRadiusLimit = 10;
  91. this._camera.wheelPrecision = 20;
  92. this._camera.minZ = 0.1;
  93. this._camera.attachControl(targetCanvas, false);
  94. this._lightParent = new TransformNode("LightParent", this._scene);
  95. this._refreshPreviewMesh();
  96. this._engine.runRenderLoop(() => {
  97. this._engine.resize();
  98. this._scene.render();
  99. });
  100. let lastOffsetX: number | undefined = undefined;
  101. const lightRotationSpeed = 0.01;
  102. this._scene.onPointerObservable.add((evt) => {
  103. if (this._globalState.controlCamera) {
  104. return;
  105. }
  106. if (evt.type === PointerEventTypes.POINTERUP) {
  107. lastOffsetX = undefined;
  108. return;
  109. }
  110. if (evt.event.buttons !== 1) {
  111. return;
  112. }
  113. if (lastOffsetX === undefined) {
  114. lastOffsetX = evt.event.offsetX;
  115. }
  116. var rotateLighting = (lastOffsetX - evt.event.offsetX) * lightRotationSpeed;
  117. this._lightParent.rotation.y += rotateLighting;
  118. lastOffsetX = evt.event.offsetX;
  119. });
  120. // this._scene.registerBeforeRender(() => {
  121. // if (this._camera.alpha === cameraLastRotation) {
  122. // return;
  123. // }
  124. // if (!this._globalState.controlCamera) {
  125. // return;
  126. // }
  127. // var rotateLighting = (this._camera.alpha - cameraLastRotation) * lightRotationParallaxSpeed;
  128. // this._lightParent.rotate(Vector3.Up(), rotateLighting);
  129. // cameraLastRotation = this._camera.alpha;
  130. // });
  131. }
  132. private _handleAnimations() {
  133. this._scene.stopAllAnimations();
  134. if (this._globalState.rotatePreview) {
  135. for (var root of this._scene.rootNodes) {
  136. let transformNode = root as TransformNode;
  137. if (transformNode.getClassName() === "TransformNode" || transformNode.getClassName() === "Mesh" || transformNode.getClassName() === "GroundMesh") {
  138. if (transformNode.rotationQuaternion) {
  139. transformNode.rotation = transformNode.rotationQuaternion.toEulerAngles();
  140. transformNode.rotationQuaternion = null;
  141. }
  142. Animation.CreateAndStartAnimation("turnTable", root, "rotation.y", 60, 1200, transformNode.rotation.y, transformNode.rotation.y + 2 * Math.PI, 1);
  143. }
  144. }
  145. }
  146. }
  147. private _prepareLights() {
  148. // Remove current lights
  149. let currentLights = this._scene.lights.slice(0);
  150. for (var light of currentLights) {
  151. light.dispose();
  152. }
  153. // Create new lights based on settings
  154. if (this._globalState.hemisphericLight) {
  155. new HemisphericLight("Hemispheric light", new Vector3(0, 1, 0), this._scene);
  156. }
  157. if (this._globalState.directionalLight0) {
  158. let dir0 = new DirectionalLight("Directional light #0", new Vector3(0.841626576496605, -0.2193391004130599, -0.49351298337996535), this._scene);
  159. dir0.intensity = 0.9;
  160. dir0.diffuse = new Color3(0.9294117647058824, 0.9725490196078431, 0.996078431372549);
  161. dir0.specular = new Color3(0.9294117647058824, 0.9725490196078431, 0.996078431372549);
  162. dir0.parent = this._lightParent;
  163. }
  164. if (this._globalState.directionalLight1) {
  165. let dir1 = new DirectionalLight("Directional light #1", new Vector3(-0.9519937437504213, -0.24389315636999764, -0.1849974057546125), this._scene);
  166. dir1.intensity = 1.2;
  167. dir1.specular = new Color3(0.9803921568627451, 0.9529411764705882, 0.7725490196078432);
  168. dir1.diffuse = new Color3(0.9803921568627451, 0.9529411764705882, 0.7725490196078432);
  169. dir1.parent = this._lightParent;
  170. }
  171. }
  172. private _prepareMeshes() {
  173. if (this._globalState.mode === NodeMaterialModes.Material) {
  174. this._prepareLights();
  175. // Framing
  176. this._camera.useFramingBehavior = true;
  177. var framingBehavior = this._camera.getBehaviorByName("Framing") as FramingBehavior;
  178. setTimeout(() => { // Let the behavior activate first
  179. framingBehavior.framingTime = 0;
  180. framingBehavior.elevationReturnTime = -1;
  181. if (this._scene.meshes.length) {
  182. var worldExtends = this._scene.getWorldExtends();
  183. this._camera.lowerRadiusLimit = null;
  184. this._camera.upperRadiusLimit = null;
  185. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  186. }
  187. this._camera.pinchPrecision = 200 / this._camera.radius;
  188. this._camera.upperRadiusLimit = 5 * this._camera.radius;
  189. });
  190. this._camera.wheelDeltaPercentage = 0.01;
  191. this._camera.pinchDeltaPercentage = 0.01;
  192. // Animations
  193. this._handleAnimations();
  194. }
  195. // Material
  196. let serializationObject = this._nodeMaterial.serialize();
  197. this._updatePreview(serializationObject);
  198. }
  199. private _refreshPreviewMesh() {
  200. if (this._currentType !== this._globalState.previewMeshType || this._currentType === PreviewMeshType.Custom) {
  201. this._currentType = this._globalState.previewMeshType;
  202. if (this._meshes && this._meshes.length) {
  203. for (var mesh of this._meshes) {
  204. mesh.dispose();
  205. }
  206. }
  207. this._meshes = [];
  208. let lights = this._scene.lights.slice(0);
  209. for (var light of lights) {
  210. light.dispose();
  211. }
  212. this._engine.releaseEffects();
  213. if (this._particleSystem) {
  214. if (this._particleSystemDrawObserver) {
  215. this._particleSystem.onBeforeDrawParticlesObservable.remove(this._particleSystemDrawObserver);
  216. }
  217. this._particleSystem.customEffect = null;
  218. this._particleSystem.stop();
  219. this._particleSystem.dispose();
  220. this._particleSystem = null;
  221. this._particleSystemDrawObserver = null;
  222. }
  223. SceneLoader.ShowLoadingScreen = false;
  224. this._globalState.onIsLoadingChanged.notifyObservers(true);
  225. if (this._globalState.mode === NodeMaterialModes.Material) {
  226. switch (this._globalState.previewMeshType) {
  227. case PreviewMeshType.Box:
  228. SceneLoader.AppendAsync("https://models.babylonjs.com/", "roundedCube.glb", this._scene).then(() => {
  229. this._meshes.push(...this._scene.meshes);
  230. this._prepareMeshes();
  231. });
  232. return;
  233. case PreviewMeshType.Sphere:
  234. this._meshes.push(Mesh.CreateSphere("dummy-sphere", 32, 2, this._scene));
  235. break;
  236. case PreviewMeshType.Torus:
  237. this._meshes.push(Mesh.CreateTorus("dummy-torus", 2, 0.5, 32, this._scene));
  238. break;
  239. case PreviewMeshType.Cylinder:
  240. SceneLoader.AppendAsync("https://models.babylonjs.com/", "roundedCylinder.glb", this._scene).then(() => {
  241. this._meshes.push(...this._scene.meshes);
  242. this._prepareMeshes();
  243. });
  244. return;
  245. case PreviewMeshType.Plane:
  246. let plane = Mesh.CreateGround("dummy-plane", 2, 2, 128, this._scene);
  247. plane.scaling.y = -1;
  248. plane.rotation.x = Math.PI;
  249. this._meshes.push(plane);
  250. break;
  251. case PreviewMeshType.ShaderBall:
  252. SceneLoader.AppendAsync("https://models.babylonjs.com/", "shaderBall.glb", this._scene).then(() => {
  253. this._meshes.push(...this._scene.meshes);
  254. this._prepareMeshes();
  255. });
  256. return;
  257. case PreviewMeshType.Custom:
  258. SceneLoader.AppendAsync("file:", this._globalState.previewMeshFile, this._scene).then(() => {
  259. this._meshes.push(...this._scene.meshes);
  260. this._prepareMeshes();
  261. });
  262. return;
  263. }
  264. } else if (this._globalState.mode === NodeMaterialModes.Particle) {
  265. switch (this._globalState.previewMeshType) {
  266. case PreviewMeshType.Bubbles:
  267. this._particleSystem = new ParticleSystem("particles", 4000, this._scene);
  268. this._particleSystem.particleTexture = new Texture("https://assets.babylonjs.com/particles/textures/explosion/Flare.png", this._scene);
  269. this._particleSystem.minSize = 0.1;
  270. this._particleSystem.maxSize = 1.0;
  271. this._particleSystem.minLifeTime = 0.5;
  272. this._particleSystem.maxLifeTime = 5.0;
  273. this._particleSystem.minEmitPower = 0.5;
  274. this._particleSystem.maxEmitPower = 3.0;
  275. this._particleSystem.createBoxEmitter(new Vector3(-1, 1, -1), new Vector3(1, 1, 1), new Vector3(-0.1, -0.1, -0.1), new Vector3(0.1, 0.1, 0.1));
  276. this._particleSystem.emitRate = 100;
  277. this._particleSystem.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  278. this._particleSystem.color1 = new Color4(1, 1, 0, 1);
  279. this._particleSystem.color2 = new Color4(1, 0.5, 0, 1);
  280. this._particleSystem.gravity = new Vector3(0, -1.0, 0);
  281. this._particleSystem.start();
  282. break;
  283. case PreviewMeshType.Explosion:
  284. this._loadParticleSystem("explosion");
  285. return;
  286. case PreviewMeshType.Fire:
  287. this._loadParticleSystem("fire");
  288. return;
  289. case PreviewMeshType.Rain:
  290. this._loadParticleSystem("rain");
  291. return;
  292. case PreviewMeshType.Smoke:
  293. this._loadParticleSystem("smoke");
  294. return;
  295. case PreviewMeshType.Custom:
  296. FileTools.ReadFile(this._globalState.previewMeshFile, (json) => {
  297. this._particleSystem = ParticleSystem.Parse(JSON.parse(json), this._scene, "");
  298. this._particleSystem.start();
  299. this._prepareMeshes();
  300. }, undefined, false, (error) => {
  301. console.log(error);
  302. });
  303. return;
  304. }
  305. }
  306. this._prepareMeshes();
  307. }
  308. }
  309. private _loadParticleSystem(name: string) {
  310. ParticleHelper.CreateAsync(name, this._scene).then((set) => {
  311. for (let i = 1; i < set.systems.length; ++i) {
  312. set.systems[i].dispose();
  313. }
  314. this._particleSystem = set.systems[0] as ParticleSystem;
  315. this._particleSystem.start();
  316. this._prepareMeshes();
  317. });
  318. }
  319. private _forceCompilationAsync(material: NodeMaterial, mesh: AbstractMesh): Promise<void> {
  320. return material.forceCompilationAsync(mesh);
  321. }
  322. private _updatePreview(serializationObject: any) {
  323. try {
  324. let tempMaterial = NodeMaterial.Parse(serializationObject, this._scene);
  325. tempMaterial.backFaceCulling = this._globalState.backFaceCulling;
  326. tempMaterial.needDepthPrePass = this._globalState.depthPrePass;
  327. if (this._postprocess) {
  328. this._postprocess.dispose(this._camera);
  329. this._postprocess = null;
  330. }
  331. switch (this._globalState.mode) {
  332. case NodeMaterialModes.PostProcess: {
  333. this._globalState.onIsLoadingChanged.notifyObservers(false);
  334. this._postprocess = tempMaterial.createPostProcess(this._camera, 1.0, Constants.TEXTURE_NEAREST_SAMPLINGMODE, this._engine);
  335. const currentScreen = tempMaterial.getBlockByPredicate((block) => block instanceof CurrentScreenBlock);
  336. if (currentScreen) {
  337. this._postprocess!.onApplyObservable.add((effect) => {
  338. effect.setTexture("textureSampler", (currentScreen as CurrentScreenBlock).texture);
  339. });
  340. }
  341. if (this._material) {
  342. this._material.dispose();
  343. }
  344. this._material = tempMaterial;
  345. break;
  346. }
  347. case NodeMaterialModes.Particle: {
  348. this._globalState.onIsLoadingChanged.notifyObservers(false);
  349. if (this._particleSystemDrawObserver) {
  350. this._particleSystem.onBeforeDrawParticlesObservable.remove(this._particleSystemDrawObserver);
  351. }
  352. this._particleSystemDrawObserver = this._particleSystem.onBeforeDrawParticlesObservable.add((effect) => {
  353. const textureBlock = tempMaterial.getBlockByPredicate((block) => block instanceof ParticleTextureBlock);
  354. if (textureBlock && (textureBlock as ParticleTextureBlock).texture) {
  355. effect.setTexture("diffuseSampler", (textureBlock as ParticleTextureBlock).texture);
  356. }
  357. });
  358. tempMaterial.createEffectForParticles(this._particleSystem);
  359. break;
  360. }
  361. default: {
  362. if (this._meshes.length) {
  363. let tasks = this._meshes.map((m) => this._forceCompilationAsync(tempMaterial, m));
  364. Promise.all(tasks).then(() => {
  365. for (var mesh of this._meshes) {
  366. mesh.material = tempMaterial;
  367. }
  368. if (this._material) {
  369. this._material.dispose();
  370. }
  371. this._material = tempMaterial;
  372. this._globalState.onIsLoadingChanged.notifyObservers(false);
  373. }).catch((reason) => {
  374. this._globalState.onLogRequiredObservable.notifyObservers(new LogEntry("Shader compilation error:\r\n" + reason, true));
  375. this._globalState.onIsLoadingChanged.notifyObservers(false);
  376. });
  377. } else {
  378. this._material = tempMaterial;
  379. }
  380. break;
  381. }
  382. }
  383. } catch (err) {
  384. // Ignore the error
  385. this._globalState.onIsLoadingChanged.notifyObservers(false);
  386. }
  387. }
  388. public dispose() {
  389. this._nodeMaterial.onBuildObservable.remove(this._onBuildObserver);
  390. this._globalState.onPreviewCommandActivated.remove(this._onPreviewCommandActivatedObserver);
  391. this._globalState.onUpdateRequiredObservable.remove(this._onUpdateRequiredObserver);
  392. this._globalState.onAnimationCommandActivated.remove(this._onAnimationCommandActivatedObserver);
  393. this._globalState.onPreviewBackgroundChanged.remove(this._onPreviewBackgroundChangedObserver);
  394. this._globalState.onBackFaceCullingChanged.remove(this._onBackFaceCullingChangedObserver);
  395. this._globalState.onDepthPrePassChanged.remove(this._onDepthPrePassChangedObserver);
  396. this._globalState.onLightUpdated.remove(this._onLightUpdatedObserver);
  397. if (this._material) {
  398. this._material.dispose();
  399. }
  400. this._camera.dispose();
  401. for (var mesh of this._meshes) {
  402. mesh.dispose();
  403. }
  404. this._scene.dispose();
  405. this._engine.dispose();
  406. }
  407. }