diff --git a/content/communityExtensions/Babylon.js+ExternalLibraries/BabylonJS_and_VRM.md b/content/communityExtensions/Babylon.js+ExternalLibraries/BabylonJS_and_VRM.md index 6a3958b53..5fed7584b 100644 --- a/content/communityExtensions/Babylon.js+ExternalLibraries/BabylonJS_and_VRM.md +++ b/content/communityExtensions/Babylon.js+ExternalLibraries/BabylonJS_and_VRM.md @@ -72,7 +72,7 @@ import * as BABYLON from "@babylonjs/core"; import "babylon-vrm-loader"; // vrmFile is File object retrieved by . -const scene = await BABYLON.SceneLoader.LoadAsync("file:", vrmFile, engine); +const scene = await BABYLON.LoadSceneAsync("file:" + vrmFile, engine); const vrmManager = scene.metadata.vrmManagers[0]; // Update secondary animation diff --git a/content/communityExtensions/editor/workspace/renamingScene.md b/content/communityExtensions/editor/workspace/renamingScene.md index 20b998283..231194bc3 100644 --- a/content/communityExtensions/editor/workspace/renamingScene.md +++ b/content/communityExtensions/editor/workspace/renamingScene.md @@ -1,6 +1,6 @@ --- title: Renaming a scene -image: +image: description: Understanding how to rename a scene keywords: editor, workspace, project, scene further-reading: @@ -13,29 +13,33 @@ video-content: To rename a scene, just go to the `Assets Browser` panel and rename the scene file by double-clicking its name. Once accepted, the following folders will be renamed: -- *`workspacePath`/projects/`oldname`* -> *`workspacePath`/projects/`newname`* -- *`workspacePath`/scenes/`oldname`* -> *`workspacePath`/scenes/`newname`* + +- _`workspacePath`/projects/`oldname`_ -> _`workspacePath`/projects/`newname`_ +- _`workspacePath`/scenes/`oldname`_ -> _`workspacePath`/scenes/`newname`_ Scene names must be unique. In case the folders already exists (in other words, if the scene already exists) then the operation is aborted. ## Renaming paths in loaders in sources + Paths to scenes being loaded in the code must have their paths updated. For example: + ```typescript const rootUrl = "./scenes/oldName/"; -SceneLoader.Append(rootUrl, "scene.babylon", this.scene, () => { - ... +AppendSceneAsync(rootUrl + "scene.babylon", this.scene, () => { + // ... }); ``` should be renamed to: + ```typescript const rootUrl = "./scenes/newName/"; -SceneLoader.Append(rootUrl, "scene.babylon", this.scene, () => { - ... +AppendSceneAsync(rootUrl + "scene.babylon", this.scene, () => { + // ... }); -``` \ No newline at end of file +``` diff --git a/content/communityExtensions/mmdLoader.md b/content/communityExtensions/mmdLoader.md index 391ea8bc3..1e4ceb3d4 100644 --- a/content/communityExtensions/mmdLoader.md +++ b/content/communityExtensions/mmdLoader.md @@ -79,10 +79,10 @@ await new Promise((resolve) => { ```typescript import "babylon-mmd/esm/Loader/pmxLoader"; // side effect import -const mmdMesh = await SceneLoader.ImportMeshAsync(undefined, "your_model_path.pmx", undefined, scene).then((result) => result.meshes[0]); +const mmdMesh = await ImportMeshAsync("your_model_path.pmx", scene).then((result) => result.meshes[0]); ``` -load PMX model by `SceneLoader.ImportMeshAsync` always returns a 1-length array, so you can get the mesh by `result.meshes[0]`. +load PMX model by `ImportMeshAsync` always returns a 1-length array, so you can get the mesh by `result.meshes[0]`. ### Import VMD Motion diff --git a/content/contribute/toBabylon/HowToContribute.md b/content/contribute/toBabylon/HowToContribute.md index e9543f024..85c6f2e8d 100644 --- a/content/contribute/toBabylon/HowToContribute.md +++ b/content/contribute/toBabylon/HowToContribute.md @@ -724,7 +724,7 @@ This is an extended example of how to use the dev host to integrate GUI, Loaders import { canvas, engine } from "./index"; import "@dev/loaders"; import { Inspector } from "@dev/inspector"; -import { ArcRotateCamera, CubeTexture, Scene, SceneLoader } from "@dev/core"; +import { ArcRotateCamera, CubeTexture, Scene, AppendSceneAsync } from "@dev/core"; import { AdvancedDynamicTexture, Button } from "@dev/gui"; export const createScene = async function () { @@ -734,7 +734,7 @@ export const createScene = async function () { scene.createDefaultSkybox(hdrTexture, true, 10000); // The first parameter can be used to specify which mesh to import. Here we import all meshes - SceneLoader.AppendAsync("https://assets.babylonjs.com/meshes/webp/", "webp.gltf", scene, function (_newMeshes) { + AppendSceneAsync("https://assets.babylonjs.com/meshes/webp/webp.gltf", scene).then((result) => { scene.activeCamera!.attachControl(canvas, false); // scene.activeCamera!.alpha += Math.PI; // camera +180° (scene.activeCamera as ArcRotateCamera).radius = 80; diff --git a/content/features/featuresDeepDive/Exporters/Blender.md b/content/features/featuresDeepDive/Exporters/Blender.md index 0e5759698..896075d5a 100644 --- a/content/features/featuresDeepDive/Exporters/Blender.md +++ b/content/features/featuresDeepDive/Exporters/Blender.md @@ -185,19 +185,19 @@ In `sources`, we have our master scene, with only static objects (on the layer 1 Once exported, you can see in `BJS/index.html` that we create our main scene using this `.babylon`: line 36 -```html -BABYLON.SceneLoader.Load("", "01.master-static-scene.babylon", engine, function (scene) { }); +```javascript +BABYLON.LoadSceneAsync("01.master-static-scene.babylon", engine).then(function (scene) {}); ``` Same way for out animated object in `sources/02.classic-animation.blend`: layer 1 is for our object, layer 6 is just for us to see the main scene in our _.blend_. _Export only selected layers_ is used to help us exporting only the first layer to babylon. Once exported, we can import our meshes inside the onSuccess of our Loader above. Check on `BJS/index.html`, line 64: -```html -BABYLON.SceneLoader.ImportMesh("", "", "02.classic-animation.babylon", scene, function (importedMeshes){ }); +```javascript +BABYLON.ImportMeshAsync("02.classic-animation.babylon", scene).then(function (result) {}); ``` -Now, you already have a basic scene with animations autoplaying in it. +Now, you already have a basic scene with animations auto-playing in it. ### Armatures @@ -259,7 +259,7 @@ Let's say you have exported your first scene. In this example we will use [blend const engine = new BABYLON.Engine(canvas, true); // here the doc for Load function: //doc.babylonjs.com/typedoc/classes/babylon.sceneloader#load - BABYLON.SceneLoader.Load("", "babylonJS_logo_v3.babylon", engine, function (scene) { + BABYLON.LoadSceneAsync("babylonJS_logo_v3.babylon", engine).then(function (scene) { //as this .babylon example hasn't camera in it, we have to create one const camera = new BABYLON.ArcRotateCamera("Camera", 1, 1, 4, BABYLON.Vector3.Zero(), scene); camera.attachControl(canvas, false); @@ -286,5 +286,3 @@ Let's say you have exported your first scene. In this example we will use [blend - some browsers may not want loading the scene, for some security issues (e.g.: Chrome). In this case, you have to open the html file through a webserver (local or not), or try into another browser (e.g.: Firefox, Edge). ![blender babylon scene loaded in BJS](/img/exporters/blender/babylon/babylon-loaded.png) - -#### Animated object diff --git a/content/features/featuresDeepDive/Exporters/Blender_to_glTF.md b/content/features/featuresDeepDive/Exporters/Blender_to_glTF.md index 57074b095..4b430cb18 100644 --- a/content/features/featuresDeepDive/Exporters/Blender_to_glTF.md +++ b/content/features/featuresDeepDive/Exporters/Blender_to_glTF.md @@ -82,7 +82,7 @@ Let's say you have exported [WaterBottle.glb](https://github.com/KhronosGroup/gl const engine = new BABYLON.Engine(canvas, true); // here the doc for Load function: //doc.babylonjs.com/api/classes/babylon.sceneloader#load - BABYLON.SceneLoader.Load("", "WaterBottle.glb", engine, function (scene) { + BABYLON.LoadSceneAsync("WaterBottle.glb", engine).then(function (scene) { scene.createDefaultCamera(true, true, true); scene.createDefaultEnvironment({ createGround: false, diff --git a/content/features/featuresDeepDive/animation/animatedCharacter.md b/content/features/featuresDeepDive/animation/animatedCharacter.md index f0c1476cb..1bd7dadb1 100644 --- a/content/features/featuresDeepDive/animation/animatedCharacter.md +++ b/content/features/featuresDeepDive/animation/animatedCharacter.md @@ -70,8 +70,9 @@ The result is exported as a .GLB file and the animation information can be seen The model can be loaded using the [**ImportMesh**](/typedoc/classes/babylon.sceneloader#importmesh) method of the SceneLoader class and making sure to add the animationGroups parameter as it is used to get and play the animations. ```javascript -BABYLON.SceneLoader.ImportMesh("", "https://assets.babylonjs.com/meshes/", "HVGirl.glb", scene, function (newMeshes, particleSystems, skeletons, animationGroups) { - const hero = newMeshes[0]; +// Load hero character and play animation +BABYLON.ImportMeshAsync("https://assets.babylonjs.com/meshes/HVGirl.glb", scene).then(function (result) { + var hero = result.meshes[0]; //Scale the model down hero.scaling.scaleInPlace(0.1); @@ -87,7 +88,7 @@ BABYLON.SceneLoader.ImportMesh("", "https://assets.babylonjs.com/meshes/", "HVGi }); ``` - + The names of the AnimationGroups can be found in the Sandbox via the Inspector, by loading the model and selecting the Animation Group in the Scene Explorer. diff --git a/content/features/featuresDeepDive/animation/baked_texture_animations.md b/content/features/featuresDeepDive/animation/baked_texture_animations.md index 0a849b76f..7677b01b3 100644 --- a/content/features/featuresDeepDive/animation/baked_texture_animations.md +++ b/content/features/featuresDeepDive/animation/baked_texture_animations.md @@ -22,7 +22,7 @@ The `VertexAnimationBaker` class generates a texture for you given the animation let baker = null, mesh = null; const animationRanges = [{ from: 1, to: 20, name: "My animation" }]; -BABYLON.SceneLoader.ImportMeshAsync("", "https://raw.githubusercontent.com/RaggarDK/Baby/baby/", "arr.babylon", scene, undefined) +BABYLON.ImportMeshAsync("https://raw.githubusercontent.com/RaggarDK/Baby/baby/arr.babylon", scene, undefined) .then((importResult) => { mesh = importResult.meshes[0]; // create the baker helper, so we can generate the texture @@ -58,7 +58,7 @@ BABYLON.SceneLoader.ImportMeshAsync("", "https://raw.githubusercontent.com/Ragga Here's an example for a single mesh: - + ## VATs for instances @@ -107,7 +107,7 @@ Baking the texture can be a slow process, and will play the entire animation vis let baker = null, mesh = null; const animationRanges = [{ from: 1, to: 20, name: "My animation" }]; -BABYLON.SceneLoader.ImportMeshAsync("", "http://example.com", "arr.babylon", scene, undefined) +BABYLON.ImportMeshAsync("http://example.com/arr.babylon", scene, undefined) .then((importResult) => { mesh = importResult.meshes[0]; // create the baker helper, so we can generate the texture @@ -134,7 +134,7 @@ let baker = null, const animationRanges = [{ from: 1, to: 20, name: "My animation" }]; // read your mesh like always -BABYLON.SceneLoader.ImportMeshAsync("", "http://example.com", "arr.babylon", scene, undefined) +BABYLON.ImportMeshAsync("http://example.com/arr.babylon", scene, undefined) .then((importResult) => { mesh = importResult.meshes[0]; // read the vertex data file. diff --git a/content/features/featuresDeepDive/audio/v1/playingSoundsMusic.md b/content/features/featuresDeepDive/audio/v1/playingSoundsMusic.md index 7e748e736..f40fee96b 100644 --- a/content/features/featuresDeepDive/audio/v1/playingSoundsMusic.md +++ b/content/features/featuresDeepDive/audio/v1/playingSoundsMusic.md @@ -431,30 +431,22 @@ Here is a simple sample loading a _.babylon_ scene file embedding some sounds: ```javascript const canvas = document.getElementById("renderCanvas"); const engine = new BABYLON.Engine(canvas, true); -BABYLON.SceneLoader.Load( - "TestScene/", - "testsound.babylon", - engine, - function (newScene) { - newScene.executeWhenReady(function () { - newScene.activeCamera.attachControl(canvas); - - const gunshotSound = newScene.getSoundByName("gunshot-1.wav"); - window.addEventListener("keydown", function (evt) { - if (evt.keyCode === 32 && gunshotSound) { - gunshotSound.play(); - } - }); - - engine.runRenderLoop(function () { - newScene.render(); - }); +BABYLON.LoadSceneAsync("TestScene/testsound.babylon", engine).then(function (newScene) { + newScene.executeWhenReady(function () { + newScene.activeCamera.attachControl(canvas); + + const gunshotSound = newScene.getSoundByName("gunshot-1.wav"); + window.addEventListener("keydown", function (evt) { + if (evt.keyCode === 32 && gunshotSound) { + gunshotSound.play(); + } }); - }, - function (progress) { - // To do: give progress feedback to user - }, -); + + engine.runRenderLoop(function () { + newScene.render(); + }); + }); +}); ``` Pressing the spacebar will play the gunshot sound. diff --git a/content/features/featuresDeepDive/cameras/camera_introduction.md b/content/features/featuresDeepDive/cameras/camera_introduction.md index 8863fe4e1..034131425 100644 --- a/content/features/featuresDeepDive/cameras/camera_introduction.md +++ b/content/features/featuresDeepDive/cameras/camera_introduction.md @@ -251,7 +251,7 @@ function startGame() { const canvas = document.getElementById("renderCanvas"); const engine = new BABYLON.Engine(canvas, true); - BABYLON.SceneLoader.Load("Espilit/", "Espilit.babylon", engine, function (newScene) { + BABYLON.LoadSceneAsync("Espilit/Espilit.babylon", engine).then(function (newScene) { const VJC = new BABYLON.VirtualJoysticksCamera("VJC", newScene.activeCamera.position, newScene); VJC.rotation = newScene.activeCamera.rotation; @@ -268,9 +268,7 @@ function startGame() { newScene.render(); }), }), - }, function (progress) { - // To do: give progress feedback to user. - }), + });, } } ``` diff --git a/content/features/featuresDeepDive/events/promises.md b/content/features/featuresDeepDive/events/promises.md index a4b071979..a5916c284 100644 --- a/content/features/featuresDeepDive/events/promises.md +++ b/content/features/featuresDeepDive/events/promises.md @@ -23,12 +23,12 @@ Regarding portability, Babylon.js provides a custom polyfill for browsers where ### Basic usage ```javascript -BABYLON.SceneLoader.LoadAssetContainerAsync("https://playground.babylonjs.com/scenes/", "skull.babylon", scene).then(function (container) { +BABYLON.LoadAssetContainerAsync("https://playground.babylonjs.com/scenes/skull.babylon", scene).then(function (container) { container.addAllToScene(); }); ``` - + ### Chaining multiple promises together @@ -37,7 +37,7 @@ const scene = new BABYLON.Scene(engine); const xrPromise = scene.createDefaultXRExperienceAsync(); xrPromise .then((xrExperience) => { - return BABYLON.SceneLoader.AppendAsync("https://playground.babylonjs.com/scenes/", "skull.babylon", scene); + return BABYLON.AppendSceneAsync("https://playground.babylonjs.com/scenes/skull.babylon", scene); }) .then(function () { // xr resolved, skull added to the scene @@ -51,10 +51,8 @@ Note: This is not supported in all browsers ```javascript const main = async function () { const scene = new BABYLON.Scene(engine); - const helper = scene.createDefaultVRExperience(); - const supported = await helper.webVRCamera.useStandingMatrixAsync(); - console.log(supported); - await BABYLON.SceneLoader.AppendAsync("https://playground.babylonjs.com/scenes/", "skull.babylon", scene); + const xrPromise = await scene.createDefaultXRExperienceAsync(); + return BABYLON.AppendSceneAsync("https://playground.babylonjs.com/scenes/skull.babylon", scene); }; ``` @@ -66,10 +64,10 @@ const scene = new BABYLON.Scene(engine); const baseUrl = "https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/"; Promise.all([ - BABYLON.SceneLoader.ImportMeshAsync(null, baseUrl + "BoomBox/glTF/", "BoomBox.gltf", scene).then(function (result) { + BABYLON.ImportMeshAsync(baseUrl + "BoomBox/glTF/BoomBox.gltf", scene).then(function (result) { result.meshes[0].position.x = 0.01; }), - BABYLON.SceneLoader.ImportMeshAsync(null, baseUrl + "Avocado/glTF/", "Avocado.gltf", scene).then(function (result) { + BABYLON.ImportMeshAsync(baseUrl + "Avocado/glTF/Avocado.gltf", scene).then(function (result) { result.meshes[0].position.x = -0.01; result.meshes[0].position.y = -0.01; result.meshes[0].scaling.scaleInPlace(0.25); @@ -80,4 +78,4 @@ Promise.all([ }); ``` - + diff --git a/content/features/featuresDeepDive/importers/glTF/progressiveglTFLoad.md b/content/features/featuresDeepDive/importers/glTF/progressiveglTFLoad.md index a2be1a782..ec67cd32e 100644 --- a/content/features/featuresDeepDive/importers/glTF/progressiveglTFLoad.md +++ b/content/features/featuresDeepDive/importers/glTF/progressiveglTFLoad.md @@ -44,11 +44,9 @@ BABYLON.SceneLoader.OnPluginActivatedObservable.addOnce(function (loader) { When loading large assets either using loose files or with range requests, it is useful to show the download progress. Progress is supported through the progress callback of `BABYLON.SceneLoader` methods which is a small subset of the HTTP request [progress event](https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent). Here is an example from the demo above: ```javascript -BABYLON.SceneLoader.AppendAsync( - url, - undefined, - scene, - function (event) { +BABYLON.AppendSceneAsync(url, scene, { + pluginExtension: ".glb", + onProgress: function (event) { // Compute the percentage for each stage unless the length is not computable. // The lengthComputable is often false when serving content that is gzipped. const percentage = event.lengthComputable ? " " + Math.floor((event.loaded / event.total) * 100) + "%" : ""; @@ -65,8 +63,7 @@ BABYLON.SceneLoader.AppendAsync( bottomLine.text = "Loading '" + lodNames[lodNext] + "' LOD..." + percentage; } }, - ".glb", -); +}); ``` ## Key Notes @@ -80,15 +77,15 @@ It is useful to stop at a specific LOD to inspect the results. This can be achie ```javascript BABYLON.SceneLoader.OnPluginActivatedObservable.addOnce(function (loader) { - if (loader.name === "gltf") { - loader.onExtensionLoadedObservable.add(function (extension) { - if (extension.name === "MSFT_lod") { - // Stop at the first LOD. - extension.maxLODsToLoad = 1; - } - } - } -} + if (loader.name === "gltf") { + loader.onExtensionLoadedObservable.add(function (extension) { + if (extension.name === "MSFT_lod") { + // Stop at the first LOD. + extension.maxLODsToLoad = 1; + } + }); + } +}); ``` ## Enabling Logging diff --git a/content/features/featuresDeepDive/importers/legacy.md b/content/features/featuresDeepDive/importers/legacy.md index 15ea55a02..2f0298195 100644 --- a/content/features/featuresDeepDive/importers/legacy.md +++ b/content/features/featuresDeepDive/importers/legacy.md @@ -5,28 +5,28 @@ Once the plugin is referenced, the SceneLoader class can be used which provides Loads all babylon assets from the file and appends them to the scene ```javascript -BABYLON.SceneLoader.Append("./", "duck.gltf", scene, function (scene) { +BABYLON.AppendSceneAsync("duck.gltf", scene).then(function () { // do something with the scene }); ``` -See an example here: +See an example here: Loads all babylon assets from a string and appends them to the scene ```javascript -BABYLON.SceneLoader.Append("", "data:" + gltfString, scene, function (scene) { +BABYLON.AppendSceneAsync("data:" + gltfString, scene).then(function () { // do something with the scene }); ``` -See an example here: +See an example here: You can also load a .glb binary file from a data string as long as the binary data is base64 encoded: ```javascript const base64_model_content = "data:;base64,BASE 64 ENCODED DATA..."; -BABYLON.SceneLoader.Append("", base64_model_content, scene, function (scene) { +BABYLON.AppendSceneAsync(base64_model_content, scene).then(function () { // do something with the scene }); ``` @@ -38,20 +38,22 @@ const base64_model_content = "data:application/octet-stream;base64,-BASE 64 ENCO const base64_model_content = "data:model/gltf-binary;base64,-BASE 64 ENCODED DATA-"; ``` -See an example here: +See an example here: -## SceneLoader.Load +## LoadSceneAsync Loads all babylon assets from the file and creates a new scene ```javascript -BABYLON.SceneLoader.Load("/assets/", "batman.obj", engine, function (scene) { +BABYLON.LoadSceneAsync("/assets/", "batman.obj", engine).then(function (scene) { // do something with the scene }); ``` ## SceneLoader.ImportMesh +Note: This function is deprecated. Use the `ImportMeshAsync` function instead. + Loads the meshes from the file and appends them to the scene ```javascript @@ -64,36 +66,36 @@ BABYLON.SceneLoader.ImportMesh(["myMesh1", "myMesh2"], "./", "duck.gltf", scene, See an example here: -### SceneLoader.ImportMeshAsync +### ImportMeshAsync [Asynchronous](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous) version of the ImportMesh function. The result can be obtained by calling on the returned [Promise](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises) or by using the [await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) keyword (note: to be able to use the await keyword in the `createScene` function, it has to be marked as async in its definition). ```javascript // The first parameter can be set to null to load all meshes and skeletons -const importPromise = BABYLON.SceneLoader.ImportMeshAsync(["myMesh1", "myMesh2"], "./", "duck.gltf", scene); +const importPromise = BABYLON.ImportMeshAsync("./duck.gltf", scene, { meshNames: ["myMesh1", "myMesh2"] }); importPromise.then((result) => { //// Result has meshes, particleSystems, skeletons, animationGroups and transformNodes }); ``` -See an example here: +See an example here: or ```javascript // The first parameter can be set to null to load all meshes and skeletons -const result = await BABYLON.SceneLoader.ImportMeshAsync(["myMesh1", "myMesh2"], "./", "duck.gltf", scene); +const result = await BABYLON.ImportMeshAsync("./duck.gltf", scene, { meshNames: ["myMesh1", "myMesh2"] }); // Result has meshes, particleSystems, skeletons, animationGroups and transformNodes ``` -See an example here: +See an example here: -## SceneLoader.LoadAssetContainer +## LoadAssetContainerAsync Loads all babylon assets from the file and does not append them to the scene ```javascript -BABYLON.SceneLoader.LoadAssetContainer("./", "duck.gltf", scene, function (container) { +BABYLON.LoadAssetContainerAsync("./duck.gltf", scene).then(function (container) { const meshes = container.meshes; const materials = container.materials; //... @@ -103,25 +105,25 @@ BABYLON.SceneLoader.LoadAssetContainer("./", "duck.gltf", scene, function (conta }); ``` -See an example here: +See an example here: -## SceneLoader.ImportAnimations +## ImportAnimationsAsync Loads the animations from the file and merges them to the scene You can customize the import process using options and callbacks ```javascript -BABYLON.SceneLoader.ImportAnimations("./", "Elf_run.gltf", scene); +BABYLON.ImportAnimationsAsync("./Elf_run.gltf", scene); ``` -See an example here: +See an example here: -## SceneLoader.AppendAsync +## AppendSceneAsync There are also `Async` versions of these functions that return promises: ```javascript -BABYLON.SceneLoader.AppendAsync("./", "duck.gltf", scene).then(function (scene) { +BABYLON.AppendSceneAsync("./duck.gltf", scene).then(function (scene) { // do something with the scene }); ``` @@ -155,7 +157,7 @@ glb formats). The `pluginExtension` parameter should be set when using base64 da The format for a minimum base64 encoded model file is: -``` +```javascript data:;base64, ``` diff --git a/content/features/featuresDeepDive/mesh/bonesSkeletons.md b/content/features/featuresDeepDive/mesh/bonesSkeletons.md index d0c20b700..72fabe312 100644 --- a/content/features/featuresDeepDive/mesh/bonesSkeletons.md +++ b/content/features/featuresDeepDive/mesh/bonesSkeletons.md @@ -67,17 +67,15 @@ Skeletons and bones can be loaded from .babylon files. Here is a sample of how to load a boned mesh and how to launch skeleton animation: ```javascript -BABYLON.SceneLoader.ImportMesh("him", "Scenes/Dude/", "Dude.babylon", scene, function (newMeshes, particleSystems, skeletons) { - const dude = newMeshes[0]; +BABYLON.ImportMeshAsync("scenes/Dude/Dude.babylon", scene, { meshNames: "him" }).then(function (result) { + scene.createDefaultCameraOrLight(true, true, true); + scene.createDefaultEnvironment(); - dude.rotation.y = Math.PI; - dude.position = new BABYLON.Vector3(0, 0, -80); - - scene.beginAnimation(skeletons[0], 0, 100, true, 1.0); + scene.beginAnimation(result.skeletons[0], 0, 100, true, 1.0); }); ``` -A complete running example can be found here: +A complete running example can be found here: ## Use Bones with Node Material @@ -85,7 +83,7 @@ The [Node Material](/features/featuresDeepDive/materials/node_material) is a pow ![Use Instances with Node Material](/img/how_to/bones-node.png) - + ## Cloning bones @@ -94,8 +92,8 @@ Bones and skeletons can be cloned (This is the case with the rabbits in the prev Here is a sample of how to load and clone a mesh and its skeleton: ```javascript -BABYLON.SceneLoader.ImportMesh("Rabbit", "Scenes/Rabbit/", "Rabbit.babylon", scene, function (newMeshes, particleSystems, skeletons) { - const rabbit = newMeshes[1]; +BABYLON.ImportMeshAsync("Scenes/Rabbit/Rabbit.babylon", scene, { meshNames: "Rabbit" }).then(function (result) { + const rabbit = result.meshes[1]; rabbit.scaling = new BABYLON.Vector3(0.4, 0.4, 0.4); shadowGenerator.getShadowMap().renderList.push(rabbit); @@ -109,7 +107,7 @@ BABYLON.SceneLoader.ImportMesh("Rabbit", "Scenes/Rabbit/", "Rabbit.babylon", sce rabbit3.position = new BABYLON.Vector3(50, 0, -20); rabbit3.skeleton = rabbit.skeleton.clone("clonedSkeleton2"); - scene.beginAnimation(skeletons[0], 0, 100, true, 0.8); + scene.beginAnimation(result.skeletons[0], 0, 100, true, 0.8); scene.beginAnimation(rabbit2.skeleton, 73, 100, true, 0.8); scene.beginAnimation(rabbit3.skeleton, 0, 72, true, 0.8); }); @@ -120,28 +118,28 @@ BABYLON.SceneLoader.ImportMesh("Rabbit", "Scenes/Rabbit/", "Rabbit.babylon", sce More complex models, such as the Dude, contain submeshes. When cloning you must iterate and clone the submeshes as well. Here is an example of how to clone a more complex model: ```javascript -BABYLON.SceneLoader.ImportMesh("him", "Dude/", "dude.babylon", scene, function (newMeshes, particleSystems, skeletons) { - - newMeshes[0].position = new BABYLON.Vector3(0, 0, 5); // The original dude - scene.beginAnimation(skeletons[0], 0, 120, 1.0, true); +BABYLON.ImportMeshAsync("Dude/dude.babylon", scene, { meshNames: "him" }).then(function (result) { + result.meshes[0].position = new BABYLON.Vector3(0, 0, 5); // The original dude + scene.beginAnimation(result.skeletons[0], 0, 120, 1.0, true); - dudes = []; + dudes = []; - for (i = 0; i < 10; i++) { // 10 clones - const xrand = Math.floor(Math.random() * 501) - 250; - const zrand = Math.floor(Math.random() * 501) - 250; + for (i = 0; i < 10; i++) { + // 10 clones + const xrand = Math.floor(Math.random() * 501) - 250; + const zrand = Math.floor(Math.random() * 501) - 250; - const c = []; + const c = []; - for (j = 1; j < newMeshes.length; j++) { - c[j] = newMeshes[j].clone("c" + j); - c[j].position = new BABYLON.Vector3(xrand, 0, zrand); - c[j].skeleton = newMeshes[j].skeleton.clone(); - scene.beginAnimation(c[j].skeleton, 0, 120, 1.0, true); - } - dudes[i] = c; + for (j = 1; j < result.meshes.length; j++) { + c[j] = result.meshes[j].clone("c" + j); + c[j].position = new BABYLON.Vector3(xrand, 0, zrand); + c[j].skeleton = result.meshes[j].skeleton.clone(); + scene.beginAnimation(c[j].skeleton, 0, 120, 1.0, true); } -} + dudes[i] = c; + } +}); ``` ## Picking a mesh attached to a skeleton diff --git a/content/features/featuresDeepDive/mesh/copies/instances.md b/content/features/featuresDeepDive/mesh/copies/instances.md index 7b7633328..9eaa7eda6 100644 --- a/content/features/featuresDeepDive/mesh/copies/instances.md +++ b/content/features/featuresDeepDive/mesh/copies/instances.md @@ -20,8 +20,8 @@ Instances are built from a mesh with the following code: ```javascript // In this case we're loading our mesh from an external source. -BABYLON.SceneLoader.ImportMesh("", "//www.babylonjs.com/assets/Tree/", "tree.babylon", scene, function (newMeshes) { - var mesh = newMeshes[0]; +BABYLON.ImportMeshAsync("https://www.babylonjs.com/assets/Tree/tree.babylon", scene).then(function (result) { + var mesh = result.meshes[0]; // Make the "root" mesh not visible. The instanced versions of it that we // create below will be visible. mesh.isVisible = false; @@ -112,7 +112,7 @@ Example: { +BABYLON.ImportMeshAsync("PATH TO FOLDER" + "file.babylon").then((result) => { const goldbergPoly = result.meshes[0]; }); ``` -PG: +PG: diff --git a/content/features/featuresDeepDive/mesh/gaussianSplatting.md b/content/features/featuresDeepDive/mesh/gaussianSplatting.md index 6ea7ac3e1..d9ba55eaf 100644 --- a/content/features/featuresDeepDive/mesh/gaussianSplatting.md +++ b/content/features/featuresDeepDive/mesh/gaussianSplatting.md @@ -25,13 +25,13 @@ Supported formats are : Load asynchronously the splat or PLY file like any other supported file format: ```javascript -BABYLON.SceneLoader.ImportMeshAsync(null, "https://assets.babylonjs.com/splats/", "gs_Skull.splat", scene).then((result) =>{ +BABYLON.ImportMeshAsync("https://assets.babylonjs.com/splats/gs_Skull.splat", scene).then((result) =>{ const gaussianSplattingMesh = result.meshes[0]; }); ``` **Note: Gaussian splatting files do not have a standard on handness or orientation. No space change operation will happen. Some scene might appear updside down or mirrored.** - + ## Updating datas of a Gaussian Splatting diff --git a/content/features/featuresDeepDive/mesh/simplifyingMeshes.md b/content/features/featuresDeepDive/mesh/simplifyingMeshes.md index 3cfbe02ec..3049517de 100644 --- a/content/features/featuresDeepDive/mesh/simplifyingMeshes.md +++ b/content/features/featuresDeepDive/mesh/simplifyingMeshes.md @@ -71,8 +71,8 @@ This function will be called after the Auto-LOD process is successfully done. - **Usage Example** ```javascript -BABYLON.SceneLoader.ImportMesh("", "./", "DanceMoves.babylon", scene, (newMeshes, particleSystems, skeletons) => { - newMeshes[1].simplify( +BABYLON.ImportMeshAsync("./DanceMoves.babylon", scene).then((result) => { + result.meshes[1].simplify( [ { quality: 0.9, distance: 25 }, { quality: 0.3, distance: 50 }, @@ -89,7 +89,7 @@ BABYLON.SceneLoader.ImportMesh("", "./", "DanceMoves.babylon", scene, (newMeshes Once the simplification is finished, you can also access the simplified mesh by utilizing the [getLODLevelAtDistance](/typedoc/classes/babylon.mesh#getlodlevelatdistance) and [getLODLevels](/typedoc/classes/babylon.mesh#getlodlevels) functions of the mesh class. You can use this to clone the simplified mesh and use it indepedently of the main mesh. -## Demos  +## Demos Zoom in and out to see the effect, watch the number of active vertices closely. diff --git a/content/features/featuresDeepDive/mesh/transforms/lattice.md b/content/features/featuresDeepDive/mesh/transforms/lattice.md index bf056606f..db8daf9bc 100644 --- a/content/features/featuresDeepDive/mesh/transforms/lattice.md +++ b/content/features/featuresDeepDive/mesh/transforms/lattice.md @@ -146,8 +146,8 @@ One important point here is that we use the `deform` function with a second para You can also update the lattice data: -``` - const loadedData = await BABYLON.SceneLoader.ImportMeshAsync("", "scenes/", "skull.babylon", scene); +```javascript +const loadedData = await BABYLON.ImportMeshAsync("scenes/skull.babylon", scene); const skull = loadedData.meshes[0]; skull.position.set(0, 0, 0); @@ -156,35 +156,35 @@ const updatedPositions = new Float32Array(positions.length); // lattice var lattice = new BABYLON.Lattice({ - resolutionY: 10, - autoAdaptToMesh: skull, - position: BABYLON.Vector3.Zero() + resolutionY: 10, + autoAdaptToMesh: skull, + position: BABYLON.Vector3.Zero(), }); scene.onBeforeRenderObservable.add(() => { - // Twist!! - for (x = 0; x < lattice.resolutionX; x++) { - for (y = 0; y < lattice.resolutionY; y++) { - for (z = 0; z < lattice.resolutionZ; z++) { - const angle = (y / lattice.resolutionY) * 0.02; - const control = lattice.data[x][y][z]; - const cx = control.x; - const cz = control.z; - - const cosAngle = Math.cos(angle); - const sinAngle = Math.sin(angle); - - // Rotation - control.x = cosAngle * cx - sinAngle * cz; - control.z = sinAngle * cx + cosAngle * cz; - } - } + // Twist!! + for (x = 0; x < lattice.resolutionX; x++) { + for (y = 0; y < lattice.resolutionY; y++) { + for (z = 0; z < lattice.resolutionZ; z++) { + const angle = (y / lattice.resolutionY) * 0.02; + const control = lattice.data[x][y][z]; + const cx = control.x; + const cz = control.z; + + const cosAngle = Math.cos(angle); + const sinAngle = Math.sin(angle); + + // Rotation + control.x = cosAngle * cx - sinAngle * cz; + control.z = sinAngle * cx + cosAngle * cz; + } } + } - lattice.deform(positions, updatedPositions); - skull.setVerticesData(BABYLON.VertexBuffer.PositionKind, updatedPositions); - skull.createNormals(true); + lattice.deform(positions, updatedPositions); + skull.setVerticesData(BABYLON.VertexBuffer.PositionKind, updatedPositions); + skull.createNormals(true); }); ``` - + diff --git a/content/features/featuresDeepDive/particles/point_cloud_system/pcs_creation.md b/content/features/featuresDeepDive/particles/point_cloud_system/pcs_creation.md index 0087cc1b8..7dd3bc157 100644 --- a/content/features/featuresDeepDive/particles/point_cloud_system/pcs_creation.md +++ b/content/features/featuresDeepDive/particles/point_cloud_system/pcs_creation.md @@ -1,6 +1,6 @@ --- title: Creating A Point Cloud System -image: +image: description: Learn how to create a point cloud system in Babylon.js. keywords: diving deeper, point cloud, point cloud system further-reading: @@ -28,13 +28,13 @@ pcs.addPoints(10000); will add 10000 points. -- +- You can use your own function as a second parameter to set particle properties such as position and color. This function must have this kind of signature: ```javascript var myFunc = function (particle, i, s) { - // particle is the current particle, the i-th one in the PCS and the s-th one in its group + // particle is the current particle, the i-th one in the PCS and the s-th one in its group }; ``` @@ -42,8 +42,8 @@ For example using i; ```javascript var myfunc = function (particle, i, s) { - particle.position = new BABYLON.Vector3(0.5 + 0.25 * Math.random(), i / 5000, 0.25 * Math.random()); - particle.color = new BABYLON.Color4(Math.random(), Math.random(), Math.random(), Math.random()); + particle.position = new BABYLON.Vector3(0.5 + 0.25 * Math.random(), i / 5000, 0.25 * Math.random()); + particle.color = new BABYLON.Color4(Math.random(), Math.random(), Math.random(), Math.random()); }; pcs.addPoints(10000, myfunc); pcs.addPoints(10000, myfunc); @@ -53,8 +53,8 @@ will produce a tall block of points whose heights cover the full range of 20000 ```javascript var myfunc = function (particle, i, s) { - particle.position = new BABYLON.Vector3(0.5 + 0.25 * Math.random(), s / 5000, 0.25 * Math.random()); - particle.color = new BABYLON.Color4(Math.random(), Math.random(), Math.random(), Math.random()); + particle.position = new BABYLON.Vector3(0.5 + 0.25 * Math.random(), s / 5000, 0.25 * Math.random()); + particle.color = new BABYLON.Color4(Math.random(), Math.random(), Math.random(), Math.random()); }; pcs.addPoints(10000, myfunc); pcs.addPoints(10000, myfunc); @@ -68,8 +68,8 @@ In addition the use of `particle.groupId` can have an effect on all particles wi ```javascript var myfunc = function (particle, i, s) { - particle.position = new BABYLON.Vector3(particle.groupId * 0.5 + 0.25 * Math.random(), i / 5000, 0.25 * Math.random()); - particle.color = new BABYLON.Color4(Math.random(), Math.random(), Math.random(), Math.random()); + particle.position = new BABYLON.Vector3(particle.groupId * 0.5 + 0.25 * Math.random(), i / 5000, 0.25 * Math.random()); + particle.color = new BABYLON.Color4(Math.random(), Math.random(), Math.random(), Math.random()); }; pcs.addPoints(10000, myfunc); pcs.addPoints(10000, myfunc); @@ -79,7 +79,7 @@ will displace the second group of points along the x axis. ![use groupId](/img/how_to/particles/points2.jpg) -- +- ## Add Surface / Volume Points @@ -136,37 +136,37 @@ pcs.addVolumePoints(model, 10000, BABYLON.PointColor.Color, 3); Of course when you import a model you may not know how many child meshes the model is made up off nor the order of textures for each mesh. Using the [inspector](/toolsAndResources/inspector) you can check the loaded textures and see if their names give you a clue. If not then use trial and error from 0 to the number of textures. Alternatively you can check out meshes and textures once loaded along the lines of ```javascript -BABYLON.SceneLoader.ImportMesh("", "location", "file", scene, function (meshes) { - var n = meshes.length; - var p; - var t; - for (let i = 0; i < n; i++) { - if (meshes[i].material !== null) { - console.log("Mesh", i); - t = meshes[i].material.getActiveTextures(); - p = t.length; - for (let j = 0; j < p; j++) { - console.log("Texture", j, "Name", t[j].name); - } - } +BABYLON.ImportMeshAsync("location" + "file", scene).then(function ({ meshes }) { + var n = meshes.length; + var p; + var t; + for (let i = 0; i < n; i++) { + if (meshes[i].material !== null) { + console.log("Mesh", i); + t = meshes[i].material.getActiveTextures(); + p = t.length; + for (let j = 0; j < p; j++) { + console.log("Texture", j, "Name", t[j].name); + } } + } }); ``` **Examples** -- -- -- -- -- -- -- -- -- -- -- -- +- +- +- +- +- +- +- +- +- +- +- +- ## Building the Mesh @@ -186,4 +186,4 @@ If you never want the particle properties of your PCS to change, ie you want it var pcs = new BABYLON.PointsCloudSystem("pcs", 5, scene, { updatable: false }); ``` -After making updatable false the following methods will no longer have any effect, `initParticles()`, `updateParticle(particle)` and `setParticles()`. \ No newline at end of file +After making updatable false the following methods will no longer have any effect, `initParticles()`, `updateParticle(particle)` and `setParticles()`. diff --git a/content/features/featuresDeepDive/physics/v2/compounds.md b/content/features/featuresDeepDive/physics/v2/compounds.md index 2b5bdeb7b..6734b09ec 100644 --- a/content/features/featuresDeepDive/physics/v2/compounds.md +++ b/content/features/featuresDeepDive/physics/v2/compounds.md @@ -1,11 +1,11 @@ --- title: Physics compounds -image: +image: description: How to use compounds to model complex objects with simple primitives keywords: diving deeper, phyiscs further-reading: - - title: How To Use Forces - url: /features/featuresDeepDive/physics/forces + - title: How To Use Forces + url: /features/featuresDeepDive/physics/forces video-overview: video-content: --- @@ -19,7 +19,7 @@ The Compound is a special type of shape that acts as a "container" to other shap Imagine you have a mesh that represents a character. Character meshes are usually pretty complex, thus we want to avoid using it directly for collision. We can approximate the shape of the character with a sphere representing the head, and a box representing the rest of the body. We will create two meshes to represent these shapes, parent them to the character mesh, create two child PhysicShapes and parent them to a PhysicsShapeContainer: ```javascript -const myMesh = BABYLON.SceneLoader.ImportMeshAsync(...); +const myMesh = BABYLON.ImportMeshAsync(...); const headNode = new BABYLON.TransformNode("headNode"); headNode.position.y = 3; @@ -38,8 +38,9 @@ parentShape.addChildFromParent(myMesh, sphereShape, headNode); const body = new BABYLON.PhysicsBody(myMesh, scene); body.shape = parentShape; ``` + The following Playground shows a simple example of creating a Container body to approximate a mesh: - + The following Playground shows a comparison of using Container, Convex Hull and Mesh shapes on different meshes: diff --git a/content/features/featuresDeepDive/physics/v2/migrateFromV1.md b/content/features/featuresDeepDive/physics/v2/migrateFromV1.md index 636f920ef..a632395fe 100644 --- a/content/features/featuresDeepDive/physics/v2/migrateFromV1.md +++ b/content/features/featuresDeepDive/physics/v2/migrateFromV1.md @@ -53,7 +53,7 @@ sphereBody.setMassProperties({ mass: 1 }); The advantage of this approach is that, if you have another mesh you want to use with the same collider shape and material, you can reuse the shape: ```javascript -const complexModel = await BABYLON.SceneLoader.ImportMeshAsync(...); +const complexModel = await BABYLON.ImportMeshAsync(...); const body = new BABYLON.PhysicsBody(complexModel, BABYLON.PhysicsMotionType.DYNAMIC, false, scene); body.shape = sphereShape; body.setMassProperties({mass: complexModelMass}); diff --git a/content/features/featuresDeepDive/scene/customLoadingScreen.md b/content/features/featuresDeepDive/scene/customLoadingScreen.md index 5d9287e52..cbd1c601c 100644 --- a/content/features/featuresDeepDive/scene/customLoadingScreen.md +++ b/content/features/featuresDeepDive/scene/customLoadingScreen.md @@ -1,13 +1,13 @@ --- title: Creating Custom Loading Screens -image: +image: description: Learn how to create custom loading screens in Babylon.js. keywords: diving deeper, scene, loader, loading screen further-reading: video-overview: video-content: - - title: Custom Loading Screens - url: https://youtu.be/cLqK9vgTKBw + - title: Custom Loading Screens + url: https://youtu.be/cLqK9vgTKBw --- ## How To Create a Custom Loading Screen @@ -31,14 +31,14 @@ interface ILoadingScreen { In plain JavaScript, your loader code will look like this: ```javascript -function CustomLoadingScreen( /* variables needed, for example:*/ text) { +function CustomLoadingScreen(/* variables needed, for example:*/ text) { //init the loader this.loadingUIText = text; } -CustomLoadingScreen.prototype.displayLoadingUI = function() { +CustomLoadingScreen.prototype.displayLoadingUI = function () { alert(this.loadingUIText); }; -CustomLoadingScreen.prototype.hideLoadingUI = function() { +CustomLoadingScreen.prototype.hideLoadingUI = function () { alert("Loaded!"); }; ``` @@ -88,7 +88,7 @@ You might also be interested in a standalone html example: ```html - + Babylon.js custom loading screen example @@ -97,89 +97,83 @@ You might also be interested in a standalone html example: - + - +
default div text
- + ``` @@ -187,35 +181,28 @@ You might also be interested in a standalone html example: When loading files, you can get the [SceneLoaderProgressEvent](/typedoc/classes/babylon.sceneloader) sent in the `onProgress` callback. -Example using `BABYLON.SceneLoader.ImportMesh`: +Example using `BABYLON.ImportMeshAsync`: ```javascript -BABYLON.SceneLoader.ImportMesh( - "", - "https://models.babylonjs.com/CornellBox/", - "cornellBox.glb", - scene, - function () { - // onSuccess - scene.createDefaultCamera(true, true, true); - scene.activeCamera.alpha = Math.PI / 2; - engine.hideLoadingUI(); - }, - function (evt) { - // onProgress - var loadedPercent = 0; - if (evt.lengthComputable) { - loadedPercent = (evt.loaded * 100 / evt.total).toFixed(); - } else { - var dlCount = evt.loaded / (1024 * 1024); - loadedPercent = Math.floor(dlCount * 100.0) / 100.0; - } - // assuming "loadingScreenPercent" is an existing html element - document.getElementById("loadingScreenPercent").innerHTML = loadedPercent; +BABYLON.ImportMeshAsync("https://models.babylonjs.com/CornellBox/cornellBox.glb", scene, { + onProgress: function (evt) { + // onProgress + var loadedPercent = 0; + if (evt.lengthComputable) { + loadedPercent = ((evt.loaded * 100) / evt.total).toFixed(); + } else { + var dlCount = evt.loaded / (1024 * 1024); + loadedPercent = Math.floor(dlCount * 100.0) / 100.0; } -); - - + // assuming "loadingScreenPercent" is an existing html element + document.getElementById("loadingScreenPercent").innerHTML = loadedPercent; + }, +}).then(function () { + // onSuccess + scene.createDefaultCamera(true, true, true); + scene.activeCamera.alpha = Math.PI / 2; + engine.hideLoadingUI(); +}); ``` ## File Loading Rate of Multiple Assets diff --git a/content/features/featuresDeepDive/scene/fastBuildWorld.md b/content/features/featuresDeepDive/scene/fastBuildWorld.md index 04e16c85b..2ad114c2c 100644 --- a/content/features/featuresDeepDive/scene/fastBuildWorld.md +++ b/content/features/featuresDeepDive/scene/fastBuildWorld.md @@ -254,7 +254,7 @@ The camera adjusts its position automatically to make the world viewable dependi Since the `createDefault...` helpers take into account any models in the scene they can only be applied after the model is loaded and so are placed in the callback function. For example ```javascript -BABYLON.SceneLoader.Append("https://www.babylonjs.com/assets/DamagedHelmet/glTF/", "DamagedHelmet.gltf", scene, function (meshes) { +BABYLON.AppendSceneAsync("https://www.babylonjs.com/assets/DamagedHelmet/glTF/", "DamagedHelmet.gltf", scene).then(function ({ meshes }) { scene.createDefaultCameraOrLight(true, true, true); scene.createDefaultEnvironment(); }); diff --git a/content/features/introductionToFeatures/chap1/first_app.md b/content/features/introductionToFeatures/chap1/first_app.md index 999198acb..b2022fc9a 100644 --- a/content/features/introductionToFeatures/chap1/first_app.md +++ b/content/features/introductionToFeatures/chap1/first_app.md @@ -155,7 +155,7 @@ Example setup for a loaded model const createScene = function () { const scene = new BABYLON.Scene(engine); - BABYLON.SceneLoader.ImportMeshAsync("", "https://assets.babylonjs.com/meshes/", "box.babylon"); + BABYLON.ImportMeshAsync("https://assets.babylonjs.com/meshes/box.babylon"); const camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 15, new BABYLON.Vector3(0, 0, 0)); camera.attachControl(canvas, true); diff --git a/content/features/introductionToFeatures/chap1/first_import.md b/content/features/introductionToFeatures/chap1/first_import.md index 2e122ad63..f6e5786f6 100644 --- a/content/features/introductionToFeatures/chap1/first_import.md +++ b/content/features/introductionToFeatures/chap1/first_import.md @@ -17,36 +17,36 @@ The playgrounds on this page contain models (in this example, houses) which can When you add a model to a scene, you are loading it through the browser. As you likely already know, loading anything from a website is an asynchronous function. Therefore, before you can do anything with your models, you first must ensure they have been loaded successfully. You can do this using the _ImportMeshAsync_ method of the _SceneLoader_, which can be done as follows: ```javascript -BABYLON.SceneLoader.ImportMeshAsync(model_name, folder_path, file_name, scene); +BABYLON.ImportMeshAsync(folder_path + file_name, scene, optionalOptions); ``` -The scene parameter is optional and will default to the current scene. The first parameter can be any one of three types depending whether you want to load all the models, just one model or a list of models. +The scene parameter is optional and will default to the current scene. In the options you can specify which meshes to load: ```javascript -BABYLON.SceneLoader.ImportMeshAsync("", "/relative path/", "myFile"); //Empty string loads all meshes -BABYLON.SceneLoader.ImportMeshAsync("model1", "/relative path/", "myFile"); //Name of the model loads one model -BABYLON.SceneLoader.ImportMeshAsync(["model1", "model2"], "/relative path/", "myFile"); //Array of model names +BABYLON.ImportMeshAsync("/relative path/myFile"); //Empty string loads all meshes +BABYLON.ImportMeshAsync("/relative path/myFile", scene, { meshNames: "model1" }); //Name of the model loads one model +BABYLON.ImportMeshAsync("/relative path/myFile", scene, { meshNames: ["model1", "model2"] }); //Array of model names ``` Note that any of the calls above will only load the models; however, you will not be able to manipulate them in any way. Internally, a Promise object is setup and returned, but the above code does nothing with the result of that Promise. Examples of this are in the following two playgrounds, which **only** import the named models. - + - + Therefore, in order to act on the result and manipulate the objects, we follow the Promise with the _then_ method to call a function with the _result_ of the _Promise_. The _result_ is an object containing, among other things, the property _meshes_ which contains all the loaded models. We can use this array, or their names, to manipulate each mesh. ```javascript -BABYLON.SceneLoader.ImportMeshAsync("", "/relative path/", "myFile").then((result) => { - result.meshes[1].position.x = 20; - const myMesh1 = scene.getMeshByName("myMesh_1"); - myMesh1.rotation.y = Math.PI / 2; +BABYLON.ImportMeshAsync("/relative path/myFile").then((result) => { + result.meshes[1].position.x = 20; + const myMesh1 = scene.getMeshByName("myMesh_1"); + myMesh1.rotation.y = Math.PI / 2; }); ``` The following playground imports all models and changes their positions: - + ## Moving On diff --git a/content/features/introductionToFeatures/chap3/animation.md b/content/features/introductionToFeatures/chap3/animation.md index 4375b5473..8277a4785 100644 --- a/content/features/introductionToFeatures/chap3/animation.md +++ b/content/features/introductionToFeatures/chap3/animation.md @@ -17,28 +17,31 @@ We will start with a wheel and rotate it about its axle. Remember that in order We need to create a new animation object ```javascript - const animWheel = new BABYLON.Animation("wheelAnimation", "rotation.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); +const animWheel = new BABYLON.Animation("wheelAnimation", "rotation.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); ``` + which has the parameters - name, property to animate, animation frames per second, property to animate type, loop mode, in this case repeat animation. We follow this with the key frame array where we set values for the property to animate by frame number + ```javascript -const wheelKeys = []; +const wheelKeys = []; //At the animation key 0, the value of rotation.y is 0 wheelKeys.push({ - frame: 0, - value: 0 + frame: 0, + value: 0, }); //At the animation key 30, (after 1 sec since animation fps = 30) the value of rotation.y is 2PI for a complete rotation wheelKeys.push({ - frame: 30, - value: 2 * Math.PI + frame: 30, + value: 2 * Math.PI, }); ``` Finally we link the key frame array to the animation, the animation to the mesh and begin it. + ```javascript //set the keys animWheel.setKeys(wheelKeys); @@ -64,19 +67,19 @@ scene.beginAnimation(wheelLF, 0, 30, true); To ensure that in later playgrounds new code is not overwhelmed by a large amount of previous coding we will save the car as a model and import and animate it as an item. ```javascript -BABYLON.SceneLoader.ImportMeshAsync("", "url to model car", "car.babylon").then(() => { - const wheelRB = scene.getMeshByName("wheelRB"); - const wheelRF = scene.getMeshByName("wheelRF"); - const wheelLB = scene.getMeshByName("wheelLB"); - const wheelLF = scene.getMeshByName("wheelLF"); - - scene.beginAnimation(wheelRB, 0, 30, true); - scene.beginAnimation(wheelRF, 0, 30, true); - scene.beginAnimation(wheelLB, 0, 30, true); - scene.beginAnimation(wheelLF, 0, 30, true); +BABYLON.ImportMeshAsync("url to model car" + "car.babylon").then(() => { + const wheelRB = scene.getMeshByName("wheelRB"); + const wheelRF = scene.getMeshByName("wheelRF"); + const wheelLB = scene.getMeshByName("wheelLB"); + const wheelLF = scene.getMeshByName("wheelLF"); + + scene.beginAnimation(wheelRB, 0, 30, true); + scene.beginAnimation(wheelRF, 0, 30, true); + scene.beginAnimation(wheelLB, 0, 30, true); + scene.beginAnimation(wheelLF, 0, 30, true); }); ``` -We can now animate the car itself and add it into the village \ No newline at end of file +We can now animate the car itself and add it into the village diff --git a/content/features/introductionToFeatures/chap3/import_character.md b/content/features/introductionToFeatures/chap3/import_character.md index 655ed38ac..bbf653864 100644 --- a/content/features/introductionToFeatures/chap3/import_character.md +++ b/content/features/introductionToFeatures/chap3/import_character.md @@ -11,23 +11,24 @@ video-content: # Getting Started - Character Animation ## A Walking Figure + Sometimes the easiest way to add a model to a scene is to obtain one from elsewhere. This could be one you have created in your favorite model building software or one your have purchased. -The *Dude* model is one that has been built with its own skeleton animation. +The _Dude_ model is one that has been built with its own skeleton animation. ![dude walking](/img/getstarted/dude.gif) Once imported the character and its skeleton are obtained from the meshes and skeletons properties of the results object. ```javascript -BABYLON.SceneLoader.ImportMeshAsync("him" /* mesh name */, "/scenes/Dude/" /* path to model */, "Dude.babylon" /* model file */, scene).then((result) => { - var dude = result.meshes[0]; - dude.scaling = new BABYLON.Vector3(0.25, 0.25, 0.25); - - scene.beginAnimation(result.skeletons[0], 0, 100, true, 1.0); +BABYLON.ImportMeshAsync("/scenes/Dude/Dude.babylon" /* model file */, scene, { meshNames: "him" }).then((result) => { + var dude = result.meshes[0]; + dude.scaling = new BABYLON.Vector3(0.25, 0.25, 0.25); + + scene.beginAnimation(result.skeletons[0], 0, 100, true, 1.0); }); ``` - + -Currently the character is set in one position and we would like him to walk around the village. This time instead of creating another animation object for the character we will change its position and orientation before each frame is rendered. \ No newline at end of file +Currently the character is set in one position and we would like him to walk around the village. This time instead of creating another animation object for the character we will change its position and orientation before each frame is rendered. diff --git a/content/guidedLearning/createAGame/importMeshes.md b/content/guidedLearning/createAGame/importMeshes.md index 2884d1dd5..b8ab59737 100644 --- a/content/guidedLearning/createAGame/importMeshes.md +++ b/content/guidedLearning/createAGame/importMeshes.md @@ -19,7 +19,7 @@ Previously, we created an [Environment class](/guidedLearning/createAGame/simple ### \_loadAsset ```javascript -const result = await SceneLoader.ImportMeshAsync(null, "./models/", "envSetting.glb", this._scene); +const result = await ImportMeshAsync("./models/envSetting.glb", this._scene); let env = result.meshes[0]; let allMeshes = env.getChildMeshes(); @@ -29,8 +29,8 @@ We want to first import the mesh for the environment, then grab the root and ext ```javascript return { - env: env, //reference to our entire imported glb (meshes and transform nodes) - allMeshes: allMeshes, // all of the meshes that are in the environment + env: env, //reference to our entire imported glb (meshes and transform nodes) + allMeshes: allMeshes, // all of the meshes that are in the environment }; ``` @@ -44,8 +44,8 @@ Now we need to update the **load** function to call **\_loadAsset**. We use awai const assets = await this._loadAsset(); //Loop through all environment meshes that were imported assets.allMeshes.forEach((m) => { - m.receiveShadows = true; - m.checkCollisions = true; + m.receiveShadows = true; + m.checkCollisions = true; }); ``` @@ -80,7 +80,7 @@ The function's purpose is to call loadCharacter(), store our assets, and then re In order to load our assets, we just need to modify the body portion of our character assets. Instead of having primitives for our body, we'll be using the imported mesh. ```javascript -return SceneLoader.ImportMeshAsync(null, "./models/", "player.glb", scene).then((result) =>{ +return ImportMeshAsync("./models/player.glb", scene).then((result) =>{ const root = result.meshes[0]; //body is our actual player mesh const body = root; @@ -116,8 +116,8 @@ scene.getMeshByName("outer").position = scene.getTransformNodeByName("startPosit ```javascript await this._setUpGame().then((res) => { - finishedLoading = true; - this._goToGame(); + finishedLoading = true; + this._goToGame(); }); ``` @@ -129,14 +129,14 @@ When you run the game now, you'll see the environment and character meshes in th **Files Used:** -- [app.ts](https://github.com/BabylonJS/SummerFestival/blob/master/src/app.ts) -- [environment.ts](https://github.com/BabylonJS/SummerFestival/blob/master/src/environment.ts) -- [characterController.ts](https://github.com/BabylonJS/SummerFestival/blob/master/src/characterController.ts) +- [app.ts](https://github.com/BabylonJS/SummerFestival/blob/master/src/app.ts) +- [environment.ts](https://github.com/BabylonJS/SummerFestival/blob/master/src/environment.ts) +- [characterController.ts](https://github.com/BabylonJS/SummerFestival/blob/master/src/characterController.ts) **Follow Along:** -- [app.ts](https://github.com/BabylonJS/SummerFestival/blob/master/tutorial/importMeshes/app.ts) -- [environment.ts](https://github.com/BabylonJS/SummerFestival/blob/master/tutorial/importMeshes/environment.ts) -- [characterController.ts](https://github.com/BabylonJS/SummerFestival/blob/master/tutorial/importMeshes/characterController.ts) -- [environment model](https://github.com/BabylonJS/SummerFestival/blob/master/public/models/envSetting.glb) -- [player model](https://github.com/BabylonJS/SummerFestival/blob/master/public/models/player.glb) +- [app.ts](https://github.com/BabylonJS/SummerFestival/blob/master/tutorial/importMeshes/app.ts) +- [environment.ts](https://github.com/BabylonJS/SummerFestival/blob/master/tutorial/importMeshes/environment.ts) +- [characterController.ts](https://github.com/BabylonJS/SummerFestival/blob/master/tutorial/importMeshes/characterController.ts) +- [environment model](https://github.com/BabylonJS/SummerFestival/blob/master/public/models/envSetting.glb) +- [player model](https://github.com/BabylonJS/SummerFestival/blob/master/public/models/player.glb) diff --git a/content/guidedLearning/createAGame/lanterns.md b/content/guidedLearning/createAGame/lanterns.md index 083872435..374f51862 100644 --- a/content/guidedLearning/createAGame/lanterns.md +++ b/content/guidedLearning/createAGame/lanterns.md @@ -20,7 +20,7 @@ In [\_loadAsset](https://github.com/BabylonJS/SummerFestival/blob/master/src/env ```javascript //loads lantern mesh -const res = await SceneLoader.ImportMeshAsync("", "./models/", "lantern.glb", this._scene); +const res = await ImportMeshAsync("./models/lantern.glb", this._scene); ``` Then, we extract the mesh from the root, and remove the root. [The coordinate system guide for 3DMax](/features/featuresDeepDive/Exporters/3DSMax_to_glTF#left-to-right-handed-coordinate-system) explains why we have this root node when we import the glTF. Since we want to clone just the mesh, we'll need to remove the root. diff --git a/content/guidedLearning/workshop/Bowling.md b/content/guidedLearning/workshop/Bowling.md index 8b1a00cbb..06b60b2dc 100644 --- a/content/guidedLearning/workshop/Bowling.md +++ b/content/guidedLearning/workshop/Bowling.md @@ -1,6 +1,6 @@ --- title: Creating a Bowling Scene with the Havok Physics Plugin -image: +image: description: Simple bowling scene that simulates bowling ball movement and pin interactions keywords: workshop, bowling, Havok, physics further-reading: @@ -16,25 +16,25 @@ Let’s first create a new playground. We can get rid of the sphere and ground w ```javascript var createScene = function () { - // This creates a basic Babylon Scene object (non-mesh) - var scene = new BABYLON.Scene(engine); + // This creates a basic Babylon Scene object (non-mesh) + var scene = new BABYLON.Scene(engine); - // This creates and positions a free camera (non-mesh) - var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene); + // This creates and positions a free camera (non-mesh) + var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene); - // This targets the camera to scene origin - camera.setTarget(BABYLON.Vector3.Zero()); + // This targets the camera to scene origin + camera.setTarget(BABYLON.Vector3.Zero()); - // This attaches the camera to the canvas - camera.attachControl(canvas, true); + // This attaches the camera to the canvas + camera.attachControl(canvas, true); - // This creates a light, aiming 0,1,0 - to the sky (non-mesh) - var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene); + // This creates a light, aiming 0,1,0 - to the sky (non-mesh) + var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene); - // Default intensity is 1. Let's dim the light a small amount - light.intensity = 0.7; + // Default intensity is 1. Let's dim the light a small amount + light.intensity = 0.7; - return scene; + return scene; }; ``` @@ -86,9 +86,9 @@ We first start by loading the bowling pin from the Asset Librarian. Once loaded, ```javascript async function createPins(scene) { - const result = await BABYLON.SceneLoader.ImportMeshAsync("", Assets.meshes.bowlingPinpin_glb.rootUrl, Assets.meshes.bowlingPinpin_glb.filename, scene); - const bowlingPin = result.meshes[1]; - bowlingPin.scaling = new BABYLON.Vector3(0.3, 0.3, 0.3) + const result = await BABYLON.ImportMeshAsync(Assets.meshes.bowlingPinpin_glb.rootUrl + Assets.meshes.bowlingPinpin_glb.filename, scene); + const bowlingPin = result.meshes[1]; + bowlingPin.scaling = new BABYLON.Vector3(0.3, 0.3, 0.3); } createPins(scene); @@ -106,26 +106,26 @@ Since we can change the position for each instanced pin, we need a way to both s ```javascript pinPositions = [ - new BABYLON.Vector3(0, 0, 5), - new BABYLON.Vector3(.5, 0, 6), - new BABYLON.Vector3(-.5, 0, 6), - new BABYLON.Vector3(0, 0, 7), - new BABYLON.Vector3(1, 0, 7), - new BABYLON.Vector3(-1, 0, 7), - new BABYLON.Vector3(-1.5, 0, 8), - new BABYLON.Vector3(-.5, 0, 8), - new BABYLON.Vector3(.5, 0, 8), - new BABYLON.Vector3(1.5, 0, 8) -] + new BABYLON.Vector3(0, 0, 5), + new BABYLON.Vector3(0.5, 0, 6), + new BABYLON.Vector3(-0.5, 0, 6), + new BABYLON.Vector3(0, 0, 7), + new BABYLON.Vector3(1, 0, 7), + new BABYLON.Vector3(-1, 0, 7), + new BABYLON.Vector3(-1.5, 0, 8), + new BABYLON.Vector3(-0.5, 0, 8), + new BABYLON.Vector3(0.5, 0, 8), + new BABYLON.Vector3(1.5, 0, 8), +]; ``` We now iterate over the `pinPositions` array using the `map()` method. For each position in `pinPositions`, a new `bowlingPin` instance is created. Each new pin’s name is given the prefix `pin` followed by the corresponding index. The instanced pin’s position is then assigned based on the corresponding position value from the `pinPositions` array. ```javascript return pinPositions.map(function (positionInSpace, idx) { - const pin = new BABYLON.InstancedMesh("pin-" + idx, bowlingPin); - pin.position = positionInSpace; - return pin; + const pin = new BABYLON.InstancedMesh("pin-" + idx, bowlingPin); + pin.position = positionInSpace; + return pin; }); ``` @@ -145,10 +145,10 @@ With our bowling lane created and our pins perfectly placed, we’re ready to cr ```javascript async function createBall(scene) { - const result = await BABYLON.SceneLoader.ImportMeshAsync("", Assets.meshes.bowlingBall_glb.rootUrl, Assets.meshes.bowlingBall_glb.filename, scene); - const bowlingBall = result.meshes[1]; - bowlingBall.scaling.scaleInPlace(0.2); - bowlingBall.position = new BABYLON.Vector3(0, 0.5, -5); + const result = await BABYLON.ImportMeshAsync(Assets.meshes.bowlingBall_glb.rootUrl + Assets.meshes.bowlingBall_glb.filename, scene); + const bowlingBall = result.meshes[1]; + bowlingBall.scaling.scaleInPlace(0.2); + bowlingBall.position = new BABYLON.Vector3(0, 0.5, -5); } createBall(scene); @@ -178,13 +178,12 @@ The final step in our tutorial is to add keyboard input to both move the positio ```javascript scene.onKeyboardObservable.add((kbInfo) => { - switch (kbInfo.type) { - case BABYLON.KeyboardEventTypes.KEYDOWN: - switch (kbInfo.event.key.toLowerCase()) { - - } - } - }); + switch (kbInfo.type) { + case BABYLON.KeyboardEventTypes.KEYDOWN: + switch (kbInfo.event.key.toLowerCase()) { + } + } +}); ``` For typical keyboard game play, the A and D keys are used for left and right movement, respectively. Since we’re only moving the bowling ball to the left and right, we change the ball’s `x` position when the key is pressed. We don’t want to change the position too much per key press, therefore, we decrement and increment `0.1` on the x-axis. diff --git a/content/journey/theFirstStep.md b/content/journey/theFirstStep.md index 8cf909682..b511e6e90 100644 --- a/content/journey/theFirstStep.md +++ b/content/journey/theFirstStep.md @@ -103,7 +103,7 @@ Ok it's time for another addition to the scene. After all of your ground-related You should see the following lines of code pop right into the playground: ```javascript -BABYLON.SceneLoader.ImportMesh("meshName", "url to the mesh parent directory", "Mesh filename.fileextension", scene, function (newMeshes) {}); +BABYLON.ImportMeshAsync("url to the mesh parent directory" + "Mesh filename.fileextension", scene, { meshNames: "meshName" }).then(function (result) {}); ``` Let's do a few more things: @@ -112,24 +112,24 @@ Let's do a few more things: - 2. Replace "url to the mesh parent directory" (including quotes) with this: ```javascript -Assets.meshes.Yeti.rootUrl +Assets.meshes.Yeti.rootUrl; ``` - 3. Replace the "Mesh filename.fileextension" (including quotes) with this: ```javascript -Assets.meshes.Yeti.filename +Assets.meshes.Yeti.filename; ``` -- 4. After the `BABYLON.SceneLoader.ImportMesh` line, but before the "});" add the following line: +- 4. After the `BABYLON.ImportMeshAsync` line, but before the "});" add the following line: ```javascript -newMeshes[0].scaling = new BABYLON.Vector3(0.1, 0.1, 0.1); +result.meshes[0].scaling = new BABYLON.Vector3(0.1, 0.1, 0.1); ``` - 5. Run the scene - + Whoa! Cool! You just added an animated .gltf object into the scene! And you also scaled it down to fit on the groundplane! Well done! @@ -141,7 +141,7 @@ Press CTRL+SPACE to bring up the playground templates and create an Arc Rotate C Run the scene and click+drag or touch+drag on the Babylon scene. - + WooHoo! You've added interaction to the scene! Great job! Go ahead and save your playground by pressing CTRL+S or hitting the save button. @@ -211,7 +211,6 @@ This will open a text editor for you to create the file. At the top, type `_conf theme: jekyll-theme-minimal title: Title For Your Website description: Website description. - ``` ![create config file](/img/home/createTextFile.jpg) diff --git a/content/setup/frameworkPackages/es6Support.md b/content/setup/frameworkPackages/es6Support.md index 111e15565..a9e8ff6f5 100644 --- a/content/setup/frameworkPackages/es6Support.md +++ b/content/setup/frameworkPackages/es6Support.md @@ -696,9 +696,9 @@ let engine = new BABYLON.NullEngine(); // create your scene here const scene = .....; -BABYLON.SceneLoader.ImportMesh("", "https://awesomeserver.mine.com/", "my.glb", scene, () => { +BABYLON.ImportMeshAsync("https://awesomeserver.mine.com/my.glb", scene).then(() => { console.log("draco worked"); - }, null, (e) => { + }, (e) => { console.log("oh no! something is off", e); } ); diff --git a/content/setup/support/serverSide.md b/content/setup/support/serverSide.md index d3318f74a..222b7b2db 100644 --- a/content/setup/support/serverSide.md +++ b/content/setup/support/serverSide.md @@ -13,6 +13,7 @@ Starting with Babylon.js v3.1, we introduced the NullEngine which is a version o The NullEngine will not produce any rendering and thus can be used in a Node.js / server side environment. It can be used to: + - Run tests - Run a server side version of your application / game - Use specific Babylon.js services (like glTF loaders for instance) @@ -21,7 +22,7 @@ It can be used to: To use a headless version of Babylon.js, just run: -``` +```javascript var engine = new BABYLON.NullEngine(); var scene = new BABYLON.Scene(engine); ``` @@ -32,7 +33,7 @@ First install babylonjs and babylonjs-loaders: `npm install babylonjs babylonjs- Then use this code: -``` +```javascript var BABYLON = require("babylonjs"); var LOADERS = require("babylonjs-loaders"); global.XMLHttpRequest = require("xhr2").XMLHttpRequest; @@ -44,35 +45,34 @@ var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(20, 20, 100), sce var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, BABYLON.Vector3.Zero(), scene); -BABYLON.SceneLoader.ImportMesh("", "https://playground.babylonjs.com/scenes/", "skull.babylon", scene, function (newMeshes) { - camera.target = newMeshes[0]; +BABYLON.ImportMeshAsync("https://playground.babylonjs.com/scenes/skull.babylon", scene).then(function ({ meshes }) { + camera.target = meshes[0]; + + console.log("Meshes loaded from babylon file: " + meshes.length); + for (let index = 0; index < meshes.length; index++) { + console.log(meshes[index].toString()); + } - console.log("Meshes loaded from babylon file: " + newMeshes.length); - for (let index = 0; index < newMeshes.length; index++) { - console.log(newMeshes[index].toString()); + BABYLON.ImportMeshAsync("https://www.babylonjs.com/assets/DamagedHelmet/glTF/DamagedHelmet.gltf", scene).then(function ({ meshes }) { + console.log("Meshes loaded from gltf file: " + meshes.length); + for (let index = 0; index < meshes.length; index++) { + console.log(meshes[index].toString()); } + }); - BABYLON.SceneLoader.ImportMesh("", "https://www.babylonjs.com/assets/DamagedHelmet/glTF/", "DamagedHelmet.gltf", scene, function (meshes) { - console.log("Meshes loaded from gltf file: " + meshes.length); - for (let index = 0; index < meshes.length; index++) { - console.log(meshes[index].toString()); - } - }); - - console.log("render started") - engine.runRenderLoop(function() { - scene.render(); - }) + console.log("render started"); + engine.runRenderLoop(function () { + scene.render(); + }); }); - ``` ## Configuration You can specifiy some options in the `NullEngine` constructor: -``` -var engine = new BABYLON.NullEngine({ +```javascript +const engine = new BABYLON.NullEngine({ renderWidth: 512, renderHeight: 256, textureSize: 512 @@ -85,7 +85,8 @@ With `textureSize`, you can define the size of all textures (which will be all b ## Troubleshooting While the goal of the NullEngine is to completely replace the Engine class, some features cannot be used server side: -* `camera.attachControl` cannot be used as it requires an HTML element -* `DynamicTexture` cannot be used as it relies on HTML canvas + +- `camera.attachControl` cannot be used as it requires an HTML element +- `DynamicTexture` cannot be used as it relies on HTML canvas Furthermore as we already mentioned earlier, you need to provide an implementation of the `XMLHttpRequest` class. diff --git a/content/toolsAndResources/assetLibrarian.md b/content/toolsAndResources/assetLibrarian.md index 1bb7459d4..2722f5603 100644 --- a/content/toolsAndResources/assetLibrarian.md +++ b/content/toolsAndResources/assetLibrarian.md @@ -10,7 +10,7 @@ video-content: ## The Asset Librarian -Babylon.js provides a large asset library of free models, environments, textures, materials, particles, sounds, etc. These assets are free for you to use under the [Creative Commons 0](https://creativecommons.org/share-your-work/public-domain/cc0/) license. +Babylon.js provides a large asset library of free models, environments, textures, materials, particles, sounds, etc. These assets are free for you to use under the [Creative Commons 0](https://creativecommons.org/share-your-work/public-domain/cc0/) license. Intrdouced in Babaylon.js 5.0, the Asset Librarian is an incredibly simply tool allowing you to access this full library of content directly in the playground with simple lines of code. @@ -19,9 +19,10 @@ Using the "Assets" namespace, you can easily add any asset into your scene. For example adding the Pirate Fort mesh into your scene is as simple as this: ```javascript -BABYLON.SceneLoader.ImportMesh("", Assets.meshes.pirateFort.rootUrl, Assets.meshes.pirateFort.filename, scene) +BABYLON.ImportMeshAsync(Assets.meshes.pirateFort.rootUrl + Assets.meshes.pirateFort.filename, scene); ``` - + + ## Adding To the Asset Library @@ -29,12 +30,13 @@ The raw files for the assets available through the Asset Librarian can be found This library of assets is free, open-source, and available for anyone to use under the [Creative Commons 0](https://creativecommons.org/share-your-work/public-domain/cc0/) license. -If you would like to contribute your own assets to the asset repository, you are ABSOLUTELY encouraged to do so. This is the spirit of Open Source Software. +If you would like to contribute your own assets to the asset repository, you are ABSOLUTELY encouraged to do so. This is the spirit of Open Source Software. We will gladly accept assets that: -1) Are family-friendly, safe, and welcoming to everyone. -2) Can be useful to anyone (no custom airplane turbine mounting bracket CAD files please) + +1. Are family-friendly, safe, and welcoming to everyone. +2. Can be useful to anyone (no custom airplane turbine mounting bracket CAD files please) Please be aware that the Babylon Development Team reserves the right to accept, decline, or remove ANY asset being contributed to this library for any reason, including: overusing hosting resources, content that is not family-friendly, safe, or welcoming of everyone, content that does not benefit the greater community. -Also please understand that by contributing your assets to the asset repository, you are offering your assets freely under the [Creative Commons 0](https://creativecommons.org/share-your-work/public-domain/cc0/) license. Only assets that are given freely to the public domain will be accepted. \ No newline at end of file +Also please understand that by contributing your assets to the asset repository, you are offering your assets freely under the [Creative Commons 0](https://creativecommons.org/share-your-work/public-domain/cc0/) license. Only assets that are given freely to the public domain will be accepted. diff --git a/content/toolsAndResources/thePlayground/externalPGAssets.md b/content/toolsAndResources/thePlayground/externalPGAssets.md index 78bddcb4e..9c778370e 100644 --- a/content/toolsAndResources/thePlayground/externalPGAssets.md +++ b/content/toolsAndResources/thePlayground/externalPGAssets.md @@ -1,17 +1,17 @@ --- title: Using External Assets In the Playground -image: +image: description: Learn how to use external assets in the playground in Babylon.js. keywords: babylon.js, tools, resources, playground further-reading: - - title: Textures Directly Available to the Playground - url: /toolsAndResources/assetLibraries/availableTextures - - title: Meshes Available to Import into the Playground - url: /toolsAndResources/assetLibraries/availableMeshes + - title: Textures Directly Available to the Playground + url: /toolsAndResources/assetLibraries/availableTextures + - title: Meshes Available to Import into the Playground + url: /toolsAndResources/assetLibraries/availableMeshes video-overview: video-content: - - title: Using External Assets In the Playground - url: https://youtu.be/3D6BtdMnnQI + - title: Using External Assets In the Playground + url: https://youtu.be/3D6BtdMnnQI --- # Using External Assets in the Playground @@ -20,70 +20,71 @@ Sometimes you might want to load you own assets into the playground. Should the It is very likely that the issue you are struggling with can be isolated and presented in a simplified and more focused form using basic meshes and existing [textures](/toolsAndResources/assetLibraries/availableTextures) and [models](/toolsAndResources/assetLibraries/availableMeshes). -Doing this will lead to quicker answers as your question will be more understandable, since few people want to work through long sections of code. Using the existing assets will also ensure that they remain reachable and the playgrounds you create will still be a useful resource in the future. However should you still wish to use your own assets then this page describes ways of doing so. +Doing this will lead to quicker answers as your question will be more understandable, since few people want to work through long sections of code. Using the existing assets will also ensure that they remain reachable and the playgrounds you create will still be a useful resource in the future. However should you still wish to use your own assets then this page describes ways of doing so. - Any site hosting you assets must be [CORS compliant](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) and use the secure [https](https://en.wikipedia.org/wiki/HTTPS) protocol. +Any site hosting you assets must be [CORS compliant](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) and use the secure [https](https://en.wikipedia.org/wiki/HTTPS) protocol. ## From github.com ### using raw.githubusercontent.com - - ensure that your git repo is set to **public** - - navigate to your file. We'll take as example https://github.com/BabylonJS/MeshesLibrary/blob/master/PBR_Spheres.glb - - remove `/blob/` part - - replace `https://github.com` by `https://raw.githubusercontent.com` - - you now have raw access to your file `https://raw.githubusercontent.com/BabylonJS/MeshesLibrary/master/PBR_Spheres.glb` +- ensure that your git repo is set to **public** +- navigate to your file. We'll take as example https://github.com/BabylonJS/MeshesLibrary/blob/master/PBR_Spheres.glb +- remove `/blob/` part +- replace `https://github.com` by `https://raw.githubusercontent.com` +- you now have raw access to your file `https://raw.githubusercontent.com/BabylonJS/MeshesLibrary/master/PBR_Spheres.glb` ```javascript -BABYLON.SceneLoader.ImportMesh("", "https://raw.githubusercontent.com/BabylonJS/MeshesLibrary/master/", "PBR_Spheres.glb", scene); +BABYLON.ImportMeshAsync("https://raw.githubusercontent.com/BabylonJS/MeshesLibrary/master/PBR_Spheres.glb", scene); ``` - + ### using rawgit.com - + You were able to use [GitHub](https://github.com/) with a link generated by the **[RawGit](https://rawgit.com/)** site to ensure correct MIME type. Unfortunately this site has now closed. Any existing links to files using **RawGit** can be updated using **[Raw Git to jsDelivr](https://www.jsdelivr.com/rawgit)**. Changes should be made to **RawGit** links before October 2019. ### using jsdelivr.com - To use **[jsDelivr](https://www.jsdelivr.com)** with a file: - - ensure that your git repo is set to **public** - - let's say you have a file named _myFile.babylon_ on **github**, go to that file in your repository and click on the commit number. - - then in the address bar copy the part after `https://github.com/`, for example +To use **[jsDelivr](https://www.jsdelivr.com)** with a file: + +- ensure that your git repo is set to **public** +- let's say you have a file named _myFile.babylon_ on **github**, go to that file in your repository and click on the commit number. +- then in the address bar copy the part after `https://github.com/`, for example - ```javascript +```javascript myGithubUserName/myRepository/commit/2bd79648e08709145cd9575e6679b2ea360f12f6 - ``` +``` - - replace `/commit/` with `@` +- replace `/commit/` with `@` - ```javascript +```javascript myGithubUserName/myRepository@2bd79648e08709145cd9575e6679b2ea360f12f6 - ``` +``` - - add at the front `https://cdn.jsdelivr.net/gh/` +- add at the front `https://cdn.jsdelivr.net/gh/` - ```javascript +```javascript https://cdn.jsdelivr.net/gh/myGithubUserName/myRepository@2bd79648e08709145cd9575e6679b2ea360f12f6 - ``` +``` -- *(optional)* by adding the filename to the end, you now have direct download access +- _(optional)_ by adding the filename to the end, you now have direct download access - ```javascript +```javascript https://cdn.jsdelivr.net/gh/myGithubUserName/myRepository@2bd79648e08709145cd9575e6679b2ea360f12f6/myFile.babylon - ``` +``` You now have all necessary data to load your meshes. - + ```javascript -BABYLON.SceneLoader.ImportMesh("", "https://cdn.jsdelivr.net/gh/myGithubUserName/myRepository@2bd79648e08709145cd9575e6679b2ea360f12f6", "myFile.babylon", scene); +BABYLON.ImportMeshAsync("https://cdn.jsdelivr.net/gh/myGithubUserName/myRepository@2bd79648e08709145cd9575e6679b2ea360f12f6/myFile.babylon", scene); ``` From our MeshesLibrary repo, [using PBR_Spheres.glb](https://github.com/BabylonJS/MeshesLibrary/commit/fa494961cbe0b8d44854b3cf8aa8268ba211741a): - + ## From Gitlab.com @@ -94,7 +95,7 @@ You have to configure your own [Gitlab pages](https://docs.gitlab.com/ee/user/pr When done, just use the direct link in the loader: ```javascript -BABYLON.SceneLoader.ImportMesh("", "https://yourpages.gitlab.io/yourScene/", "myFile.babylon", scene); +BABYLON.ImportMeshAsync("https://yourpages.gitlab.io/yourScene/myFile.babylon", scene); ``` ## From dropbox.com @@ -111,7 +112,7 @@ BABYLON.SceneLoader.ImportMesh("", "https://yourpages.gitlab.io/yourScene/", "my It can be used in this way: ```javascript -BABYLON.SceneLoader.ImportMesh("", "https://dl.dropbox.com/s/rANdoMGeneR4tedLink/", "my-file.glb", scene); +BABYLON.ImportMeshAsync("https://dl.dropbox.com/s/rANdoMGeneR4tedLink/my-file.glb", scene); ``` @@ -131,7 +132,7 @@ var texture = new BABYLON.Texture("https://i.imgur.com/yn98ktz.png", scene); -## Embedded assets +## Embedded assets You can make a raw text copy-paste of your assets, like the content of a .gltf file. @@ -146,13 +147,15 @@ Note that you need to use `Append` so you can define the plugin to use as there var blob = new Blob([json]); var url = URL.createObjectURL(blob); - BABYLON.SceneLoader.Append(url, "", scene, function(scene) { + BABYLON.AppendSceneAsync(url, scene, { + pluginExtension: ".gltf" + }).then(function() { scene.createDefaultCameraOrLight(true, true, true), scene.createDefaultEnvironment(); - }, null, null, ".gltf"); + }); ``` - + ## Javascript files @@ -164,16 +167,15 @@ var s = document.createElement("script"); s.src = url; document.head.appendChild(s); -var createScene = function() { +var createScene = function () { + //Scene set up code - //Scene set up code + s.onload = function () { + //any code calling on loaded file code + }; - s.onload = function() { - //any code calling on loaded file code - } - - return scene; -} + return scene; +}; ``` diff --git a/lib/buildUtils/tools.ts b/lib/buildUtils/tools.ts index 3b92a656c..29040fdf4 100644 --- a/lib/buildUtils/tools.ts +++ b/lib/buildUtils/tools.ts @@ -145,7 +145,7 @@ export const generateExampleImage = async (type: "pg" | "nme" | "nge" | "sfe" | } else { await page.waitForSelector("#graph-canvas", { visible: true, timeout: 60000 }); } - await new Promise((r) => setTimeout(r, 1000)); // wait for the page to load + await new Promise((r) => setTimeout(r, 1500)); // wait for the page to load const imageUrl = optionalFilename ? join(process.cwd(), "public", optionalFilename) : getExampleImagePath({ type, id }); if (type !== "pg") { diff --git a/public/img/playgroundsAndNMEs/pg-0MDAYA.png b/public/img/playgroundsAndNMEs/pg-0MDAYA.png new file mode 100644 index 000000000..e550a1504 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-0MDAYA.png differ diff --git a/public/img/playgroundsAndNMEs/pg-2KRNG9-3849.png b/public/img/playgroundsAndNMEs/pg-2KRNG9-3849.png new file mode 100644 index 000000000..cdefdcc18 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-2KRNG9-3849.png differ diff --git a/public/img/playgroundsAndNMEs/pg-2KRNG9-3850.png b/public/img/playgroundsAndNMEs/pg-2KRNG9-3850.png new file mode 100644 index 000000000..66054089f Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-2KRNG9-3850.png differ diff --git a/public/img/playgroundsAndNMEs/pg-92Y727-462.png b/public/img/playgroundsAndNMEs/pg-92Y727-462.png new file mode 100644 index 000000000..bbb40c185 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-92Y727-462.png differ diff --git a/public/img/playgroundsAndNMEs/pg-92Y727-463.png b/public/img/playgroundsAndNMEs/pg-92Y727-463.png new file mode 100644 index 000000000..7153f8587 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-92Y727-463.png differ diff --git a/public/img/playgroundsAndNMEs/pg-A8VZGP-288.png b/public/img/playgroundsAndNMEs/pg-A8VZGP-288.png new file mode 100644 index 000000000..39d83c2fd Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-A8VZGP-288.png differ diff --git a/public/img/playgroundsAndNMEs/pg-ABDDD6-122.png b/public/img/playgroundsAndNMEs/pg-ABDDD6-122.png new file mode 100644 index 000000000..94e29c89f Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-ABDDD6-122.png differ diff --git a/public/img/playgroundsAndNMEs/pg-CP2RN9-235.png b/public/img/playgroundsAndNMEs/pg-CP2RN9-235.png new file mode 100644 index 000000000..28b604863 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-CP2RN9-235.png differ diff --git a/public/img/playgroundsAndNMEs/pg-FQWPBI-11.png b/public/img/playgroundsAndNMEs/pg-FQWPBI-11.png new file mode 100644 index 000000000..6836427af Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-FQWPBI-11.png differ diff --git a/public/img/playgroundsAndNMEs/pg-IX12S2-139.png b/public/img/playgroundsAndNMEs/pg-IX12S2-139.png new file mode 100644 index 000000000..864fee850 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-IX12S2-139.png differ diff --git a/public/img/playgroundsAndNMEs/pg-KEY4S4-93.png b/public/img/playgroundsAndNMEs/pg-KEY4S4-93.png new file mode 100644 index 000000000..05e75dc8f Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-KEY4S4-93.png differ diff --git a/public/img/playgroundsAndNMEs/pg-KY0N7T-68.png b/public/img/playgroundsAndNMEs/pg-KY0N7T-68.png new file mode 100644 index 000000000..11cb9de50 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-KY0N7T-68.png differ diff --git a/public/img/playgroundsAndNMEs/pg-M05L0C-5.png b/public/img/playgroundsAndNMEs/pg-M05L0C-5.png new file mode 100644 index 000000000..a277d4571 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-M05L0C-5.png differ diff --git a/public/img/playgroundsAndNMEs/pg-MDVD75-27.png b/public/img/playgroundsAndNMEs/pg-MDVD75-27.png new file mode 100644 index 000000000..d10ac4667 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-MDVD75-27.png differ diff --git a/public/img/playgroundsAndNMEs/pg-UIAXAU-29.png b/public/img/playgroundsAndNMEs/pg-UIAXAU-29.png new file mode 100644 index 000000000..5adca2904 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-UIAXAU-29.png differ diff --git a/public/img/playgroundsAndNMEs/pg-WGZLGJ-11075.png b/public/img/playgroundsAndNMEs/pg-WGZLGJ-11075.png new file mode 100644 index 000000000..6ae0cea5d Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-WGZLGJ-11075.png differ diff --git a/public/img/playgroundsAndNMEs/pg-YIU90M-1416.png b/public/img/playgroundsAndNMEs/pg-YIU90M-1416.png new file mode 100644 index 000000000..864fee850 Binary files /dev/null and b/public/img/playgroundsAndNMEs/pg-YIU90M-1416.png differ diff --git a/public/webpages/app1.html b/public/webpages/app1.html index 9f0a3b024..edccbbbee 100644 --- a/public/webpages/app1.html +++ b/public/webpages/app1.html @@ -40,7 +40,7 @@ const scene = new BABYLON.Scene(engine); - BABYLON.SceneLoader.ImportMeshAsync("", "https://assets.babylonjs.com/meshes/", "box.babylon"); + BABYLON.ImportMeshAsync("https://assets.babylonjs.com/meshes/box.babylon"); const camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 15, new BABYLON.Vector3(0, 0, 0)); camera.attachControl(canvas, true); diff --git a/public/webpages/app3.html b/public/webpages/app3.html index 34fcd0bd2..f08c500ef 100644 --- a/public/webpages/app3.html +++ b/public/webpages/app3.html @@ -68,7 +68,7 @@

Instructions

const scene = new BABYLON.Scene(engine); - BABYLON.SceneLoader.ImportMeshAsync("", "https://assets.babylonjs.com/meshes/", "village.glb"); + BABYLON.ImportMeshAsync("https://assets.babylonjs.com/meshes/village.glb"); const camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 15, new BABYLON.Vector3(0, 0, 0)); camera.attachControl(canvas, true);