@dice-o-rolla/dice-renderer-three 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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Dice O Rolla
2
+ Copyright 2026 Dmitriy Pyankov
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # `@dice-o-rolla/dice-renderer-three`
2
+
3
+ Official Three.js WebGL rendering adapters for Dice O Rolla, including the standard perspective
4
+ renderer and `TopDownDiceRenderer` for overhead application surfaces.
5
+
6
+ ```ts
7
+ import { ThreeDiceRenderer, TopDownDiceRenderer } from '@dice-o-rolla/dice-renderer-three';
8
+ ```
9
+
10
+ Most browser applications should use the preassembled entry point from
11
+ `@dice-o-rolla/dice-engine/browser`.
12
+
13
+ Licensed under Apache-2.0. See `LICENSE`, `NOTICE`, and `THIRD_PARTY_NOTICES.md` in the package.
@@ -0,0 +1,18 @@
1
+ # Third-party notices
2
+
3
+ ## 3DDiceRoller
4
+
5
+ The geometry model and physical dice behavior were informed by 3DDiceRoller by MajorVictory,
6
+ released under The Unlicense.
7
+
8
+ - Source: <https://github.com/MajorVictory/3DDiceRoller>
9
+ - License: <https://unlicense.org/>
10
+
11
+ ## Runtime dependencies
12
+
13
+ - Three.js is distributed under the MIT License: <https://github.com/mrdoob/three.js>.
14
+ - Rapier is distributed under the Apache License 2.0:
15
+ <https://github.com/dimforge/rapier.js>.
16
+
17
+ The UNLICENSED anvil-dice-engine project was used only for architectural comparison. No source code,
18
+ assets, sounds, shaders, or textures from that project are included in this distribution.
@@ -0,0 +1,7 @@
1
+ export { ThreeMaterialFactory, type DiceMaterialStyle, type FaceLabel, type FaceMaterialOptions, } from './material-factory.js';
2
+ export { createPolyhedronGeometry, createFaceUvs, DEFAULT_THREE_THEME, getFaceLabel, ThreeDiceMeshFactory, type ThreeDiceMesh, } from './mesh-factory.js';
3
+ export { ThreeCamera, ThreeLighting, ThreeScene } from './scene.js';
4
+ export { TopDownCamera, type TopDownCameraOptions } from './top-down-camera.js';
5
+ export { TopDownDiceRenderer, type TopDownDiceRendererOptions } from './top-down-dice-renderer.js';
6
+ export { ThreeDiceRenderer, type ThreeDiceRendererOptions } from './three-dice-renderer.js';
7
+ export { applyInterpolatedTransform } from './transform.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { ThreeMaterialFactory, } from './material-factory.js';
2
+ export { createPolyhedronGeometry, createFaceUvs, DEFAULT_THREE_THEME, getFaceLabel, ThreeDiceMeshFactory, } from './mesh-factory.js';
3
+ export { ThreeCamera, ThreeLighting, ThreeScene } from './scene.js';
4
+ export { TopDownCamera } from './top-down-camera.js';
5
+ export { TopDownDiceRenderer } from './top-down-dice-renderer.js';
6
+ export { ThreeDiceRenderer } from './three-dice-renderer.js';
7
+ export { applyInterpolatedTransform } from './transform.js';
@@ -0,0 +1,11 @@
1
+ import type { RendererTheme } from '@dice-o-rolla/dice-renderer';
2
+ import { MeshStandardMaterial } from 'three';
3
+ export type DiceMaterialStyle = RendererTheme['material'];
4
+ export type FaceLabel = string | number | readonly number[];
5
+ export interface FaceMaterialOptions {
6
+ readonly labelScale?: number;
7
+ }
8
+ export declare class ThreeMaterialFactory {
9
+ createFace(label: FaceLabel, theme: RendererTheme, options?: FaceMaterialOptions): MeshStandardMaterial;
10
+ }
11
+ export declare function requiresOrientationDot(label: FaceLabel): boolean;
@@ -0,0 +1,53 @@
1
+ import { CanvasTexture, MeshStandardMaterial, SRGBColorSpace } from 'three';
2
+ const ORIENTATION_DOT_LABELS = new Set(['6', '9', '60', '90']);
3
+ export class ThreeMaterialFactory {
4
+ createFace(label, theme, options = {}) {
5
+ const canvas = document.createElement('canvas');
6
+ canvas.width = 256;
7
+ canvas.height = 256;
8
+ const context = canvas.getContext('2d');
9
+ if (context === null)
10
+ throw new Error('A 2D canvas context is required for die labels');
11
+ context.fillStyle = theme.bodyColor;
12
+ context.fillRect(0, 0, canvas.width, canvas.height);
13
+ context.fillStyle = theme.labelColor;
14
+ const scalarLabel = typeof label === 'string' || typeof label === 'number';
15
+ const labelScale = options.labelScale ?? 1;
16
+ const fontSize = (scalarLabel && String(label).length >= 2 ? 100 : 128) * labelScale;
17
+ context.font = `700 ${fontSize}px system-ui, sans-serif`;
18
+ context.textAlign = 'center';
19
+ context.textBaseline = 'middle';
20
+ if (scalarLabel) {
21
+ const labelY = canvas.height / 2 + 8;
22
+ context.fillText(String(label), canvas.width / 2, labelY);
23
+ if (requiresOrientationDot(label)) {
24
+ context.beginPath();
25
+ context.arc(canvas.width / 2, labelY + fontSize * 0.55, canvas.width * 0.025, 0, Math.PI * 2);
26
+ context.fill();
27
+ }
28
+ }
29
+ else {
30
+ context.font = '700 58px system-ui, sans-serif';
31
+ context.save();
32
+ context.translate(canvas.width / 2, canvas.height / 2);
33
+ for (const value of label) {
34
+ context.fillText(String(value), 0, -canvas.height * 0.31);
35
+ context.rotate((Math.PI * 2) / 3);
36
+ }
37
+ context.restore();
38
+ }
39
+ const texture = new CanvasTexture(canvas);
40
+ texture.colorSpace = SRGBColorSpace;
41
+ return new MeshStandardMaterial({
42
+ color: 0xffffff,
43
+ map: texture,
44
+ metalness: theme.metalness,
45
+ roughness: theme.roughness,
46
+ });
47
+ }
48
+ }
49
+ export function requiresOrientationDot(label) {
50
+ if (typeof label !== 'string' && typeof label !== 'number')
51
+ return false;
52
+ return ORIENTATION_DOT_LABELS.has(String(label));
53
+ }
@@ -0,0 +1,20 @@
1
+ import type { PolygonDefinition, PolyhedronDefinition } from '@dice-o-rolla/dice-geometry';
2
+ import type { RendererTheme } from '@dice-o-rolla/dice-renderer';
3
+ import { BufferGeometry, Mesh, type MeshStandardMaterial } from 'three';
4
+ import { ThreeMaterialFactory } from './material-factory.js';
5
+ type Vector2Tuple = readonly [u: number, v: number];
6
+ export declare const DEFAULT_THREE_THEME: RendererTheme;
7
+ export interface ThreeDiceMesh {
8
+ readonly mesh: Mesh<BufferGeometry, MeshStandardMaterial[]>;
9
+ dispose(): void;
10
+ }
11
+ export declare function createPolyhedronGeometry(definition: PolyhedronDefinition, scale?: number): BufferGeometry;
12
+ export declare class ThreeDiceMeshFactory {
13
+ #private;
14
+ constructor(materials?: ThreeMaterialFactory);
15
+ create(definition: PolyhedronDefinition, theme?: RendererTheme, scale?: number, faceLabels?: Readonly<Record<number, string | number>>): ThreeDiceMesh;
16
+ createD6(theme?: RendererTheme, scale?: number): ThreeDiceMesh;
17
+ }
18
+ export declare function createFaceUvs(definition: PolyhedronDefinition, face: PolygonDefinition): readonly Vector2Tuple[];
19
+ export declare function getFaceLabel(definition: PolyhedronDefinition, face: PolygonDefinition, faceLabels?: Readonly<Record<number, string | number>>): string | number | readonly number[];
20
+ export {};
@@ -0,0 +1,151 @@
1
+ import { D6_DEFINITION } from '@dice-o-rolla/dice-geometry';
2
+ import { BufferGeometry, Float32BufferAttribute, Mesh } from 'three';
3
+ import { ThreeMaterialFactory } from './material-factory.js';
4
+ const D10_LABEL_SCALE = 0.7;
5
+ const D10_UV_EXTENT = 0.86;
6
+ export const DEFAULT_THREE_THEME = Object.freeze({
7
+ material: 'plastic',
8
+ bodyColor: '#f7f3e8',
9
+ labelColor: '#181818',
10
+ roughness: 0.28,
11
+ metalness: 0,
12
+ });
13
+ export function createPolyhedronGeometry(definition, scale = 1) {
14
+ if (!Number.isFinite(scale) || scale <= 0) {
15
+ throw new RangeError('scale must be a positive finite number');
16
+ }
17
+ const positions = [];
18
+ const uvs = [];
19
+ const geometry = new BufferGeometry();
20
+ definition.faces.forEach((face, materialIndex) => {
21
+ const start = positions.length / 3;
22
+ const uvByVertex = createFaceUvs(definition, face);
23
+ for (let index = 1; index < face.indices.length - 1; index += 1) {
24
+ for (const faceIndex of [0, index, index + 1]) {
25
+ const vertexIndex = face.indices[faceIndex];
26
+ const vertex = vertexIndex === undefined ? undefined : definition.vertices[vertexIndex];
27
+ const uv = uvByVertex[faceIndex];
28
+ if (vertex === undefined || uv === undefined) {
29
+ throw new RangeError(`Face ${face.value} references an invalid vertex`);
30
+ }
31
+ positions.push(vertex[0] * scale, vertex[1] * scale, vertex[2] * scale);
32
+ uvs.push(uv[0], uv[1]);
33
+ }
34
+ }
35
+ geometry.addGroup(start, positions.length / 3 - start, materialIndex);
36
+ });
37
+ geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
38
+ geometry.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
39
+ geometry.computeVertexNormals();
40
+ geometry.computeBoundingSphere();
41
+ return geometry;
42
+ }
43
+ export class ThreeDiceMeshFactory {
44
+ #materials;
45
+ constructor(materials = new ThreeMaterialFactory()) {
46
+ this.#materials = materials;
47
+ }
48
+ create(definition, theme = DEFAULT_THREE_THEME, scale = 1, faceLabels) {
49
+ const geometry = createPolyhedronGeometry(definition, scale);
50
+ const materials = definition.faces.map((face) => this.#materials.createFace(getFaceLabel(definition, face, faceLabels), theme, definition.id === 'd10' ? { labelScale: D10_LABEL_SCALE } : undefined));
51
+ const mesh = new Mesh(geometry, materials);
52
+ mesh.castShadow = true;
53
+ mesh.receiveShadow = true;
54
+ return {
55
+ mesh,
56
+ dispose() {
57
+ geometry.dispose();
58
+ for (const material of materials) {
59
+ material.map?.dispose();
60
+ material.dispose();
61
+ }
62
+ },
63
+ };
64
+ }
65
+ createD6(theme = DEFAULT_THREE_THEME, scale = 1) {
66
+ return this.create(D6_DEFINITION, theme, scale);
67
+ }
68
+ }
69
+ export function createFaceUvs(definition, face) {
70
+ if (definition.id !== 'd10') {
71
+ return face.indices.map((_, index) => {
72
+ const angle = Math.PI / 2 - (index / face.indices.length) * Math.PI * 2;
73
+ return [0.5 - Math.cos(angle) * 0.5, 0.5 + Math.sin(angle) * 0.5];
74
+ });
75
+ }
76
+ const vertices = face.indices.map((vertexIndex) => {
77
+ const vertex = definition.vertices[vertexIndex];
78
+ if (vertex === undefined) {
79
+ throw new RangeError(`Face ${face.value} references an invalid vertex`);
80
+ }
81
+ return vertex;
82
+ });
83
+ const centroid = average(vertices);
84
+ const vertical = normalize(subtract(vertices[0], centroid));
85
+ const normal = normalize(cross(subtract(vertices[1], vertices[0]), subtract(vertices[2], vertices[0])));
86
+ let horizontal = normalize(cross(vertical, normal));
87
+ if (dot(subtract(vertices[1], centroid), horizontal) > 0) {
88
+ horizontal = scaleVector(horizontal, -1);
89
+ }
90
+ const projected = vertices.map((vertex) => {
91
+ const offset = subtract(vertex, centroid);
92
+ return [dot(offset, horizontal), dot(offset, vertical)];
93
+ });
94
+ const xCoordinates = projected.map(([x]) => x);
95
+ const yCoordinates = projected.map(([, y]) => y);
96
+ const minX = Math.min(...xCoordinates);
97
+ const maxX = Math.max(...xCoordinates);
98
+ const minY = Math.min(...yCoordinates);
99
+ const maxY = Math.max(...yCoordinates);
100
+ const extent = Math.max(maxX - minX, maxY - minY);
101
+ if (extent <= Number.EPSILON) {
102
+ throw new RangeError(`Face ${face.value} cannot be projected to texture coordinates`);
103
+ }
104
+ const uvScale = D10_UV_EXTENT / extent;
105
+ const centerX = (minX + maxX) / 2;
106
+ const centerY = (minY + maxY) / 2;
107
+ return projected.map(([x, y]) => [0.5 + (x - centerX) * uvScale, 0.5 + (y - centerY) * uvScale]);
108
+ }
109
+ function average(vertices) {
110
+ const sum = vertices.reduce((result, vertex) => [result[0] + vertex[0], result[1] + vertex[1], result[2] + vertex[2]], [0, 0, 0]);
111
+ return scaleVector(sum, 1 / vertices.length);
112
+ }
113
+ function subtract(left, right) {
114
+ return [left[0] - right[0], left[1] - right[1], left[2] - right[2]];
115
+ }
116
+ function scaleVector(vector, multiplier) {
117
+ return [vector[0] * multiplier, vector[1] * multiplier, vector[2] * multiplier];
118
+ }
119
+ function dot(left, right) {
120
+ return left[0] * right[0] + left[1] * right[1] + left[2] * right[2];
121
+ }
122
+ function cross(left, right) {
123
+ return [
124
+ left[1] * right[2] - left[2] * right[1],
125
+ left[2] * right[0] - left[0] * right[2],
126
+ left[0] * right[1] - left[1] * right[0],
127
+ ];
128
+ }
129
+ function normalize(vector) {
130
+ const length = Math.hypot(...vector);
131
+ if (length <= Number.EPSILON)
132
+ throw new RangeError('Cannot normalize a zero-length vector');
133
+ return scaleVector(vector, 1 / length);
134
+ }
135
+ export function getFaceLabel(definition, face, faceLabels) {
136
+ const override = faceLabels?.[face.value];
137
+ if (override !== undefined)
138
+ return override;
139
+ if (definition.id === 'd4') {
140
+ return face.indices.map((vertexIndex) => {
141
+ const oppositeFace = definition.faces.find((candidate) => !candidate.indices.includes(vertexIndex));
142
+ if (oppositeFace === undefined) {
143
+ throw new RangeError(`No d4 result is associated with vertex ${vertexIndex}`);
144
+ }
145
+ return oppositeFace.value;
146
+ });
147
+ }
148
+ if (definition.id === 'd10' && face.value === 10)
149
+ return 0;
150
+ return face.value;
151
+ }
@@ -0,0 +1,17 @@
1
+ import { PerspectiveCamera, Scene } from 'three';
2
+ export declare class ThreeScene {
3
+ #private;
4
+ readonly value: Scene<import("three").Object3DEventMap>;
5
+ constructor();
6
+ dispose(): void;
7
+ }
8
+ export declare class ThreeCamera {
9
+ readonly value: PerspectiveCamera;
10
+ constructor();
11
+ resize(width: number, height: number): void;
12
+ }
13
+ export declare class ThreeLighting {
14
+ #private;
15
+ constructor(scene: Scene);
16
+ dispose(scene: Scene): void;
17
+ }
package/dist/scene.js ADDED
@@ -0,0 +1,46 @@
1
+ import { AmbientLight, Color, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera, PlaneGeometry, Scene, } from 'three';
2
+ export class ThreeScene {
3
+ value = new Scene();
4
+ #floorGeometry = new PlaneGeometry(20, 20);
5
+ #floorMaterial = new MeshStandardMaterial({ color: 0x20242b, roughness: 0.9 });
6
+ #lighting;
7
+ constructor() {
8
+ this.value.background = new Color(0x101318);
9
+ const floor = new Mesh(this.#floorGeometry, this.#floorMaterial);
10
+ floor.rotation.x = -Math.PI / 2;
11
+ floor.receiveShadow = true;
12
+ this.value.add(floor);
13
+ this.#lighting = new ThreeLighting(this.value);
14
+ }
15
+ dispose() {
16
+ this.#lighting.dispose(this.value);
17
+ this.#floorGeometry.dispose();
18
+ this.#floorMaterial.dispose();
19
+ this.value.clear();
20
+ }
21
+ }
22
+ export class ThreeCamera {
23
+ value = new PerspectiveCamera(42, 1, 0.1, 100);
24
+ constructor() {
25
+ this.value.position.set(7, 8, 9);
26
+ this.value.lookAt(0, 0.8, 0);
27
+ }
28
+ resize(width, height) {
29
+ this.value.aspect = width / height;
30
+ this.value.updateProjectionMatrix();
31
+ }
32
+ }
33
+ export class ThreeLighting {
34
+ #ambient = new AmbientLight(0xffffff, 1.25);
35
+ #key = new DirectionalLight(0xffffff, 3.25);
36
+ constructor(scene) {
37
+ this.#key.position.set(5, 10, 6);
38
+ this.#key.castShadow = true;
39
+ this.#key.shadow.mapSize.set(1024, 1024);
40
+ scene.add(this.#ambient, this.#key);
41
+ }
42
+ dispose(scene) {
43
+ scene.remove(this.#ambient, this.#key);
44
+ this.#key.dispose();
45
+ }
46
+ }
@@ -0,0 +1,21 @@
1
+ import type { DiceRenderer, RenderDieState, RendererTheme, RendererViewport } from '@dice-o-rolla/dice-renderer';
2
+ export interface ThreeDiceRendererOptions extends Partial<RendererTheme> {
3
+ readonly antialias?: boolean;
4
+ readonly observeResize?: boolean;
5
+ readonly maxPixelRatio?: number;
6
+ readonly maxViewportDimension?: number;
7
+ readonly maxFramebufferPixels?: number;
8
+ }
9
+ export declare class ThreeDiceRenderer implements DiceRenderer {
10
+ #private;
11
+ constructor(container: HTMLElement, options?: ThreeDiceRendererOptions);
12
+ initialize(): void;
13
+ createDie(state: RenderDieState): void;
14
+ updateDie(state: RenderDieState): void;
15
+ removeDie(id: string): void;
16
+ render(alpha: number): void;
17
+ resize(viewport: RendererViewport): void;
18
+ setTheme(theme: RendererTheme): void;
19
+ clear(): void;
20
+ destroy(): void;
21
+ }
@@ -0,0 +1,184 @@
1
+ import { getDieGeometry, getRegisteredDieTypes } from '@dice-o-rolla/dice-geometry';
2
+ import { PCFShadowMap, WebGLRenderer } from 'three';
3
+ import { DEFAULT_THREE_THEME, ThreeDiceMeshFactory } from './mesh-factory.js';
4
+ import { ThreeCamera, ThreeScene } from './scene.js';
5
+ import { applyInterpolatedTransform } from './transform.js';
6
+ import { fitViewportToLimits, resolveViewportLimits, validateViewport, } from './viewport-limits.js';
7
+ function copyState(state) {
8
+ return {
9
+ id: state.id,
10
+ geometryId: state.geometryId,
11
+ ...(state.faceLabels === undefined ? {} : { faceLabels: { ...state.faceLabels } }),
12
+ previous: {
13
+ position: { ...state.previous.position },
14
+ quaternion: { ...state.previous.quaternion },
15
+ },
16
+ current: {
17
+ position: { ...state.current.position },
18
+ quaternion: { ...state.current.quaternion },
19
+ },
20
+ };
21
+ }
22
+ export class ThreeDiceRenderer {
23
+ #container;
24
+ #options;
25
+ #meshFactory = new ThreeDiceMeshFactory();
26
+ #entries = new Map();
27
+ #viewportLimits;
28
+ #theme;
29
+ #scene;
30
+ #camera;
31
+ #renderer;
32
+ #resizeObserver;
33
+ #destroyed = false;
34
+ constructor(container, options = {}) {
35
+ this.#container = container;
36
+ this.#options = options;
37
+ this.#viewportLimits = resolveViewportLimits(options);
38
+ this.#theme = {
39
+ material: options.material ?? DEFAULT_THREE_THEME.material,
40
+ bodyColor: options.bodyColor ?? DEFAULT_THREE_THEME.bodyColor,
41
+ labelColor: options.labelColor ?? DEFAULT_THREE_THEME.labelColor,
42
+ roughness: options.roughness ?? DEFAULT_THREE_THEME.roughness,
43
+ metalness: options.metalness ?? DEFAULT_THREE_THEME.metalness,
44
+ };
45
+ }
46
+ initialize() {
47
+ this.#assertAlive();
48
+ if (this.#renderer !== undefined)
49
+ return;
50
+ const scene = new ThreeScene();
51
+ const camera = new ThreeCamera();
52
+ const renderer = new WebGLRenderer({
53
+ antialias: this.#options.antialias ?? true,
54
+ alpha: true,
55
+ powerPreference: 'high-performance',
56
+ });
57
+ renderer.shadowMap.enabled = true;
58
+ renderer.shadowMap.type = PCFShadowMap;
59
+ this.#container.append(renderer.domElement);
60
+ this.#scene = scene;
61
+ this.#camera = camera;
62
+ this.#renderer = renderer;
63
+ this.#resizeToContainer();
64
+ if ((this.#options.observeResize ?? true) && typeof ResizeObserver !== 'undefined') {
65
+ this.#resizeObserver = new ResizeObserver(() => this.#resizeToContainer());
66
+ this.#resizeObserver.observe(this.#container);
67
+ }
68
+ }
69
+ createDie(state) {
70
+ this.#assertInitialized();
71
+ if (this.#entries.has(state.id))
72
+ throw new Error(`A render die with id "${state.id}" already exists`);
73
+ const resource = this.#createResource(state.geometryId, state.faceLabels);
74
+ const ownedState = copyState(state);
75
+ applyInterpolatedTransform(resource.mesh, ownedState, 1);
76
+ this.#scene?.value.add(resource.mesh);
77
+ this.#entries.set(state.id, { resource, state: ownedState });
78
+ }
79
+ updateDie(state) {
80
+ this.#assertInitialized();
81
+ const entry = this.#entries.get(state.id);
82
+ if (entry === undefined)
83
+ throw new Error(`Unknown render die: ${state.id}`);
84
+ if (state.geometryId !== entry.state.geometryId) {
85
+ throw new Error('A die geometry cannot be changed after creation');
86
+ }
87
+ if (!haveEqualFaceLabels(state.faceLabels, entry.state.faceLabels)) {
88
+ throw new Error('Die face labels cannot be changed after creation');
89
+ }
90
+ entry.state = copyState(state);
91
+ }
92
+ removeDie(id) {
93
+ this.#assertAlive();
94
+ const entry = this.#entries.get(id);
95
+ if (entry === undefined)
96
+ return;
97
+ this.#scene?.value.remove(entry.resource.mesh);
98
+ entry.resource.dispose();
99
+ this.#entries.delete(id);
100
+ }
101
+ render(alpha) {
102
+ this.#assertInitialized();
103
+ for (const entry of this.#entries.values()) {
104
+ applyInterpolatedTransform(entry.resource.mesh, entry.state, alpha);
105
+ }
106
+ this.#renderer?.render(this.#scene.value, this.#camera.value);
107
+ }
108
+ resize(viewport) {
109
+ this.#assertInitialized();
110
+ validateViewport(viewport, this.#viewportLimits);
111
+ this.#camera?.resize(viewport.width, viewport.height);
112
+ this.#renderer?.setPixelRatio(viewport.pixelRatio);
113
+ this.#renderer?.setSize(viewport.width, viewport.height, false);
114
+ }
115
+ setTheme(theme) {
116
+ this.#assertAlive();
117
+ this.#theme = { ...theme };
118
+ for (const entry of this.#entries.values()) {
119
+ const replacement = this.#createResource(entry.state.geometryId, entry.state.faceLabels);
120
+ applyInterpolatedTransform(replacement.mesh, entry.state, 1);
121
+ this.#scene?.value.remove(entry.resource.mesh);
122
+ entry.resource.dispose();
123
+ entry.resource = replacement;
124
+ this.#scene?.value.add(replacement.mesh);
125
+ }
126
+ }
127
+ clear() {
128
+ this.#assertAlive();
129
+ for (const id of this.#entries.keys())
130
+ this.removeDie(id);
131
+ }
132
+ destroy() {
133
+ if (this.#destroyed)
134
+ return;
135
+ this.clear();
136
+ this.#resizeObserver?.disconnect();
137
+ this.#resizeObserver = undefined;
138
+ const canvas = this.#renderer?.domElement;
139
+ this.#renderer?.dispose();
140
+ this.#renderer?.forceContextLoss();
141
+ if (canvas?.parentElement === this.#container)
142
+ canvas.remove();
143
+ this.#scene?.dispose();
144
+ this.#scene = undefined;
145
+ this.#camera = undefined;
146
+ this.#renderer = undefined;
147
+ this.#destroyed = true;
148
+ }
149
+ #resizeToContainer() {
150
+ const bounds = this.#container.getBoundingClientRect();
151
+ if (bounds.width <= 0 || bounds.height <= 0)
152
+ return;
153
+ this.resize(fitViewportToLimits({
154
+ width: bounds.width,
155
+ height: bounds.height,
156
+ pixelRatio: globalThis.devicePixelRatio || 1,
157
+ }, this.#viewportLimits));
158
+ }
159
+ #createResource(geometryId, faceLabels) {
160
+ const type = getRegisteredDieTypes().find((registered) => registered === geometryId);
161
+ if (type === undefined)
162
+ throw new Error(`Unsupported geometry: ${geometryId}`);
163
+ return this.#meshFactory.create(getDieGeometry(type), this.#theme, 1, faceLabels);
164
+ }
165
+ #assertAlive() {
166
+ if (this.#destroyed)
167
+ throw new Error('Renderer has been destroyed');
168
+ }
169
+ #assertInitialized() {
170
+ this.#assertAlive();
171
+ if (this.#renderer === undefined)
172
+ throw new Error('Renderer has not been initialized');
173
+ }
174
+ }
175
+ function haveEqualFaceLabels(left, right) {
176
+ if (left === right)
177
+ return true;
178
+ if (left === undefined || right === undefined)
179
+ return false;
180
+ const leftEntries = Object.entries(left);
181
+ const rightEntries = Object.entries(right);
182
+ return (leftEntries.length === rightEntries.length &&
183
+ leftEntries.every(([face, label]) => right[Number(face)] === label));
184
+ }
@@ -0,0 +1,13 @@
1
+ import { PerspectiveCamera } from 'three';
2
+ export interface TopDownCameraOptions {
3
+ readonly trayWidth?: number;
4
+ readonly trayDepth?: number;
5
+ readonly cameraFieldOfViewDegrees?: number;
6
+ readonly cameraPadding?: number;
7
+ }
8
+ export declare class TopDownCamera {
9
+ #private;
10
+ readonly value: PerspectiveCamera;
11
+ constructor(options?: TopDownCameraOptions);
12
+ resize(width: number, height: number): void;
13
+ }
@@ -0,0 +1,43 @@
1
+ import { PerspectiveCamera } from 'three';
2
+ const DEFAULT_TRAY_SIZE = 10;
3
+ const DEFAULT_FIELD_OF_VIEW_DEGREES = 38;
4
+ const DEFAULT_PADDING = 1.5;
5
+ export class TopDownCamera {
6
+ value;
7
+ #trayWidth;
8
+ #trayDepth;
9
+ #fieldOfViewDegrees;
10
+ #padding;
11
+ constructor(options = {}) {
12
+ this.#trayWidth = positiveFinite(options.trayWidth ?? DEFAULT_TRAY_SIZE, 'trayWidth');
13
+ this.#trayDepth = positiveFinite(options.trayDepth ?? DEFAULT_TRAY_SIZE, 'trayDepth');
14
+ this.#fieldOfViewDegrees = options.cameraFieldOfViewDegrees ?? DEFAULT_FIELD_OF_VIEW_DEGREES;
15
+ if (!Number.isFinite(this.#fieldOfViewDegrees) ||
16
+ this.#fieldOfViewDegrees <= 0 ||
17
+ this.#fieldOfViewDegrees >= 180) {
18
+ throw new RangeError('cameraFieldOfViewDegrees must be finite and between 0 and 180');
19
+ }
20
+ this.#padding = positiveFinite(options.cameraPadding ?? DEFAULT_PADDING, 'cameraPadding');
21
+ if (this.#padding < 1)
22
+ throw new RangeError('cameraPadding must be at least 1');
23
+ this.value = new PerspectiveCamera(this.#fieldOfViewDegrees, 1, 0.1, 100);
24
+ this.value.up.set(0, 0, -1);
25
+ }
26
+ resize(width, height) {
27
+ positiveFinite(width, 'width');
28
+ positiveFinite(height, 'height');
29
+ const aspect = width / height;
30
+ const visibleHeight = Math.max(this.#trayDepth, this.#trayWidth / aspect) * this.#padding;
31
+ const cameraHeight = visibleHeight / (2 * Math.tan((this.#fieldOfViewDegrees * Math.PI) / 360));
32
+ this.value.position.set(0, cameraHeight, 0);
33
+ this.value.lookAt(0, 0, 0);
34
+ this.value.aspect = aspect;
35
+ this.value.updateProjectionMatrix();
36
+ }
37
+ }
38
+ function positiveFinite(value, name) {
39
+ if (!Number.isFinite(value) || value <= 0) {
40
+ throw new RangeError(`${name} must be a positive finite number`);
41
+ }
42
+ return value;
43
+ }
@@ -0,0 +1,20 @@
1
+ import type { DiceRenderer, RenderDieState, RendererTheme, RendererViewport } from '@dice-o-rolla/dice-renderer';
2
+ import { type TopDownCameraOptions } from './top-down-camera.js';
3
+ import { type ViewportLimitOptions } from './viewport-limits.js';
4
+ export interface TopDownDiceRendererOptions extends Partial<RendererTheme>, ViewportLimitOptions, TopDownCameraOptions {
5
+ readonly antialias?: boolean;
6
+ readonly observeResize?: boolean;
7
+ }
8
+ export declare class TopDownDiceRenderer implements DiceRenderer {
9
+ #private;
10
+ constructor(container: HTMLElement, options?: TopDownDiceRendererOptions);
11
+ initialize(): void;
12
+ createDie(state: RenderDieState): void;
13
+ updateDie(state: RenderDieState): void;
14
+ removeDie(id: string): void;
15
+ render(alpha: number): void;
16
+ resize(viewport: RendererViewport): void;
17
+ setTheme(theme: RendererTheme): void;
18
+ clear(): void;
19
+ destroy(): void;
20
+ }
@@ -0,0 +1,219 @@
1
+ import { getDieGeometry, getRegisteredDieTypes } from '@dice-o-rolla/dice-geometry';
2
+ import { AmbientLight, DirectionalLight, Mesh, PCFShadowMap, PlaneGeometry, Scene, ShadowMaterial, WebGLRenderer, } from 'three';
3
+ import { DEFAULT_THREE_THEME, ThreeDiceMeshFactory } from './mesh-factory.js';
4
+ import { TopDownCamera } from './top-down-camera.js';
5
+ import { applyInterpolatedTransform } from './transform.js';
6
+ import { fitViewportToLimits, resolveViewportLimits, validateViewport, } from './viewport-limits.js';
7
+ export class TopDownDiceRenderer {
8
+ #container;
9
+ #options;
10
+ #meshFactory = new ThreeDiceMeshFactory();
11
+ #entries = new Map();
12
+ #viewportLimits;
13
+ #trayWidth;
14
+ #trayDepth;
15
+ #theme;
16
+ #scene;
17
+ #camera;
18
+ #renderer;
19
+ #floorGeometry;
20
+ #floorMaterial;
21
+ #keyLight;
22
+ #resizeObserver;
23
+ #destroyed = false;
24
+ constructor(container, options = {}) {
25
+ this.#container = container;
26
+ this.#options = options;
27
+ this.#viewportLimits = resolveViewportLimits(options);
28
+ this.#trayWidth = options.trayWidth ?? 10;
29
+ this.#trayDepth = options.trayDepth ?? 10;
30
+ this.#theme = {
31
+ material: options.material ?? DEFAULT_THREE_THEME.material,
32
+ bodyColor: options.bodyColor ?? DEFAULT_THREE_THEME.bodyColor,
33
+ labelColor: options.labelColor ?? DEFAULT_THREE_THEME.labelColor,
34
+ roughness: options.roughness ?? DEFAULT_THREE_THEME.roughness,
35
+ metalness: options.metalness ?? DEFAULT_THREE_THEME.metalness,
36
+ };
37
+ }
38
+ initialize() {
39
+ this.#assertAlive();
40
+ if (this.#renderer !== undefined)
41
+ return;
42
+ const scene = new Scene();
43
+ const camera = new TopDownCamera(this.#options);
44
+ const floorGeometry = new PlaneGeometry(this.#trayWidth, this.#trayDepth);
45
+ const floorMaterial = new ShadowMaterial({ color: 0x11131a, opacity: 0.16 });
46
+ const floor = new Mesh(floorGeometry, floorMaterial);
47
+ floor.rotation.x = -Math.PI / 2;
48
+ floor.position.y = -0.02;
49
+ floor.receiveShadow = true;
50
+ const ambientLight = new AmbientLight(0xffffff, 1.45);
51
+ const keyLight = new DirectionalLight(0xffffff, 3.4);
52
+ keyLight.position.set(5, 12, 4);
53
+ keyLight.castShadow = true;
54
+ keyLight.shadow.mapSize.set(1024, 1024);
55
+ const shadowExtent = Math.max(this.#trayWidth, this.#trayDepth) * 0.6;
56
+ keyLight.shadow.camera.left = -shadowExtent;
57
+ keyLight.shadow.camera.right = shadowExtent;
58
+ keyLight.shadow.camera.top = shadowExtent;
59
+ keyLight.shadow.camera.bottom = -shadowExtent;
60
+ scene.add(floor, ambientLight, keyLight);
61
+ const renderer = new WebGLRenderer({
62
+ antialias: this.#options.antialias ?? true,
63
+ alpha: true,
64
+ powerPreference: 'high-performance',
65
+ });
66
+ renderer.setClearColor(0x000000, 0);
67
+ renderer.shadowMap.enabled = true;
68
+ renderer.shadowMap.type = PCFShadowMap;
69
+ this.#container.append(renderer.domElement);
70
+ this.#scene = scene;
71
+ this.#camera = camera;
72
+ this.#renderer = renderer;
73
+ this.#floorGeometry = floorGeometry;
74
+ this.#floorMaterial = floorMaterial;
75
+ this.#keyLight = keyLight;
76
+ this.#resizeToContainer();
77
+ if ((this.#options.observeResize ?? true) && typeof ResizeObserver !== 'undefined') {
78
+ this.#resizeObserver = new ResizeObserver(() => this.#resizeToContainer());
79
+ this.#resizeObserver.observe(this.#container);
80
+ }
81
+ }
82
+ createDie(state) {
83
+ this.#assertInitialized();
84
+ if (this.#entries.has(state.id)) {
85
+ throw new Error(`A render die with id "${state.id}" already exists`);
86
+ }
87
+ const resource = this.#createResource(state.geometryId, state.faceLabels);
88
+ const ownedState = copyState(state);
89
+ applyInterpolatedTransform(resource.mesh, ownedState, 1);
90
+ this.#scene?.add(resource.mesh);
91
+ this.#entries.set(state.id, { resource, state: ownedState });
92
+ }
93
+ updateDie(state) {
94
+ this.#assertInitialized();
95
+ const entry = this.#entries.get(state.id);
96
+ if (entry === undefined)
97
+ throw new Error(`Unknown render die: ${state.id}`);
98
+ if (entry.state.geometryId !== state.geometryId) {
99
+ throw new Error('A die geometry cannot be changed after creation');
100
+ }
101
+ if (!haveEqualFaceLabels(entry.state.faceLabels, state.faceLabels)) {
102
+ throw new Error('Die face labels cannot be changed after creation');
103
+ }
104
+ entry.state = copyState(state);
105
+ }
106
+ removeDie(id) {
107
+ this.#assertAlive();
108
+ const entry = this.#entries.get(id);
109
+ if (entry === undefined)
110
+ return;
111
+ this.#scene?.remove(entry.resource.mesh);
112
+ entry.resource.dispose();
113
+ this.#entries.delete(id);
114
+ }
115
+ render(alpha) {
116
+ this.#assertInitialized();
117
+ for (const entry of this.#entries.values()) {
118
+ applyInterpolatedTransform(entry.resource.mesh, entry.state, alpha);
119
+ }
120
+ this.#renderer?.render(this.#scene, this.#camera.value);
121
+ }
122
+ resize(viewport) {
123
+ this.#assertInitialized();
124
+ validateViewport(viewport, this.#viewportLimits);
125
+ this.#camera?.resize(viewport.width, viewport.height);
126
+ this.#renderer?.setPixelRatio(viewport.pixelRatio);
127
+ this.#renderer?.setSize(viewport.width, viewport.height, false);
128
+ }
129
+ setTheme(theme) {
130
+ this.#assertAlive();
131
+ this.#theme = { ...theme };
132
+ for (const entry of this.#entries.values()) {
133
+ const replacement = this.#createResource(entry.state.geometryId, entry.state.faceLabels);
134
+ applyInterpolatedTransform(replacement.mesh, entry.state, 1);
135
+ this.#scene?.remove(entry.resource.mesh);
136
+ entry.resource.dispose();
137
+ entry.resource = replacement;
138
+ this.#scene?.add(replacement.mesh);
139
+ }
140
+ }
141
+ clear() {
142
+ this.#assertAlive();
143
+ for (const id of this.#entries.keys())
144
+ this.removeDie(id);
145
+ }
146
+ destroy() {
147
+ if (this.#destroyed)
148
+ return;
149
+ this.clear();
150
+ this.#resizeObserver?.disconnect();
151
+ this.#keyLight?.dispose();
152
+ this.#floorGeometry?.dispose();
153
+ this.#floorMaterial?.dispose();
154
+ const canvas = this.#renderer?.domElement;
155
+ this.#renderer?.dispose();
156
+ this.#renderer?.forceContextLoss();
157
+ if (canvas?.parentElement === this.#container)
158
+ canvas.remove();
159
+ this.#scene?.clear();
160
+ this.#scene = undefined;
161
+ this.#camera = undefined;
162
+ this.#renderer = undefined;
163
+ this.#floorGeometry = undefined;
164
+ this.#floorMaterial = undefined;
165
+ this.#keyLight = undefined;
166
+ this.#resizeObserver = undefined;
167
+ this.#destroyed = true;
168
+ }
169
+ #resizeToContainer() {
170
+ const bounds = this.#container.getBoundingClientRect();
171
+ if (bounds.width <= 0 || bounds.height <= 0)
172
+ return;
173
+ this.resize(fitViewportToLimits({
174
+ width: bounds.width,
175
+ height: bounds.height,
176
+ pixelRatio: globalThis.devicePixelRatio || 1,
177
+ }, this.#viewportLimits));
178
+ }
179
+ #createResource(geometryId, faceLabels) {
180
+ const type = getRegisteredDieTypes().find((registered) => registered === geometryId);
181
+ if (type === undefined)
182
+ throw new Error(`Unsupported geometry: ${geometryId}`);
183
+ return this.#meshFactory.create(getDieGeometry(type), this.#theme, 1, faceLabels);
184
+ }
185
+ #assertAlive() {
186
+ if (this.#destroyed)
187
+ throw new Error('Renderer has been destroyed');
188
+ }
189
+ #assertInitialized() {
190
+ this.#assertAlive();
191
+ if (this.#scene === undefined || this.#camera === undefined || this.#renderer === undefined) {
192
+ throw new Error('Renderer has not been initialized');
193
+ }
194
+ }
195
+ }
196
+ function copyState(state) {
197
+ return {
198
+ id: state.id,
199
+ geometryId: state.geometryId,
200
+ ...(state.faceLabels === undefined ? {} : { faceLabels: { ...state.faceLabels } }),
201
+ previous: {
202
+ position: { ...state.previous.position },
203
+ quaternion: { ...state.previous.quaternion },
204
+ },
205
+ current: {
206
+ position: { ...state.current.position },
207
+ quaternion: { ...state.current.quaternion },
208
+ },
209
+ };
210
+ }
211
+ function haveEqualFaceLabels(left, right) {
212
+ if (left === right)
213
+ return true;
214
+ if (left === undefined || right === undefined)
215
+ return false;
216
+ const leftEntries = Object.entries(left);
217
+ return (leftEntries.length === Object.keys(right).length &&
218
+ leftEntries.every(([face, label]) => right[Number(face)] === label));
219
+ }
@@ -0,0 +1,3 @@
1
+ import type { RenderDieState } from '@dice-o-rolla/dice-renderer';
2
+ import type { Object3D } from 'three';
3
+ export declare function applyInterpolatedTransform(object: Object3D, state: RenderDieState, alpha: number): void;
@@ -0,0 +1,15 @@
1
+ export function applyInterpolatedTransform(object, state, alpha) {
2
+ if (!Number.isFinite(alpha))
3
+ throw new RangeError('alpha must be finite');
4
+ const t = Math.max(0, Math.min(1, alpha));
5
+ const previous = state.previous;
6
+ const current = state.current;
7
+ object.position.set(previous.position.x + (current.position.x - previous.position.x) * t, previous.position.y + (current.position.y - previous.position.y) * t, previous.position.z + (current.position.z - previous.position.z) * t);
8
+ object.quaternion
9
+ .set(previous.quaternion.x, previous.quaternion.y, previous.quaternion.z, previous.quaternion.w)
10
+ .normalize()
11
+ .slerp(object.quaternion
12
+ .clone()
13
+ .set(current.quaternion.x, current.quaternion.y, current.quaternion.z, current.quaternion.w)
14
+ .normalize(), t);
15
+ }
@@ -0,0 +1,14 @@
1
+ import type { RendererViewport } from '@dice-o-rolla/dice-renderer';
2
+ export interface ViewportLimitOptions {
3
+ readonly maxPixelRatio?: number;
4
+ readonly maxViewportDimension?: number;
5
+ readonly maxFramebufferPixels?: number;
6
+ }
7
+ export interface ViewportLimits {
8
+ readonly maxPixelRatio: number;
9
+ readonly maxViewportDimension: number;
10
+ readonly maxFramebufferPixels: number;
11
+ }
12
+ export declare function resolveViewportLimits(options: ViewportLimitOptions): ViewportLimits;
13
+ export declare function validateViewport(viewport: RendererViewport, limits: ViewportLimits): void;
14
+ export declare function fitViewportToLimits(viewport: RendererViewport, limits: ViewportLimits): RendererViewport;
@@ -0,0 +1,50 @@
1
+ const DEFAULT_VIEWPORT_LIMITS = Object.freeze({
2
+ maxPixelRatio: 2,
3
+ maxViewportDimension: 8_192,
4
+ maxFramebufferPixels: 33_554_432,
5
+ });
6
+ export function resolveViewportLimits(options) {
7
+ const limits = Object.freeze({
8
+ maxPixelRatio: options.maxPixelRatio ?? DEFAULT_VIEWPORT_LIMITS.maxPixelRatio,
9
+ maxViewportDimension: options.maxViewportDimension ?? DEFAULT_VIEWPORT_LIMITS.maxViewportDimension,
10
+ maxFramebufferPixels: options.maxFramebufferPixels ?? DEFAULT_VIEWPORT_LIMITS.maxFramebufferPixels,
11
+ });
12
+ for (const [name, value] of [
13
+ ['maxPixelRatio', limits.maxPixelRatio],
14
+ ['maxViewportDimension', limits.maxViewportDimension],
15
+ ['maxFramebufferPixels', limits.maxFramebufferPixels],
16
+ ]) {
17
+ if (!Number.isFinite(value) || value <= 0) {
18
+ throw new RangeError(`${name} must be a positive finite number`);
19
+ }
20
+ }
21
+ return limits;
22
+ }
23
+ export function validateViewport(viewport, limits) {
24
+ if (![viewport.width, viewport.height, viewport.pixelRatio].every(Number.isFinite)) {
25
+ throw new RangeError('Viewport values must be finite');
26
+ }
27
+ if (viewport.width <= 0 || viewport.height <= 0 || viewport.pixelRatio <= 0) {
28
+ throw new RangeError('Viewport values must be positive');
29
+ }
30
+ if (viewport.width > limits.maxViewportDimension ||
31
+ viewport.height > limits.maxViewportDimension) {
32
+ throw new RangeError(`Viewport dimensions must not exceed ${limits.maxViewportDimension}`);
33
+ }
34
+ if (viewport.pixelRatio > limits.maxPixelRatio) {
35
+ throw new RangeError(`Viewport pixel ratio must not exceed ${limits.maxPixelRatio}`);
36
+ }
37
+ if (framebufferPixels(viewport) > limits.maxFramebufferPixels) {
38
+ throw new RangeError(`Framebuffer must not exceed ${limits.maxFramebufferPixels} pixels`);
39
+ }
40
+ }
41
+ export function fitViewportToLimits(viewport, limits) {
42
+ const width = Math.min(viewport.width, limits.maxViewportDimension);
43
+ const height = Math.min(viewport.height, limits.maxViewportDimension);
44
+ const pixelBudgetRatio = Math.sqrt(limits.maxFramebufferPixels / (width * height)) * (1 - Number.EPSILON);
45
+ const pixelRatio = Math.min(viewport.pixelRatio, limits.maxPixelRatio, pixelBudgetRatio);
46
+ return { width, height, pixelRatio };
47
+ }
48
+ function framebufferPixels(viewport) {
49
+ return viewport.width * viewport.height * viewport.pixelRatio ** 2;
50
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@dice-o-rolla/dice-renderer-three",
3
+ "version": "0.1.0",
4
+ "description": "Three.js WebGL renderers for animated physical dice.",
5
+ "keywords": [
6
+ "dice",
7
+ "renderer",
8
+ "three.js",
9
+ "webgl"
10
+ ],
11
+ "license": "Apache-2.0",
12
+ "files": [
13
+ "dist",
14
+ "README.md",
15
+ "LICENSE",
16
+ "NOTICE",
17
+ "THIRD_PARTY_NOTICES.md"
18
+ ],
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "dependencies": {
34
+ "@dice-o-rolla/dice-geometry": "0.1.0",
35
+ "@dice-o-rolla/dice-renderer": "0.1.0",
36
+ "three": "^0.185.0"
37
+ },
38
+ "engines": {
39
+ "node": ">=20.0.0"
40
+ }
41
+ }