trid3d 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +102 -2
- package/package.json +41 -4
- package/trid/index.js +53 -0
- package/trid/loaders/obj.js +206 -0
- package/trid/loaders/texture.js +56 -0
- package/trid/math/projection.js +49 -0
- package/trid/math/transform.js +302 -0
- package/trid/render/canvasRenderer.js +634 -0
- package/trid/render/color.js +22 -0
- package/trid/render/draw.js +146 -0
- package/trid/render/effects.js +265 -0
- package/trid/render/loop.js +42 -0
- package/trid/render/normals.js +90 -0
- package/trid/render/shapes.js +230 -0
- package/trid/render/webglRenderer.js +613 -0
- package/trid/scene.js +167 -0
- package/trid/tools/dragObject.js +89 -0
- package/trid/tools/flyCamera.js +111 -0
- package/trid/tools/fpsMeter.js +51 -0
- package/trid/tools/helpers.js +85 -0
- package/trid/tools/hoverHighlight.js +62 -0
- package/trid/tools/index.js +8 -0
- package/trid/tools/manager.js +241 -0
- package/trid/tools/objUploader.js +153 -0
- package/trid/tools/orbitCamera.js +132 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ZachR622
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,103 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="docs/public/logo.svg" width="96" alt="Trid logo">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<h1 align="center">Trid</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">A small 3D library for the HTML canvas. No dependencies, no build step.</p>
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
Trid gives you a scene, a camera, shapes, model loading and mouse/keyboard tools, all in plain ES modules you can drop next to your page.
|
|
12
|
+
|
|
13
|
+
> **Status:** early. Objects can be wireframes or filled and shaded; textures and shaders are on the way.
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
- **Scene** — holds a canvas, a camera and your objects, and runs the frame loop for you.
|
|
18
|
+
- **Shapes** — cubes, boxes and spheres built in, or any mesh you define as vertices and edges.
|
|
19
|
+
- **Filled faces** — give an object a `material` to fill and shade its faces, flat or smooth, with one directional light.
|
|
20
|
+
- **Textures** — images, canvases or videos on faces, with texture coordinates from built-in shapes and OBJ files.
|
|
21
|
+
- **Effects** — stack shader effects like toon, rim and edge glow, gradients and fog on a material, or write your own in GLSL.
|
|
22
|
+
- **Two renderers** — the canvas 2D context by default, or `WebGLRenderer` for exact depth and big models, with the same scene code.
|
|
23
|
+
- **OBJ files** — load models from a URL, or let users drop their own `.obj` files on the canvas.
|
|
24
|
+
- **Camera** — position, yaw, pitch and field of view, with near-plane clipping.
|
|
25
|
+
- **Tools** — orbit and fly cameras, object dragging, hover highlight, an FPS meter and an OBJ uploader, one line each. Writing your own is a plain object with a few methods.
|
|
26
|
+
- **Pure math** — every transform and projection step is exported, so you can use the pipeline piece by piece.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npm install trid3d
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
No bundler? Use the CDN with an import map, or copy the `trid/` folder next to your page and import `./trid/index.js`:
|
|
35
|
+
|
|
36
|
+
```html
|
|
37
|
+
<script type="importmap">
|
|
38
|
+
{ "imports": { "trid3d": "https://cdn.jsdelivr.net/npm/trid3d@0.1/trid/index.js" } }
|
|
39
|
+
</script>
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
```html
|
|
45
|
+
<canvas id="canvas"></canvas>
|
|
46
|
+
<script type="module" src="main.js"></script>
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```js
|
|
50
|
+
// main.js
|
|
51
|
+
import { Scene, makeShape, OrbitCamera } from "trid3d";
|
|
52
|
+
|
|
53
|
+
const scene = new Scene(document.getElementById("canvas"), { width: 800, height: 400 });
|
|
54
|
+
const cube = scene.add({ mesh: makeShape("cube"), color: "#E9806E" }); // wireframe
|
|
55
|
+
const ball = scene.add({ mesh: makeShape("sphere"), material: { fill: "#8ab4f8" } }); // filled and shaded
|
|
56
|
+
ball.pos.x = 0.8;
|
|
57
|
+
|
|
58
|
+
scene.use(new OrbitCamera()); // drag to orbit, scroll to zoom
|
|
59
|
+
scene.start((dt) => (cube.rot.y += dt));
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Without a bundler, serve the folder (`python3 -m http.server`) instead of opening the file directly: browsers block module imports from `file://` pages.
|
|
63
|
+
|
|
64
|
+
### Loading a model
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
import { loadOBJ } from "trid3d";
|
|
68
|
+
|
|
69
|
+
const mesh = await loadOBJ("models/teapot.obj", { fit: 1 }); // centered, 1 unit wide
|
|
70
|
+
scene.add({ mesh });
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Or let users load their own: `scene.use(new ObjUploader())` accepts dropped `.obj` files, and `uploader.open()` shows a file dialog.
|
|
74
|
+
|
|
75
|
+
## Project layout
|
|
76
|
+
|
|
77
|
+
| Folder | Content |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `trid/index.js` | Entry file: exports everything (`"trid3d"`) |
|
|
80
|
+
| `trid/scene.js` | The `Scene` class |
|
|
81
|
+
| `trid/math/` | Transforms, camera directions, projection |
|
|
82
|
+
| `trid/render/` | Renderers (Canvas 2D, WebGL), effects, shapes, drawing, frame loop |
|
|
83
|
+
| `trid/loaders/` | OBJ and texture loading |
|
|
84
|
+
| `trid/tools/` | Camera, object and overlay tools |
|
|
85
|
+
| `docs/` | Documentation site with live demos |
|
|
86
|
+
|
|
87
|
+
## Documentation
|
|
88
|
+
|
|
89
|
+
The docs explain every class, option and function, with live demos. To run them locally (Node 18+):
|
|
90
|
+
|
|
91
|
+
```sh
|
|
92
|
+
npm install
|
|
93
|
+
npm run docs:dev
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
See [`docs/README.md`](docs/README.md) for building and editing the docs.
|
|
97
|
+
|
|
98
|
+
## Roadmap
|
|
99
|
+
|
|
100
|
+
- **More shapes** — cylinder, cone, torus, plane/grid
|
|
101
|
+
- **More tools** — rotate/scale objects with the mouse, selection outline
|
|
102
|
+
- **Parent/child transforms** — e.g. a moon orbiting a planet
|
|
103
|
+
- **Tests** for the math functions
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trid3d",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A small 3D library for the HTML canvas: wireframes, filled and smooth faces, textures and shader effects, drawn with Canvas 2D or WebGL. No dependencies.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"3d",
|
|
7
|
+
"canvas",
|
|
8
|
+
"webgl",
|
|
9
|
+
"wireframe",
|
|
10
|
+
"renderer",
|
|
11
|
+
"obj",
|
|
12
|
+
"shader"
|
|
13
|
+
],
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"author": "ZachR622",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/ZachR622/Trid.git"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/ZachR622/Trid#readme",
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/ZachR622/Trid/issues"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"main": "./trid/index.js",
|
|
26
|
+
"module": "./trid/index.js",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": "./trid/index.js",
|
|
29
|
+
"./*": "./trid/*"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"trid"
|
|
33
|
+
],
|
|
34
|
+
"sideEffects": false,
|
|
35
|
+
"scripts": {
|
|
36
|
+
"docs:dev": "vitepress dev docs",
|
|
37
|
+
"docs:build": "vitepress build docs",
|
|
38
|
+
"docs:preview": "vitepress preview docs"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"vitepress": "^1.6.4"
|
|
42
|
+
}
|
|
43
|
+
}
|
package/trid/index.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trid: a small 3D library for the HTML canvas.
|
|
3
|
+
*
|
|
4
|
+
* Everything the library offers, from one file:
|
|
5
|
+
*
|
|
6
|
+
* import { Scene, makeShape, OrbitCamera } from "trid3d"; // with npm
|
|
7
|
+
* import { Scene, makeShape, OrbitCamera } from "./trid/index.js"; // with the folder
|
|
8
|
+
*
|
|
9
|
+
* The individual modules can still be imported directly.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
// Scene
|
|
13
|
+
export { Scene } from "./scene.js";
|
|
14
|
+
|
|
15
|
+
// Shapes and meshes
|
|
16
|
+
export { makeShape, scaleMesh } from "./render/shapes.js";
|
|
17
|
+
|
|
18
|
+
// Renderers
|
|
19
|
+
export { CanvasRenderer, DEFAULT_LIGHT, DEFAULT_AMBIENT } from "./render/canvasRenderer.js";
|
|
20
|
+
export { WebGLRenderer, DEFAULT_FAR } from "./render/webglRenderer.js";
|
|
21
|
+
|
|
22
|
+
// Effects
|
|
23
|
+
export {
|
|
24
|
+
toon, rim, edgeGlow, unlit, gradient, fog,
|
|
25
|
+
buildEffects, effectsKey, uniformType, SURFACE_GLSL,
|
|
26
|
+
} from "./render/effects.js";
|
|
27
|
+
|
|
28
|
+
// Normals (smooth shading)
|
|
29
|
+
export { cornerNormals, creaseOf, newell, DEFAULT_CREASE } from "./render/normals.js";
|
|
30
|
+
|
|
31
|
+
// Loading files
|
|
32
|
+
export { parseOBJ, loadOBJ, readOBJFile, pickOBJFile, fitMesh } from "./loaders/obj.js";
|
|
33
|
+
export { loadTexture, textureReady, textureSize, textureIsLive } from "./loaders/texture.js";
|
|
34
|
+
|
|
35
|
+
// Tools
|
|
36
|
+
export {
|
|
37
|
+
OrbitCamera, FlyCamera, DragObject, HoverHighlight, FpsMeter, ObjUploader,
|
|
38
|
+
ToolManager, pick, screenBounds, worldPerPixel,
|
|
39
|
+
} from "./tools/index.js";
|
|
40
|
+
|
|
41
|
+
// Drawing and the frame loop
|
|
42
|
+
export { clear, point, line, drawWireframe, drawInstance, edgeSegments } from "./render/draw.js";
|
|
43
|
+
export { loop } from "./render/loop.js";
|
|
44
|
+
export { parseColor } from "./render/color.js";
|
|
45
|
+
|
|
46
|
+
// Math
|
|
47
|
+
export {
|
|
48
|
+
localToWorld, worldToCamera, cameraToScreen, worldToScreen,
|
|
49
|
+
cameraForward, cameraRight, cameraUp, clipNear,
|
|
50
|
+
scale, translate, rotateX, rotateY, rotateZ, rotateXYZ,
|
|
51
|
+
DEFAULT_FOV, DEFAULT_NEAR,
|
|
52
|
+
} from "./math/transform.js";
|
|
53
|
+
export { project, screen } from "./math/projection.js";
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wavefront OBJ loading.
|
|
3
|
+
*
|
|
4
|
+
* Reads vertex positions (`v`), texture coordinates (`vt`), normals
|
|
5
|
+
* (`vn`), faces (`f`) and polylines (`l`). Everything else (materials,
|
|
6
|
+
* groups) is ignored for now.
|
|
7
|
+
*
|
|
8
|
+
* OBJ files are right-handed with +Z toward the viewer. Trid is
|
|
9
|
+
* left-handed with the camera looking down +Z, so Z is flipped on
|
|
10
|
+
* load: a model that faces you in Blender faces you in Trid too.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @typedef {Object} ObjMesh
|
|
15
|
+
* @property {{x:number,y:number,z:number}[]} vertices
|
|
16
|
+
* @property {number[][]} edges - Unique edges as [a, b] pairs, ready to draw
|
|
17
|
+
* @property {number[][]} faces - Polygons as vertex index lists
|
|
18
|
+
* @property {{x:number,y:number,z:number}[]} [normals] - Normals from the file (`vn`), if any
|
|
19
|
+
* @property {(number[]|null)[]} [faceNormals] - For each face, the normal index of each corner
|
|
20
|
+
* (null when the file gives none for that face). Used by smooth shading.
|
|
21
|
+
* @property {{u:number,v:number}[]} [uvs] - Texture coordinates from the file (`vt`), if any
|
|
22
|
+
* @property {(number[]|null)[]} [faceUVs] - For each face, the texture coordinate index of
|
|
23
|
+
* each corner (null when the file gives none for that face). Used by textures.
|
|
24
|
+
*
|
|
25
|
+
* @typedef {Object} ObjOptions
|
|
26
|
+
* @property {number} [fit] - If set, center the model on the origin and scale it
|
|
27
|
+
* so its largest side is this long. Handy because OBJ files come in any size.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Parses the text of an OBJ file into a mesh.
|
|
32
|
+
*
|
|
33
|
+
* @param {string} text - Contents of a .obj file
|
|
34
|
+
* @param {ObjOptions} [opts]
|
|
35
|
+
* @returns {ObjMesh}
|
|
36
|
+
* @throws {Error} If a face or line points at a vertex that doesn't exist
|
|
37
|
+
*/
|
|
38
|
+
export function parseOBJ(text, { fit } = {}) {
|
|
39
|
+
const vertices = [];
|
|
40
|
+
const faces = [];
|
|
41
|
+
const lines = [];
|
|
42
|
+
const normals = [];
|
|
43
|
+
const faceNormals = []; // per face: normal index of each corner, or null
|
|
44
|
+
const uvs = [];
|
|
45
|
+
const faceUVs = []; // per face: texture coordinate index of each corner, or null
|
|
46
|
+
|
|
47
|
+
const src = text.split(/\r?\n/);
|
|
48
|
+
|
|
49
|
+
for (let n = 0; n < src.length; n++) {
|
|
50
|
+
const line = src[n].trim();
|
|
51
|
+
|
|
52
|
+
if (line === "" || line[0] === "#") continue;
|
|
53
|
+
|
|
54
|
+
const parts = line.split(/\s+/);
|
|
55
|
+
const kind = parts[0];
|
|
56
|
+
|
|
57
|
+
if (kind === "v") {
|
|
58
|
+
vertices.push({ x: +(parts[1] ?? 0), y: +(parts[2] ?? 0), z: -(parts[3] ?? 0) });
|
|
59
|
+
} else if (kind === "vt") {
|
|
60
|
+
uvs.push({ u: +(parts[1] ?? 0), v: +(parts[2] ?? 0) });
|
|
61
|
+
} else if (kind === "vn") {
|
|
62
|
+
normals.push({ x: +(parts[1] ?? 0), y: +(parts[2] ?? 0), z: -(parts[3] ?? 0) });
|
|
63
|
+
} else if (kind === "f" || kind === "l") {
|
|
64
|
+
// "7", "7/1", "7//3", "7/1/3" all point at vertex 7. Negative = counted from the end.
|
|
65
|
+
const ids = parts.slice(1).map((p) => {
|
|
66
|
+
const i = parseInt(p, 10);
|
|
67
|
+
const idx = i < 0 ? vertices.length + i : i - 1;
|
|
68
|
+
if (!Number.isInteger(idx) || idx < 0 || idx >= vertices.length) {
|
|
69
|
+
throw new Error(`OBJ line ${n + 1}: bad vertex index "${p}"`);
|
|
70
|
+
}
|
|
71
|
+
return idx;
|
|
72
|
+
});
|
|
73
|
+
if (kind === "f" && ids.length >= 3) {
|
|
74
|
+
faces.push(ids.reverse()); // flipping Z flips the winding
|
|
75
|
+
// "7//3" and "7/1/3": the third number is the corner's normal
|
|
76
|
+
const ns = parts.slice(1).map((p) => {
|
|
77
|
+
const s = p.split("/")[2];
|
|
78
|
+
if (!s) return -1;
|
|
79
|
+
const i = parseInt(s, 10);
|
|
80
|
+
const idx = i < 0 ? normals.length + i : i - 1;
|
|
81
|
+
return idx >= 0 && idx < normals.length ? idx : -1;
|
|
82
|
+
});
|
|
83
|
+
faceNormals.push(ns.includes(-1) ? null : ns.reverse());
|
|
84
|
+
// "7/1" and "7/1/3": the second number is the corner's texture coordinate
|
|
85
|
+
const ts = parts.slice(1).map((p) => {
|
|
86
|
+
const s = p.split("/")[1];
|
|
87
|
+
if (!s) return -1;
|
|
88
|
+
const i = parseInt(s, 10);
|
|
89
|
+
const idx = i < 0 ? uvs.length + i : i - 1;
|
|
90
|
+
return idx >= 0 && idx < uvs.length ? idx : -1;
|
|
91
|
+
});
|
|
92
|
+
faceUVs.push(ts.includes(-1) ? null : ts.reverse());
|
|
93
|
+
} else if (kind === "l" && ids.length >= 2) lines.push(ids);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const seen = new Set();
|
|
98
|
+
const edges = [];
|
|
99
|
+
const addEdge = (a, b) => {
|
|
100
|
+
if (a === b) return;
|
|
101
|
+
|
|
102
|
+
// (2 to the power of 32) = 4294967296
|
|
103
|
+
// The parser uses it to turn an edge into a single number
|
|
104
|
+
const key = a < b ? a * 4294967296 + b : b * 4294967296 + a;
|
|
105
|
+
|
|
106
|
+
if (seen.has(key)) return;
|
|
107
|
+
|
|
108
|
+
seen.add(key);
|
|
109
|
+
edges.push([a, b]);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
for (const f of faces) {
|
|
113
|
+
for (let i = 0; i < f.length; i++) addEdge(f[i], f[(i + 1) % f.length]);
|
|
114
|
+
}
|
|
115
|
+
for (const l of lines) {
|
|
116
|
+
for (let i = 0; i < l.length - 1; i++) addEdge(l[i], l[i + 1]);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const mesh = { vertices, edges, faces };
|
|
120
|
+
// Normals from the file, used by smooth shading
|
|
121
|
+
if (faceNormals.some((n) => n)) {
|
|
122
|
+
mesh.normals = normals;
|
|
123
|
+
mesh.faceNormals = faceNormals;
|
|
124
|
+
}
|
|
125
|
+
// Texture coordinates from the file
|
|
126
|
+
if (faceUVs.some((t) => t)) {
|
|
127
|
+
mesh.uvs = uvs;
|
|
128
|
+
mesh.faceUVs = faceUVs;
|
|
129
|
+
}
|
|
130
|
+
if (fit != null) fitMesh(mesh, fit);
|
|
131
|
+
return mesh;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Centers a mesh on the origin and scales it so its largest side is `size`.
|
|
136
|
+
* Changes the mesh in place.
|
|
137
|
+
*
|
|
138
|
+
* @param {{ vertices:{x:number,y:number,z:number}[] }} mesh
|
|
139
|
+
* @param {number} [size=1]
|
|
140
|
+
* @returns The same mesh
|
|
141
|
+
*/
|
|
142
|
+
export function fitMesh(mesh, size = 1) {
|
|
143
|
+
const vs = mesh.vertices;
|
|
144
|
+
if (vs.length === 0) return mesh;
|
|
145
|
+
|
|
146
|
+
const min = { x: Infinity, y: Infinity, z: Infinity };
|
|
147
|
+
const max = { x: -Infinity, y: -Infinity, z: -Infinity };
|
|
148
|
+
for (const v of vs) {
|
|
149
|
+
for (const k of ["x", "y", "z"]) {
|
|
150
|
+
if (v[k] < min[k]) min[k] = v[k];
|
|
151
|
+
if (v[k] > max[k]) max[k] = v[k];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const cx = (min.x + max.x) / 2, cy = (min.y + max.y) / 2, cz = (min.z + max.z) / 2;
|
|
156
|
+
const largest = Math.max(max.x - min.x, max.y - min.y, max.z - min.z);
|
|
157
|
+
const s = largest > 0 ? size / largest : 1;
|
|
158
|
+
|
|
159
|
+
for (const v of vs) {
|
|
160
|
+
v.x = (v.x - cx) * s;
|
|
161
|
+
v.y = (v.y - cy) * s;
|
|
162
|
+
v.z = (v.z - cz) * s;
|
|
163
|
+
}
|
|
164
|
+
return mesh;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Downloads an OBJ file and parses it.
|
|
169
|
+
*
|
|
170
|
+
* @param {string} url
|
|
171
|
+
* @param {ObjOptions} [opts]
|
|
172
|
+
* @returns {Promise<ObjMesh>}
|
|
173
|
+
*/
|
|
174
|
+
export async function loadOBJ(url, opts) {
|
|
175
|
+
const res = await fetch(url);
|
|
176
|
+
if (!res.ok) throw new Error(`Could not load ${url} (${res.status})`);
|
|
177
|
+
return parseOBJ(await res.text(), opts);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Parses an OBJ file the user picked or dropped (a `File` or `Blob`).
|
|
182
|
+
*
|
|
183
|
+
* @param {Blob} file
|
|
184
|
+
* @param {ObjOptions} [opts]
|
|
185
|
+
* @returns {Promise<ObjMesh>}
|
|
186
|
+
*/
|
|
187
|
+
export async function readOBJFile(file, opts) {
|
|
188
|
+
return parseOBJ(await file.text(), opts);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Opens the browser's file dialog for .obj files.
|
|
193
|
+
* Must be called from a user action, like a button click.
|
|
194
|
+
*
|
|
195
|
+
* @returns {Promise<File|null>} The chosen file, or null if the dialog was cancelled
|
|
196
|
+
*/
|
|
197
|
+
export function pickOBJFile() {
|
|
198
|
+
return new Promise((resolve) => {
|
|
199
|
+
const input = document.createElement("input");
|
|
200
|
+
input.type = "file";
|
|
201
|
+
input.accept = ".obj";
|
|
202
|
+
input.addEventListener("change", () => resolve(input.files?.[0] ?? null));
|
|
203
|
+
input.addEventListener("cancel", () => resolve(null));
|
|
204
|
+
input.click();
|
|
205
|
+
});
|
|
206
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Textures: images drawn on faces.
|
|
3
|
+
*
|
|
4
|
+
* A material's `texture` can be anything the canvas can draw:
|
|
5
|
+
* an `<img>`, a `<canvas>`, a `<video>` or an `ImageBitmap`.
|
|
6
|
+
* Canvases and videos are read again every frame, so they can change.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Loads an image to use as a texture.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} url
|
|
13
|
+
* @returns {Promise<HTMLImageElement>} The image, fully loaded
|
|
14
|
+
* @throws {Error} If the image can't be loaded
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* const crate = await loadTexture("textures/crate.png");
|
|
18
|
+
* scene.add({ mesh: makeShape("cube"), material: { texture: crate } });
|
|
19
|
+
*/
|
|
20
|
+
export function loadTexture(url) {
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const img = new Image();
|
|
23
|
+
// Lets WebGL use images from other sites when they allow it (CORS)
|
|
24
|
+
img.crossOrigin = "anonymous";
|
|
25
|
+
img.onload = () => resolve(img);
|
|
26
|
+
img.onerror = () => reject(new Error(`Could not load texture ${url}`));
|
|
27
|
+
img.src = url;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Whether a texture source has pixels to draw yet. */
|
|
32
|
+
export function textureReady(src) {
|
|
33
|
+
if (!src) return false;
|
|
34
|
+
if (typeof HTMLImageElement !== "undefined" && src instanceof HTMLImageElement) {
|
|
35
|
+
return src.complete && src.naturalWidth > 0;
|
|
36
|
+
}
|
|
37
|
+
if (typeof HTMLVideoElement !== "undefined" && src instanceof HTMLVideoElement) {
|
|
38
|
+
return src.readyState >= 2;
|
|
39
|
+
}
|
|
40
|
+
return (src.width ?? 0) > 0 && (src.height ?? 0) > 0;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Pixel size of a texture source. */
|
|
44
|
+
export function textureSize(src) {
|
|
45
|
+
return {
|
|
46
|
+
w: src.naturalWidth || src.videoWidth || src.width || 0,
|
|
47
|
+
h: src.naturalHeight || src.videoHeight || src.height || 0,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Whether a source can change over time (canvas, video), so it's read every frame. */
|
|
52
|
+
export function textureIsLive(src) {
|
|
53
|
+
return (typeof HTMLCanvasElement !== "undefined" && src instanceof HTMLCanvasElement)
|
|
54
|
+
|| (typeof HTMLVideoElement !== "undefined" && src instanceof HTMLVideoElement)
|
|
55
|
+
|| (typeof OffscreenCanvas !== "undefined" && src instanceof OffscreenCanvas);
|
|
56
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Converts normalized device coordinates (-1 to +1)
|
|
3
|
+
* into actual screen (pixel) coordinates.
|
|
4
|
+
*
|
|
5
|
+
* Normalized space:
|
|
6
|
+
* x: -1 (left) -> +1 (right)
|
|
7
|
+
* y: -1 (bottom)-> +1 (top)
|
|
8
|
+
*
|
|
9
|
+
* Canvas space:
|
|
10
|
+
* x: 0 -> width
|
|
11
|
+
* y: 0 -> height (top-down)
|
|
12
|
+
*
|
|
13
|
+
* @param {{x:number, y:number}} p - Normalized 2D point
|
|
14
|
+
* @param {number} w - Canvas width
|
|
15
|
+
* @param {number} h - Canvas height
|
|
16
|
+
* @returns {{x:number, y:number}} Screen-space point
|
|
17
|
+
*/
|
|
18
|
+
export function screen(p, w, h) {
|
|
19
|
+
return {
|
|
20
|
+
x: (p.x + 1) / 2 * w,
|
|
21
|
+
y: (1 - (p.y + 1) / 2) * h,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Projects a 3D point onto a 2D plane using
|
|
27
|
+
* a perspective projection.
|
|
28
|
+
*
|
|
29
|
+
* The result is in normalized device coordinates (-1 to +1).
|
|
30
|
+
* `fov` is the vertical field of view; X is divided by `aspect`
|
|
31
|
+
* so shapes are not stretched on non-square canvases.
|
|
32
|
+
*
|
|
33
|
+
* NOTE:
|
|
34
|
+
* - z must be > 0 (in front of the camera)
|
|
35
|
+
* - smaller z => appears larger
|
|
36
|
+
* - larger z => appears smaller
|
|
37
|
+
*
|
|
38
|
+
* @param {{x:number, y:number, z:number}} p - 3D point (camera space)
|
|
39
|
+
* @param {number} fov - Vertical field of view in radians (default: 90°)
|
|
40
|
+
* @param {number} aspect - Canvas width / height (default: 1)
|
|
41
|
+
* @returns {{x:number, y:number}} 2D projected point
|
|
42
|
+
*/
|
|
43
|
+
export function project(p, fov = Math.PI / 2, aspect = 1) {
|
|
44
|
+
const f = 1 / Math.tan(fov / 2);
|
|
45
|
+
return {
|
|
46
|
+
x: (p.x * f) / (p.z * aspect),
|
|
47
|
+
y: (p.y * f) / p.z,
|
|
48
|
+
};
|
|
49
|
+
}
|