Skip to content

Commit

Permalink
Extract SceneLoader state and functions from static class to module
Browse files Browse the repository at this point in the history
  • Loading branch information
ryantrem committed Aug 9, 2024
1 parent aa72b27 commit 93c4a86
Show file tree
Hide file tree
Showing 11 changed files with 995 additions and 1,109 deletions.
1,990 changes: 932 additions & 1,058 deletions packages/dev/core/src/Loading/sceneLoader.ts

Large diffs are not rendered by default.

8 changes: 3 additions & 5 deletions packages/dev/loaders/src/OBJ/objFileLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Vector2 } from "core/Maths/math.vector";
import { Tools } from "core/Misc/tools";
import type { AbstractMesh } from "core/Meshes/abstractMesh";
import type { ISceneLoaderPluginAsync, ISceneLoaderPluginFactory, ISceneLoaderPlugin, ISceneLoaderAsyncResult } from "core/Loading/sceneLoader";
import { SceneLoader } from "core/Loading/sceneLoader";
import { registerSceneLoaderPlugin } from "core/Loading/sceneLoader";
import { AssetContainer } from "core/assetContainer";
import type { Scene } from "core/scene";
import type { WebRequest } from "core/Misc/webRequest";
Expand Down Expand Up @@ -362,7 +362,5 @@ export class OBJFileLoader implements ISceneLoaderPluginAsync, ISceneLoaderPlugi
}
}

if (SceneLoader) {
//Add this loader into the register plugin
SceneLoader.RegisterPlugin(new OBJFileLoader());
}
//Add this loader into the register plugin
registerSceneLoaderPlugin(new OBJFileLoader());
8 changes: 3 additions & 5 deletions packages/dev/loaders/src/SPLAT/splatFileLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
ISceneLoaderPluginExtensions,
ISceneLoaderProgressEvent,
} from "core/Loading/sceneLoader";
import { SceneLoader } from "core/Loading/sceneLoader";
import { registerSceneLoaderPlugin } from "core/Loading/sceneLoader";
import { GaussianSplattingMesh } from "core/Meshes/GaussianSplatting/gaussianSplattingMesh";
import type { AssetContainer } from "core/assetContainer";
import type { Scene } from "core/scene";
Expand Down Expand Up @@ -125,7 +125,5 @@ export class SPLATFileLoader implements ISceneLoaderPluginAsync, ISceneLoaderPlu
}
}

if (SceneLoader) {
//Add this loader into the register plugin
SceneLoader.RegisterPlugin(new SPLATFileLoader());
}
//Add this loader into the register plugin
registerSceneLoaderPlugin(new SPLATFileLoader());
6 changes: 2 additions & 4 deletions packages/dev/loaders/src/STL/stlFileLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { VertexBuffer } from "core/Buffers/buffer";
import type { AbstractMesh } from "core/Meshes/abstractMesh";
import { Mesh } from "core/Meshes/mesh";
import type { ISceneLoaderPlugin, ISceneLoaderPluginExtensions } from "core/Loading/sceneLoader";
import { SceneLoader } from "core/Loading/sceneLoader";
import { registerSceneLoaderPlugin } from "core/Loading/sceneLoader";
import { AssetContainer } from "core/assetContainer";
import type { Scene } from "core/scene";

Expand Down Expand Up @@ -287,6 +287,4 @@ export class STLFileLoader implements ISceneLoaderPlugin {
}
}

if (SceneLoader) {
SceneLoader.RegisterPlugin(new STLFileLoader());
}
registerSceneLoaderPlugin(new STLFileLoader());
6 changes: 2 additions & 4 deletions packages/dev/loaders/src/glTF/glTFFileLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type {
ISceneLoaderPluginExtensions,
ISceneLoaderAsyncResult,
} from "core/Loading/sceneLoader";
import { SceneLoader } from "core/Loading/sceneLoader";
import { registerSceneLoaderPlugin } from "core/Loading/sceneLoader";
import type { SceneLoaderPluginOptions } from "core/Loading/sceneLoader";
import { AssetContainer } from "core/assetContainer";
import type { Scene, IDisposable } from "core/scene";
Expand Down Expand Up @@ -1303,6 +1303,4 @@ export class GLTFFileLoader extends GLTFLoaderOptions implements IDisposable, IS
private _endPerformanceCounterDisabled(counterName: string): void {}
}

