previewManager.ts 25 KB

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