renderingZone.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import * as React from "react";
  2. import { GlobalState } from "../globalState";
  3. import { Engine } from "babylonjs/Engines/engine";
  4. import { SceneLoader } from "babylonjs/Loading/sceneLoader";
  5. import { GLTFFileLoader } from "babylonjs-loaders/glTF/glTFFileLoader";
  6. import { Scene } from "babylonjs/scene";
  7. import { Vector3 } from "babylonjs/Maths/math.vector";
  8. import { ArcRotateCamera } from "babylonjs/Cameras/arcRotateCamera";
  9. import { FramingBehavior } from "babylonjs/Behaviors/Cameras/framingBehavior";
  10. import { EnvironmentTools } from "../tools/environmentTools";
  11. import { Tools } from "babylonjs/Misc/tools";
  12. import { FilesInput } from "babylonjs/Misc/filesInput";
  13. import { Animation } from "babylonjs/Animations/animation";
  14. import { PBRBaseMaterial, PBRMaterial, StringTools, Texture } from "babylonjs";
  15. import { Mesh } from "babylonjs/Meshes/mesh";
  16. require("../scss/renderingZone.scss");
  17. interface IRenderingZoneProps {
  18. globalState: GlobalState;
  19. assetUrl?: string;
  20. cameraPosition?: Vector3;
  21. expanded: boolean;
  22. }
  23. function isTextureAsset(name: string): boolean {
  24. return (
  25. StringTools.EndsWith(name, ".ktx") ||
  26. StringTools.EndsWith(name, ".ktx2") ||
  27. StringTools.EndsWith(name, ".png") ||
  28. StringTools.EndsWith(name, ".jpg") ||
  29. StringTools.EndsWith(name, ".jpeg")
  30. );
  31. }
  32. export class RenderingZone extends React.Component<IRenderingZoneProps> {
  33. private _currentPluginName?: string;
  34. private _engine: Engine;
  35. private _scene: Scene;
  36. private _canvas: HTMLCanvasElement;
  37. public constructor(props: IRenderingZoneProps) {
  38. super(props);
  39. }
  40. initEngine() {
  41. this._canvas = document.getElementById("renderCanvas") as HTMLCanvasElement;
  42. this._engine = new Engine(this._canvas, true, { premultipliedAlpha: false, preserveDrawingBuffer: true });
  43. this._engine.loadingUIBackgroundColor = "#2A2342";
  44. // Resize
  45. window.addEventListener("resize", () => {
  46. this._engine.resize();
  47. });
  48. this.loadAsset();
  49. // File inputs
  50. let filesInput = new FilesInput(
  51. this._engine,
  52. null,
  53. (sceneFile: File, scene: Scene) => {
  54. this._scene = scene;
  55. this.onSceneLoaded(sceneFile.name);
  56. },
  57. null,
  58. null,
  59. null,
  60. () => {
  61. Tools.ClearLogCache();
  62. if (this._scene) {
  63. this.props.globalState.isDebugLayerEnabled = this.props.globalState.currentScene.debugLayer.isVisible();
  64. if (this.props.globalState.isDebugLayerEnabled) {
  65. this._scene.debugLayer.hide();
  66. }
  67. }
  68. },
  69. null,
  70. (file, scene, message) => {
  71. this.props.globalState.onError.notifyObservers({ message: message });
  72. }
  73. );
  74. filesInput.onProcessFileCallback = (file, name, extension, setSceneFileToLoad) => {
  75. if (filesInput.filesToLoad && filesInput.filesToLoad.length === 1 && extension) {
  76. switch (extension.toLowerCase()) {
  77. case "dds":
  78. case "env":
  79. case "hdr": {
  80. FilesInput.FilesToLoad[name] = file;
  81. EnvironmentTools.SkyboxPath = "file:" + (file as any).correctName;
  82. return false;
  83. }
  84. default: {
  85. if (isTextureAsset(name)) {
  86. setSceneFileToLoad(file);
  87. }
  88. break;
  89. }
  90. }
  91. }
  92. return true;
  93. };
  94. filesInput.loadAsync = (sceneFile, onProgress) => {
  95. const filesToLoad = filesInput.filesToLoad;
  96. if (filesToLoad.length === 1) {
  97. const fileName = (filesToLoad[0] as any).correctName;
  98. if (isTextureAsset(fileName)) {
  99. return Promise.resolve(this.loadTextureAsset(`file:${fileName}`));
  100. }
  101. }
  102. return SceneLoader.LoadAsync("file:", sceneFile, this._engine, onProgress);
  103. };
  104. filesInput.monitorElementForDragNDrop(this._canvas);
  105. this.props.globalState.filesInput = filesInput;
  106. window.addEventListener("keydown", (event) => {
  107. // Press R to reload
  108. if (event.keyCode === 82 && event.target && (event.target as HTMLElement).nodeName !== "INPUT" && this._scene) {
  109. if (this.props.assetUrl) {
  110. this.loadAssetFromUrl();
  111. } else {
  112. filesInput.reload();
  113. }
  114. }
  115. });
  116. }
  117. prepareCamera() {
  118. let camera: ArcRotateCamera;
  119. // Attach camera to canvas inputs
  120. if (!this._scene.activeCamera || this._scene.lights.length === 0) {
  121. this._scene.createDefaultCamera(true);
  122. camera = this._scene.activeCamera! as ArcRotateCamera;
  123. if (this.props.cameraPosition) {
  124. camera.setPosition(this.props.cameraPosition);
  125. } else {
  126. if (this._currentPluginName === "gltf") {
  127. // glTF assets use a +Z forward convention while the default camera faces +Z. Rotate the camera to look at the front of the asset.
  128. camera.alpha += Math.PI;
  129. }
  130. // Enable camera's behaviors
  131. camera.useFramingBehavior = true;
  132. var framingBehavior = camera.getBehaviorByName("Framing") as FramingBehavior;
  133. framingBehavior.framingTime = 0;
  134. framingBehavior.elevationReturnTime = -1;
  135. if (this._scene.meshes.length) {
  136. camera.lowerRadiusLimit = null;
  137. var worldExtends = this._scene.getWorldExtends(function (mesh) {
  138. return mesh.isVisible && mesh.isEnabled();
  139. });
  140. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  141. }
  142. }
  143. camera.pinchPrecision = 200 / camera.radius;
  144. camera.upperRadiusLimit = 5 * camera.radius;
  145. camera.wheelDeltaPercentage = 0.01;
  146. camera.pinchDeltaPercentage = 0.01;
  147. }
  148. this._scene.activeCamera!.attachControl();
  149. }
  150. handleErrors() {
  151. // In case of error during loading, meshes will be empty and clearColor is set to red
  152. if (this._scene.meshes.length === 0 && this._scene.clearColor.r === 1 && this._scene.clearColor.g === 0 && this._scene.clearColor.b === 0) {
  153. this._canvas.style.opacity = "0";
  154. this.props.globalState.onError.notifyObservers({ scene: this._scene, message: "No mesh found in your scene" });
  155. } else {
  156. if (Tools.errorsCount > 0) {
  157. this.props.globalState.onError.notifyObservers({ scene: this._scene, message: "Scene loaded but several errors were found" });
  158. }
  159. // this._canvas.style.opacity = "1";
  160. let camera = this._scene.activeCamera! as ArcRotateCamera;
  161. if (camera.keysUp) {
  162. camera.keysUp.push(90); // Z
  163. camera.keysUp.push(87); // W
  164. camera.keysDown.push(83); // S
  165. camera.keysLeft.push(65); // A
  166. camera.keysLeft.push(81); // Q
  167. camera.keysRight.push(69); // E
  168. camera.keysRight.push(68); // D
  169. }
  170. }
  171. }
  172. prepareLighting() {
  173. if (this._currentPluginName === "gltf") {
  174. if (!this._scene.environmentTexture) {
  175. this._scene.environmentTexture = EnvironmentTools.LoadSkyboxPathTexture(this._scene);
  176. }
  177. if (this._scene.environmentTexture) {
  178. this._scene.createDefaultSkybox(this._scene.environmentTexture, true, (this._scene.activeCamera!.maxZ - this._scene.activeCamera!.minZ) / 2, 0.3, false);
  179. }
  180. } else {
  181. var pbrPresent = false;
  182. for (const material of this._scene.materials) {
  183. if (material instanceof PBRBaseMaterial) {
  184. pbrPresent = true;
  185. break;
  186. }
  187. }
  188. if (pbrPresent) {
  189. if (!this._scene.environmentTexture) {
  190. this._scene.environmentTexture = EnvironmentTools.LoadSkyboxPathTexture(this._scene);
  191. }
  192. } else {
  193. this._scene.createDefaultLight();
  194. }
  195. }
  196. }
  197. onSceneLoaded(filename: string) {
  198. this._engine.clearInternalTexturesCache();
  199. this._scene.skipFrustumClipping = true;
  200. this.props.globalState.onSceneLoaded.notifyObservers({ scene: this._scene, filename: filename });
  201. this.prepareCamera();
  202. this.prepareLighting();
  203. this.handleErrors();
  204. if (this.props.globalState.isDebugLayerEnabled) {
  205. this.props.globalState.showDebugLayer();
  206. }
  207. delete this._currentPluginName;
  208. }
  209. loadTextureAsset(url: string): Scene {
  210. const scene = new Scene(this._engine);
  211. const plane = Mesh.CreatePlane("plane", 1, scene);
  212. const texture = new Texture(url, scene, undefined, undefined, Texture.NEAREST_LINEAR, () => {
  213. const size = texture.getBaseSize();
  214. if (size.width > size.height) {
  215. plane.scaling.y = size.height / size.width;
  216. } else {
  217. plane.scaling.x = size.width / size.height;
  218. }
  219. texture.gammaSpace = true;
  220. texture.hasAlpha = true;
  221. texture.wrapU = Texture.CLAMP_ADDRESSMODE;
  222. texture.wrapV = Texture.CLAMP_ADDRESSMODE;
  223. scene.debugLayer.show();
  224. scene.debugLayer.select(texture, "PREVIEW");
  225. }, (message, exception) => {
  226. this.props.globalState.onError.notifyObservers({ scene: scene, message: message || exception.message || "Failed to load texture" });
  227. });
  228. const material = new PBRMaterial("unlit", scene);
  229. material.unlit = true;
  230. material.albedoTexture = texture;
  231. material.alphaMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;
  232. plane.material = material;
  233. return scene;
  234. }
  235. loadAssetFromUrl() {
  236. const assetUrl = this.props.assetUrl!;
  237. const rootUrl = Tools.GetFolderPath(assetUrl);
  238. const fileName = Tools.GetFilename(assetUrl);
  239. const promise = isTextureAsset(assetUrl)
  240. ? Promise.resolve(this.loadTextureAsset(assetUrl))
  241. : SceneLoader.LoadAsync(rootUrl, fileName, this._engine);
  242. promise
  243. .then((scene) => {
  244. if (this._scene) {
  245. this._scene.dispose();
  246. }
  247. this._scene = scene;
  248. this.onSceneLoaded(fileName);
  249. scene.whenReadyAsync().then(() => {
  250. this._engine.runRenderLoop(() => {
  251. scene.render();
  252. });
  253. });
  254. })
  255. .catch((reason) => {
  256. this.props.globalState.onError.notifyObservers({ message: reason.message });
  257. });
  258. }
  259. loadAsset() {
  260. if (this.props.assetUrl) {
  261. this.loadAssetFromUrl();
  262. return;
  263. }
  264. }
  265. componentDidMount() {
  266. if (!Engine.isSupported()) {
  267. return;
  268. }
  269. Engine.ShadersRepository = "/src/Shaders/";
  270. // This is really important to tell Babylon.js to use decomposeLerp and matrix interpolation
  271. Animation.AllowMatricesInterpolation = true;
  272. // Setting up some GLTF values
  273. GLTFFileLoader.IncrementalLoading = false;
  274. SceneLoader.OnPluginActivatedObservable.add((plugin) => {
  275. this._currentPluginName = plugin.name;
  276. if (this._currentPluginName === "gltf") {
  277. (plugin as GLTFFileLoader).onValidatedObservable.add((results) => {
  278. if (results.issues.numErrors > 0) {
  279. this.props.globalState.showDebugLayer();
  280. }
  281. });
  282. }
  283. });
  284. this.initEngine();
  285. }
  286. shouldComponentUpdate(nextProps: IRenderingZoneProps) {
  287. if (nextProps.expanded !== this.props.expanded) {
  288. setTimeout(() => this._engine.resize());
  289. return true;
  290. }
  291. return false;
  292. }
  293. public render() {
  294. return (
  295. <div id="canvasZone" className={this.props.expanded ? "expanded" : ""}>
  296. <canvas id="renderCanvas" touch-action="none" onContextMenu={(evt) => evt.preventDefault()}></canvas>
  297. </div>
  298. );
  299. }
  300. }