if (SceneLoader) {
SceneLoader.RegisterPlugin(new GLTFFileLoader());
}
registerSceneLoaderPlugin(new GLTFFileLoader());
17 changes: 16 additions & 1 deletion packages/public/@babylonjs/viewer-alpha/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,24 @@ To use the higher level `HTML3DElement` you can import the `@babylonjs/viewer` m
<html lang="en">
<body>
<script type="module">
import '@babylonjs/viewer-alpha';
import '@babylonjs/viewer';
</script>
<babylon-viewer src="https://playground.babylonjs.com/scenes/BoomBox.glb"></babylon-viewer>
</body>
</html>
```
## CDN/Direct usage
If you want to use the viewer directly in a browser without any build tools, you can use the self-contained ESM bundle (which includes all dependencies) through a CDN such as [UNPKG](https://unpkg.com/) or [jsDelivr](https://www.jsdelivr.com/) like this:
```html
<html lang="en">
<body>
<script type="module" src="https://unpkg.com/@babylonjs/viewer@preview/dist/babylon-viewer.esm.min.js"></script>
<babylon-viewer src="https://playground.babylonjs.com/scenes/BoomBox.glb"></babylon-viewer>
</body>
</html>
```
See the [codesandbox.io](https://codesandbox.io/p/sandbox/babylon-viewer-ws82xr) example for a live demo.
2 changes: 1 addition & 1 deletion packages/tools/viewer-alpha/generateCoverageReports.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { readFileSync } from "fs";
import path from "path";
import open from "open";
import chalk from "chalk";
import { generateFlameChart } from "../../../scripts/folderSizeFlameChart.js";
import { generateFlameChart } from "../../../scripts/folderSizeFlameChart.mjs";

const [scriptPath, analyzeDirectory, coverageDirectory, originalDirectory, rawDirectory] = process.argv.slice(1);

Expand Down
4 changes: 2 additions & 2 deletions packages/tools/viewer-alpha/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"compile": "tsc -b tsconfig.build.json",
"bundle:analyze": "rimraf dist/analyze && rollup -c rollup.config.analyze.mjs",
"bundle:coverage": "rimraf dist/coverage && rollup -c rollup.config.coverage.mjs",
"analyze": "npm run bundle:analyze && node ../../../scripts/folderSizeFlameChart dist/analyze \"**/*.js\" dist/analyze/flameChart",
"import-chains": "node -e \"require('../../../scripts/queryRollupStats.js').queryRollupStats(process.argv[1], 'dist/analyze/stats.json')\"",
"analyze": "npm run bundle:analyze && node ../../../scripts/folderSizeFlameChart.mjs dist/analyze \"**/*.js\" dist/analyze/flameChart",
"import-chains": "node -e \"require('../../../scripts/queryRollupStats.js').queryRollupStats(process.argv[1], process.argv[2], 'dist/analyze/stats.json')\"",
"instrument": "npm run bundle:coverage && nyc --exclude-node-modules=false instrument dist/coverage/original dist/coverage/instrumented",
"report-coverage": "node generateCoverageReports.mjs dist/analyze dist/coverage dist/coverage/original dist/coverage/raw",
"test": "echo \"Error: no test specified\" && exit 1"
Expand Down
4 changes: 2 additions & 2 deletions packages/tools/viewer-alpha/src/viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { AbstractEngine, AssetContainer, FramingBehavior, IDisposable, Mesh

import { ArcRotateCamera } from "core/Cameras/arcRotateCamera";
import { HemisphericLight } from "core/Lights/hemisphericLight";
import { SceneLoader } from "core/Loading/sceneLoader";
import { loadAssetContainerAsync } from "core/Loading/sceneLoader";
import { PBRMaterial } from "core/Materials/PBR/pbrMaterial";
import { CubeTexture } from "core/Materials/Textures/cubeTexture";
import { Texture } from "core/Materials/Textures/texture";
Expand Down Expand Up @@ -132,7 +132,7 @@ export class Viewer implements IDisposable {
await this._loadModelLock.lockAsync(async () => {
this._throwIfDisposedOrAborted(abortSignal, abortController.signal);
this._details.model?.dispose();
this._details.model = await SceneLoader.LoadAssetContainerAsync(finalSource, this._details.scene);
this._details.model = await loadAssetContainerAsync(finalSource, this._details.scene);
this._details.model.addAllToScene();
this._reframeCamera();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
// node folderSizeFlameChart.js [pattern=**/*] [outputFile=FoldersSizes]
// Example: node folderSizeFlameChart.js . "**/*.ts,!**/*.d.ts,!**/test/**"

const child_process = require("child_process");
const fs = require("fs");
const path = require("path");
const os = require("os");
const https = require("https");
const glob = require("glob");
const chalk = require("chalk");
const open = require("open");
import child_process from "child_process";
import fs from "fs";
import path from "path";
import os from "os";
import https from "https";
import { glob } from "glob";
import chalk from "chalk";
import open from "open";

async function downloadFlameGraphScript() {
// This is the temp path where the flamegraph.pl script will be downloaded
Expand Down Expand Up @@ -56,7 +56,7 @@ async function downloadFlameGraphScript() {
* @param {function} coerceSize A function to coerce the size of a file. If not provided, the actual size is used.
* @returns {Promise<void>} A promise that resolves when the flame chart has been generated.
*/
async function generateFlameChart(folder, pattern, outputFile, chartSubtitle, coerceSize) {
export async function generateFlameChart(folder, pattern, outputFile, chartSubtitle, coerceSize) {
const flameGraphScriptPath = await downloadFlameGraphScript();

// Resolve to an absolute path
Expand Down Expand Up @@ -103,7 +103,7 @@ async function generateFlameChart(folder, pattern, outputFile, chartSubtitle, co
child_process.execSync(flameGraphCommand);
}

if (require.main === module) {
if (import.meta.url === `file://${process.argv[1]}`) {
const [scriptPath, folder = ".", pattern = "**", outputFile = "FoldersSizes"] = process.argv.slice(1);

console.log(chalk.bold(`${path.basename(scriptPath)} ${folder} ${pattern} ${outputFile}`));
Expand All @@ -113,7 +113,3 @@ if (require.main === module) {
open(`${outputFile}.svg`);
});
}

module.exports = {
generateFlameChart,
};
35 changes: 22 additions & 13 deletions scripts/queryRollupStats.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,34 @@ function stringToColorHash(str) {
return color;
}

function queryRollupStats(filter, statsFilePath) {
function queryRollupStats(filter, maxDepth, statsFilePath) {
if (!maxDepth) {
maxDepth = Number.POSITIVE_INFINITY;
}
const { nodeMetas } = JSON.parse(fs.readFileSync(statsFilePath, "utf8"));
const referenceStack = [];
const seenStacks = new Set();

function traverse(uid) {
function traverse(uid, depth) {
const node = nodeMetas[uid];
referenceStack.push(node.id);

if (node.importedBy.length === 0) {
for (let reference of referenceStack) {
const folder = path.dirname(reference);
const file = path.basename(reference);
reference = chalk.hex(stringToColorHash(reference))(`${folder}/${chalk.bold(file)}`);
console.log(reference);
if (node.importedBy.length === 0 || depth >= maxDepth) {
const stack = referenceStack.join(" -> ");
if (!seenStacks.has(stack)) {
seenStacks.add(stack);

for (let reference of referenceStack) {
const folder = path.dirname(reference);
const file = path.basename(reference);
reference = chalk.hex(stringToColorHash(reference))(`${folder}/${chalk.bold(file)}`);
console.log(reference);
}
console.log();
}
console.log();
} else {
for (const importedBy of node.importedBy) {
traverse(importedBy.uid);
traverse(importedBy.uid, depth + 1);
}
}

Expand All @@ -56,12 +65,12 @@ function queryRollupStats(filter, statsFilePath) {
.filter(([key, value]) => value.id.toLowerCase().includes(filter.toLocaleLowerCase()))
.map(([key, value]) => key);

matches.forEach(traverse);
matches.forEach((match) => traverse(match, 1));
}

if (require.main === module) {
const [scriptPath, filter, statsFilePath = "stats.json"] = process.argv.slice(1);
queryRollupStats(filter, statsFilePath);
const [scriptPath, filter, maxDepth, statsFilePath = "stats.json"] = process.argv.slice(1);
queryRollupStats(filter, maxDepth, statsFilePath);
}

module.exports = {
Expand Down

0 comments on commit 93c4a86

Please sign in to comment.