roamwright 0.2.0 → 0.4.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/README.md +24 -3
- package/geometry/foliage.js +47 -0
- package/geometry/index-parts.js +60 -0
- package/geometry/instance-visibility.js +41 -0
- package/geometry/instances.js +23 -0
- package/geometry/part-ranges.js +18 -0
- package/geometry/terrain-chunks.js +19 -15
- package/motion/ground-lookahead.js +29 -0
- package/package.json +2 -2
- package/rendering/cell-lod.js +15 -6
- package/rendering/piece-batch.js +74 -20
- package/runtime/frame-budget.js +49 -0
- package/runtime/gpu-timing.js +6 -3
package/README.md
CHANGED
|
@@ -3,11 +3,18 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/roamwright)
|
|
4
4
|
[](https://github.com/enestaylan/roamwright/actions/workflows/test.yml)
|
|
5
5
|
|
|
6
|
-
Roamwright is a Three.js
|
|
6
|
+
Roamwright is a procedural worldbuilding engine built on top of Three.js. It gives you reusable systems for turning a 3D scene into a world you can explore. You define the landscape once and use the same terrain to shape riverbanks, place scenery and guide characters over uneven ground. First-person walking and flight, crowd animation, weather and day–night lighting can all be used in your own Three.js scene.
|
|
7
7
|
|
|
8
8
|

|
|
9
9
|
|
|
10
|
-
**Alpine viaduct
|
|
10
|
+
**Alpine viaduct.** One height field shapes the riverbed and snowy ridges and determines where the conifers take root. Eight copies of an arch profile form the viaduct. The stonework, rails and overhead wires share one mesh. The four-car electric train moves as a separate mesh. Choose Valley, Trackside or Riverbank and select **Run train** to watch it cross. [Explore the example source](examples/viaduct.js).
|
|
11
|
+
|
|
12
|
+
## Building an explorable world
|
|
13
|
+
|
|
14
|
+
- **Landscapes and structures.** Generate repeatable mountain ranges, eroded slopes and rock outcrops. Terrain-aware placement keeps scenery on the ground. Buildings and bridges can use modular geometry and tileable stone, timber and roof textures.
|
|
15
|
+
- **Water, light and weather.** Rivers support directional flow, lakes support reflections, and water surfaces respond to rain with ripples. Volumetric clouds, sun and moon cycles, wind and haze let the same landscape take on different weather and lighting conditions.
|
|
16
|
+
- **Characters and exploration.** Bipeds and quadrupeds have procedural gaits, and crowds can follow daily routes. First-person movement covers walking, jumping and flight, including collision checks and support for raised surfaces such as bridge decks.
|
|
17
|
+
- **Large scenes.** Background geometry generation, batched scenery, instanced crowds, distance-based levels of detail and adaptive rendering quality help manage the cost of dense forests, crowds and long views.
|
|
11
18
|
|
|
12
19
|
## Install
|
|
13
20
|
|
|
@@ -25,7 +32,7 @@ npm resolves the Three.js peer in a new project. If you already use Three.js, th
|
|
|
25
32
|
|
|
26
33
|
| Live example | What the example shows | Source |
|
|
27
34
|
| --- | --- | --- |
|
|
28
|
-
| [Alpine viaduct](https://enestaylan.github.io/roamwright/examples/viaduct.html
|
|
35
|
+
| [Alpine viaduct](https://enestaylan.github.io/roamwright/examples/viaduct.html) | Watch an electric train cross eight stone arches from the valley, trackside or riverbank. | [viaduct.js](examples/viaduct.js) |
|
|
29
36
|
| [Seeded island](https://enestaylan.github.io/roamwright/examples/?seed=42) | Seeded noise shapes the coastline, and a single mesh holds the rocks scattered along the shore. | [island.js](examples/island.js) |
|
|
30
37
|
|
|
31
38
|
### Run locally
|
|
@@ -81,8 +88,22 @@ Import any module from `roamwright/<folder>/<name>.js`. Each area below names it
|
|
|
81
88
|
| Player and world | `motion/spaces.js` and `motion/player.js` move a first-person controller over terrain, decks and colliders. | `motion/instance-sight.js`, `motion/daily-clock.js`, `runtime/spatial-audio.js` |
|
|
82
89
|
| Runtime | `runtime/pool.js` and `runtime/worker.js` run named jobs on module workers. `runtime/quality-fit.js` adapts quality to measured GPU time. | `runtime/device-quality.js`, `runtime/quality-store.js`, `runtime/gpu-timing.js`, `runtime/first-use.js`, `runtime/hand-over.js`, `runtime/seen.js`, `runtime/frame-yield.js`, `runtime/grid-cache.js`, `runtime/grid-rows.js`, `runtime/events.js`, `runtime/diagnostic-log.js`, `runtime/module-preload.js`, `runtime/search.js` |
|
|
83
90
|
|
|
91
|
+
For triangle lists, `indexParts` from `geometry/index-parts.js` reuses vertices whose complete attribute records are byte-identical and preserves the original triangle order. Run it where the arrays are built.
|
|
92
|
+
|
|
93
|
+
Use `shapeParts`, `addShape` and `partsGeometry` from `geometry/foliage.js` to assemble immutable, indexed plant models with per-vertex tints and leaf flags. `partitionInstances(arrays, cellSize)` from `geometry/instances.js` groups transforms and colours into horizontal cells for camera and shadow culling. For opaque instances with independently owned matrix and colour attributes, `createInstanceVisibility(mesh)` from `geometry/instance-visibility.js` returns a function to show or hide a logical ID. The mesh submits only its visible prefix. Instance order and shader `gl_InstanceID` can change.
|
|
94
|
+
|
|
95
|
+
For pieces that change material, `batch.materialView(material)` creates a child mesh that shares the GPU buffers. Assign pieces with `batch.setView(id, mesh)` and return them to the original material with `batch.setView(id)`. Configure the batch layers and shadow flags before creating the view. Treat the child transform and visibility as batch-managed.
|
|
96
|
+
|
|
97
|
+
Use `createFrameBudget` from `runtime/frame-budget.js` for optional synchronous work shared by multiple systems. Call `begin(rafTimestamp)` once per frame. Register each small step once with `task(fn)`. Its wrapper preserves the receiver and arguments and returns true after running the step, or false when the caller should retry it. Keep worker jobs concurrent and apply ready results in application order. The budget accounts for elapsed work, reserves time before presentation, and reduces the next allowance after a missed frame. After `maxWaitMs`, the longest-waiting producer can advance one step even on a busy frame. An individual step runs to completion, so divide expensive work at safe boundaries. Before the first frame, steps run immediately.
|
|
98
|
+
|
|
99
|
+
`createGroundLookahead` from `motion/ground-lookahead.js` predicts a horizontal position from samples in seconds, with a capped lead and a reset after jumps or pauses. `joinParts` from `geometry/part-ranges.js` assembles attribute buffers from ordered position ranges.
|
|
100
|
+
|
|
84
101
|
Pass a `revisions` object mapping grid names to input-version strings to `createGridCache` to reuse compatible grids across builds. Saving a grid retires its previous revision. Names without a revision bypass storage. The existing `build` string versions the whole cache when `revisions` is omitted.
|
|
85
102
|
|
|
103
|
+
Pass an optional world-space `initialPosition` to `terrainChunks` to create the terrain at its first viewing distance. Subsequent updates follow the camera.
|
|
104
|
+
|
|
105
|
+
For elevated viewpoints, pass the eye height and an optional positive distance scale as the last arguments to `createCellLod().update(cells, x, z, distance, detail, density, y, scale)`. Set `cy` on each cell to its centre elevation. Detail follows the eye in three dimensions while visibility follows ground distance.
|
|
106
|
+
|
|
86
107
|
For geometry generated off the main thread, call `builder.parts(true)` in the worker and `geometryOf(parts)` on the page.
|
|
87
108
|
|
|
88
109
|
## Contributing and license
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
import { indexParts } from './index-parts.js';
|
|
3
|
+
|
|
4
|
+
const _tint = [0, 0, 0],
|
|
5
|
+
_n3 = new THREE.Matrix3(),
|
|
6
|
+
_v = new THREE.Vector3(); // scratch values of this module
|
|
7
|
+
|
|
8
|
+
// An empty set of parts: positions, normals, colours and leaf flags.
|
|
9
|
+
function shapeParts() {
|
|
10
|
+
return { p: [], n: [], c: [], l: [] };
|
|
11
|
+
}
|
|
12
|
+
// Adds a geometry to parts, placed by matrix m, each vertex coloured by tint(x, y, z, out) in its own space; leaf 1 for foliage.
|
|
13
|
+
function addShape(parts, geo, m, tint, leaf) {
|
|
14
|
+
const g = geo.index ? geo.toNonIndexed() : geo,
|
|
15
|
+
pa = g.attributes.position.array,
|
|
16
|
+
na = g.attributes.normal.array;
|
|
17
|
+
_n3.getNormalMatrix(m);
|
|
18
|
+
for (let i = 0; i < pa.length; i += 3) {
|
|
19
|
+
tint(pa[i], pa[i + 1], pa[i + 2], _tint);
|
|
20
|
+
_v.set(pa[i], pa[i + 1], pa[i + 2]).applyMatrix4(m);
|
|
21
|
+
parts.p.push(_v.x, _v.y, _v.z);
|
|
22
|
+
_v.set(na[i], na[i + 1], na[i + 2])
|
|
23
|
+
.applyMatrix3(_n3)
|
|
24
|
+
.normalize();
|
|
25
|
+
parts.n.push(_v.x, _v.y, _v.z);
|
|
26
|
+
parts.c.push(_tint[0], _tint[1], _tint[2]);
|
|
27
|
+
parts.l.push(leaf);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
// A static plant model can be instanced many times with one immutable index buffer.
|
|
31
|
+
function partsGeometry(parts) {
|
|
32
|
+
const attributes = indexParts({
|
|
33
|
+
position: new Float32Array(parts.p),
|
|
34
|
+
normal: new Float32Array(parts.n),
|
|
35
|
+
color: new Float32Array(parts.c),
|
|
36
|
+
aLeaf: new Float32Array(parts.l),
|
|
37
|
+
});
|
|
38
|
+
const geometry = new THREE.BufferGeometry();
|
|
39
|
+
for (const [name, data] of Object.entries(attributes)) {
|
|
40
|
+
if (name === 'index') geometry.setIndex(new THREE.BufferAttribute(data, 1));
|
|
41
|
+
else geometry.setAttribute(name, new THREE.BufferAttribute(data, name === 'aLeaf' ? 1 : 3));
|
|
42
|
+
}
|
|
43
|
+
geometry.computeBoundingSphere();
|
|
44
|
+
return geometry;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export { addShape, partsGeometry, shapeParts };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Weld identical vertex records without rounding or changing triangle order. Comparing the
|
|
2
|
+
// stored bytes preserves seams, signed zero and normalized attributes exactly.
|
|
3
|
+
export function indexParts(parts) {
|
|
4
|
+
const count = parts.position.length / 3;
|
|
5
|
+
if (!count || parts.index) return parts;
|
|
6
|
+
const attributes = Object.entries(parts).map(([name, data]) => {
|
|
7
|
+
const strideBytes = data.byteLength / count;
|
|
8
|
+
const words = !(strideBytes % 4 || data.byteOffset % 4);
|
|
9
|
+
const View = words ? Uint32Array : Uint8Array;
|
|
10
|
+
return {
|
|
11
|
+
name,
|
|
12
|
+
data,
|
|
13
|
+
stride: strideBytes / View.BYTES_PER_ELEMENT,
|
|
14
|
+
source: new View(data.buffer, data.byteOffset, data.byteLength / View.BYTES_PER_ELEMENT),
|
|
15
|
+
};
|
|
16
|
+
});
|
|
17
|
+
const buckets = new Uint32Array(2 ** Math.ceil(Math.log2(count)));
|
|
18
|
+
const links = new Uint32Array(count);
|
|
19
|
+
const originals = new Uint32Array(count);
|
|
20
|
+
const index = count <= 65535 ? new Uint16Array(count) : new Uint32Array(count);
|
|
21
|
+
let used = 0;
|
|
22
|
+
for (let vertex = 0; vertex < count; vertex++) {
|
|
23
|
+
// Hash the complete record so coincident positions along seams, or a tight cluster
|
|
24
|
+
// of tiny features, do not all form one long chain.
|
|
25
|
+
let hash = 2166136261;
|
|
26
|
+
for (let i = 0; i < attributes.length; i++) {
|
|
27
|
+
const { source, stride } = attributes[i];
|
|
28
|
+
const offset = vertex * stride;
|
|
29
|
+
for (let j = 0; j < stride; j++) hash = Math.imul(hash ^ source[offset + j], 16777619);
|
|
30
|
+
}
|
|
31
|
+
const bucket = (hash ^ (hash >>> 16)) & (buckets.length - 1);
|
|
32
|
+
let link = buckets[bucket];
|
|
33
|
+
while (link && !sameVertex(attributes, originals[link - 1], vertex)) link = links[link - 1];
|
|
34
|
+
if (!link) {
|
|
35
|
+
originals[used] = vertex;
|
|
36
|
+
links[used] = buckets[bucket];
|
|
37
|
+
link = buckets[bucket] = ++used;
|
|
38
|
+
}
|
|
39
|
+
index[vertex] = link - 1;
|
|
40
|
+
}
|
|
41
|
+
const packed = { index };
|
|
42
|
+
for (const { name, data, stride, source } of attributes) {
|
|
43
|
+
const out = new data.constructor(used * (data.length / count));
|
|
44
|
+
const dest = new source.constructor(out.buffer);
|
|
45
|
+
for (let i = 0; i < used; i++) {
|
|
46
|
+
const from = originals[i] * stride;
|
|
47
|
+
for (let j = 0; j < stride; j++) dest[i * stride + j] = source[from + j];
|
|
48
|
+
}
|
|
49
|
+
packed[name] = out;
|
|
50
|
+
}
|
|
51
|
+
return packed;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function sameVertex(attributes, a, b) {
|
|
55
|
+
for (let i = 0; i < attributes.length; i++) {
|
|
56
|
+
const { source, stride } = attributes[i];
|
|
57
|
+
for (let j = 0; j < stride; j++) if (source[a * stride + j] !== source[b * stride + j]) return false;
|
|
58
|
+
}
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// For opaque, independently owned instance attributes. Logical ids remain stable while
|
|
2
|
+
// visible records occupy the front of the arrays. The original full bounds stay valid.
|
|
3
|
+
export function createInstanceVisibility(mesh) {
|
|
4
|
+
const slots = Uint32Array.from({ length: mesh.count }, (_, i) => i);
|
|
5
|
+
const ids = slots.slice();
|
|
6
|
+
const attributes = [mesh.instanceMatrix];
|
|
7
|
+
if (mesh.instanceColor) attributes.push(mesh.instanceColor);
|
|
8
|
+
if (!mesh.boundingSphere) mesh.computeBoundingSphere();
|
|
9
|
+
return function show(id, visible) {
|
|
10
|
+
if (!Number.isInteger(id) || id < 0 || id >= ids.length) throw new RangeError('Unknown instance id');
|
|
11
|
+
const from = slots[id];
|
|
12
|
+
if (from < mesh.count === visible) return;
|
|
13
|
+
const to = visible ? mesh.count++ : --mesh.count;
|
|
14
|
+
if (from === to) return;
|
|
15
|
+
const other = ids[to];
|
|
16
|
+
ids[from] = other;
|
|
17
|
+
slots[other] = from;
|
|
18
|
+
ids[to] = id;
|
|
19
|
+
slots[id] = to;
|
|
20
|
+
for (const attribute of attributes) {
|
|
21
|
+
const { array, itemSize } = attribute;
|
|
22
|
+
const a = from * itemSize,
|
|
23
|
+
b = to * itemSize;
|
|
24
|
+
for (let i = 0; i < itemSize; i++) {
|
|
25
|
+
const value = array[a + i];
|
|
26
|
+
array[a + i] = array[b + i];
|
|
27
|
+
array[b + i] = value;
|
|
28
|
+
}
|
|
29
|
+
// Include the hidden slot: it can become visible by growing count without another swap.
|
|
30
|
+
const start = Math.min(a, b),
|
|
31
|
+
end = Math.max(a, b) + itemSize;
|
|
32
|
+
const range = attribute.updateRanges[0];
|
|
33
|
+
if (range) {
|
|
34
|
+
const limit = Math.max(end, range.start + range.count);
|
|
35
|
+
range.start = Math.min(start, range.start);
|
|
36
|
+
range.count = limit - range.start;
|
|
37
|
+
} else attribute.addUpdateRange(start, end - start);
|
|
38
|
+
attribute.needsUpdate = true;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
package/geometry/instances.js
CHANGED
|
@@ -74,3 +74,26 @@ class Copies {
|
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
export { Copies, instanceArrays, instancedMesh, instancedTwin, putInstance };
|
|
77
|
+
|
|
78
|
+
// Partition static world-space transforms and their colors into independently cullable
|
|
79
|
+
// cells. A single cell keeps its original arrays; order within every cell is stable.
|
|
80
|
+
export function partitionInstances(arrays, cellSize) {
|
|
81
|
+
if (!(cellSize > 0)) throw new RangeError('Expected a positive cell size');
|
|
82
|
+
const { matrices, colours } = arrays;
|
|
83
|
+
const cells = new Map();
|
|
84
|
+
for (let i = 0; i < matrices.length / 16; i++) {
|
|
85
|
+
const k = Math.floor(matrices[i*16+12] / cellSize) + ',' + Math.floor(matrices[i*16+14] / cellSize);
|
|
86
|
+
let ids = cells.get(k);
|
|
87
|
+
if (!ids) cells.set(k, ids = []);
|
|
88
|
+
ids.push(i);
|
|
89
|
+
}
|
|
90
|
+
if (cells.size < 2) return matrices.length ? [arrays] : [];
|
|
91
|
+
return Array.from(cells.values(), ids => {
|
|
92
|
+
const cell = instanceArrays(ids.length);
|
|
93
|
+
ids.forEach((id, i) => {
|
|
94
|
+
cell.matrices.set(matrices.subarray(id*16,id*16+16), i*16);
|
|
95
|
+
cell.colours.set(colours.subarray(id*3,id*3+3), i*3);
|
|
96
|
+
});
|
|
97
|
+
return cell;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Concatenate matching attribute records in order. Each [parts, from, to] range uses
|
|
2
|
+
// offsets in the three-component position array. Other attribute strides are inferred.
|
|
3
|
+
export function joinParts(pieces) {
|
|
4
|
+
if (!pieces.length) return {};
|
|
5
|
+
const vertices = pieces.reduce((sum, [, from, to]) => sum + (to - from) / 3, 0),
|
|
6
|
+
[sample] = pieces.find(([parts]) => parts.position.length) ?? pieces[0],
|
|
7
|
+
joined = {};
|
|
8
|
+
for (const name in sample) {
|
|
9
|
+
const size = vertices && sample[name].length / (sample.position.length / 3),
|
|
10
|
+
array = (joined[name] = new sample[name].constructor(vertices * size));
|
|
11
|
+
let at = 0;
|
|
12
|
+
for (const [parts, from, to] of pieces) {
|
|
13
|
+
array.set(parts[name].subarray((from / 3) * size, (to / 3) * size), at);
|
|
14
|
+
at += ((to - from) / 3) * size;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return joined;
|
|
18
|
+
}
|
|
@@ -191,7 +191,8 @@ function buildFineGeometry(land, ci, cj) {
|
|
|
191
191
|
}
|
|
192
192
|
return chunkGeometry(pos, nor, col, uv, m, bedY);
|
|
193
193
|
}
|
|
194
|
-
// Builds the ground at its coarsest
|
|
194
|
+
// Builds the ground at its coarsest or, with initialPosition {x, y, z}, at the levels seen from that position.
|
|
195
|
+
// The returned updater follows camera.position as the viewer moves. `materials` is the pair
|
|
195
196
|
// every chunk is drawn with (ground, deep bed), or a function giving the pair (or the one material) for the chunk that covers
|
|
196
197
|
// (x0, z0) to (x1, z1). `held`: [{ box: [x0, z0, x1, z1], range, level }], ground over which something finer is laid on the mesh
|
|
197
198
|
// at a level of detail or finer, a list that may fill later: within `range` metres of its box
|
|
@@ -200,7 +201,7 @@ function buildFineGeometry(land, ci, cj) {
|
|
|
200
201
|
// are one batch of geometry pieces: those in view are drawn together, and a
|
|
201
202
|
// chunk's vertices are on the card only, at the one level it is shown at.
|
|
202
203
|
export function terrainChunks(parent, land, materials, {
|
|
203
|
-
camera, createBatch, lodScale = () => 1, distances = [330, 680, 1250], held = [],
|
|
204
|
+
camera, createBatch, lodScale = () => 1, distances = [330, 680, 1250], held = [], initialPosition,
|
|
204
205
|
fineRange = 70, fineHeight = 90, altitudeStart = 120, altitudeWeight = 0.6, checksPerFrame = 8,
|
|
205
206
|
}) {
|
|
206
207
|
const width = land.cells * land.spacing,
|
|
@@ -239,18 +240,18 @@ export function terrainChunks(parent, land, materials, {
|
|
|
239
240
|
cz: land.z0 + (cj + 0.5) * width,
|
|
240
241
|
materials: typeof materials === 'function' ? materials(x0, z0, x0 + width, z0 + width) : materials,
|
|
241
242
|
pieces: [],
|
|
242
|
-
lod:
|
|
243
|
+
lod: null,
|
|
243
244
|
holds: null, // the ground held over this chunk (`held`), once seen
|
|
244
245
|
};
|
|
245
|
-
show(chunk,
|
|
246
|
+
if (!initialPosition) show(chunk, 3);
|
|
246
247
|
chunks.push(chunk);
|
|
247
248
|
}
|
|
248
249
|
const boxOf = c => [c.cx - width / 2, c.cz - width / 2, c.cx + width / 2, c.cz + width / 2],
|
|
249
250
|
overlaps = (a, b) => a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3],
|
|
250
|
-
nearBox = (box, range) =>
|
|
251
|
+
nearBox = (box, range, position) =>
|
|
251
252
|
Math.hypot(
|
|
252
|
-
Math.max(box[0] -
|
|
253
|
-
Math.max(box[1] -
|
|
253
|
+
Math.max(box[0] - position.x, 0, position.x - box[2]),
|
|
254
|
+
Math.max(box[1] - position.z, 0, position.z - box[3]),
|
|
254
255
|
) <
|
|
255
256
|
range * lodScale();
|
|
256
257
|
// the chunks under ground held at a level, found when it is first seen (the list may fill later)
|
|
@@ -260,9 +261,9 @@ export function terrainChunks(parent, land, materials, {
|
|
|
260
261
|
for (const c of h.chunks) (c.holds ??= []).push(h);
|
|
261
262
|
};
|
|
262
263
|
// the level a chunk wants, `want` by its distance, or finer where ground over it is held within range
|
|
263
|
-
const heldLevel = (c, want) => {
|
|
264
|
+
const heldLevel = (c, want, position) => {
|
|
264
265
|
if (c.holds)
|
|
265
|
-
for (let i = 0; i < c.holds.length; i++) if (nearBox(c.holds[i].box, c.holds[i].range)) want = Math.min(want, c.holds[i].level);
|
|
266
|
+
for (let i = 0; i < c.holds.length; i++) if (nearBox(c.holds[i].box, c.holds[i].range, position)) want = Math.min(want, c.holds[i].level);
|
|
266
267
|
return want;
|
|
267
268
|
};
|
|
268
269
|
// whether every chunk under held ground stands at its level or finer
|
|
@@ -271,30 +272,33 @@ export function terrainChunks(parent, land, materials, {
|
|
|
271
272
|
return true;
|
|
272
273
|
};
|
|
273
274
|
let chunkCursor = 0;
|
|
274
|
-
|
|
275
|
+
const update = (force, position) => {
|
|
275
276
|
for (let i = 0; i < held.length; i++) if (!held[i].chunks) holdUnder(held[i]);
|
|
276
277
|
// Re-evaluate a few chunks per frame; put at most one at another level per frame. The fine level is drawn only near the eye.
|
|
277
|
-
const low = !!land.relief &&
|
|
278
|
+
const low = !!land.relief && position.y < land.groundAt(position.x, position.z) + fineHeight;
|
|
278
279
|
let built = false;
|
|
279
280
|
const count = force ? chunks.length : checksPerFrame;
|
|
280
281
|
for (let n = 0; n < count; n++) {
|
|
281
282
|
const c = chunks[chunkCursor];
|
|
282
283
|
chunkCursor = (chunkCursor + 1) % chunks.length;
|
|
283
|
-
const dx = Math.max(Math.abs(
|
|
284
|
-
dz = Math.max(Math.abs(
|
|
285
|
-
const d = Math.hypot(dx, dz, Math.max(0,
|
|
284
|
+
const dx = Math.max(Math.abs(position.x - c.cx) - width * 0.5, 0),
|
|
285
|
+
dz = Math.max(Math.abs(position.z - c.cz) - width * 0.5, 0);
|
|
286
|
+
const d = Math.hypot(dx, dz, Math.max(0, position.y - altitudeStart) * altitudeWeight);
|
|
286
287
|
const fine = low && Math.hypot(dx, dz) < fineRange;
|
|
287
288
|
const want = fine
|
|
288
289
|
? -1
|
|
289
290
|
: heldLevel(
|
|
290
291
|
c,
|
|
291
292
|
d < distances[0] * lodScale() ? 0 : d < distances[1] * lodScale() ? 1 : d < distances[2] * lodScale() ? 2 : 3,
|
|
293
|
+
position,
|
|
292
294
|
);
|
|
293
295
|
if (want === c.lod || (built && !force)) continue;
|
|
294
296
|
show(c, want);
|
|
295
297
|
built = true;
|
|
296
298
|
}
|
|
297
|
-
for (let i = 0; i < held.length; i++) held[i].fine = nearBox(held[i].box, held[i].range) && standsAt(held[i]);
|
|
299
|
+
for (let i = 0; i < held.length; i++) held[i].fine = nearBox(held[i].box, held[i].range, position) && standsAt(held[i]);
|
|
298
300
|
};
|
|
301
|
+
if (initialPosition) update(true, initialPosition);
|
|
302
|
+
return force => update(force, camera.position);
|
|
299
303
|
}
|
|
300
304
|
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Predict planar motion in metres, reusing the returned point between updates.
|
|
2
|
+
export function createGroundLookahead({ seconds, maxDistance, smoothing, jumpDistance, maxGap }) {
|
|
3
|
+
let lastX,
|
|
4
|
+
lastZ,
|
|
5
|
+
lastTime,
|
|
6
|
+
vx = 0,
|
|
7
|
+
vz = 0;
|
|
8
|
+
const point = { x: 0, z: 0, jumped: false };
|
|
9
|
+
return function predict(x, z, time) {
|
|
10
|
+
const dt = time - lastTime,
|
|
11
|
+
dx = x - lastX,
|
|
12
|
+
dz = z - lastZ;
|
|
13
|
+
point.jumped = lastTime === undefined || Math.hypot(dx, dz) > jumpDistance;
|
|
14
|
+
if (point.jumped || !(dt > 0 && dt < maxGap)) vx = vz = 0;
|
|
15
|
+
else {
|
|
16
|
+
const k = Math.min(1, dt * smoothing);
|
|
17
|
+
vx += (dx / dt - vx) * k;
|
|
18
|
+
vz += (dz / dt - vz) * k;
|
|
19
|
+
}
|
|
20
|
+
const speed = Math.hypot(vx, vz);
|
|
21
|
+
const lead = speed ? Math.min(seconds, maxDistance / speed) : seconds;
|
|
22
|
+
point.x = x + vx * lead;
|
|
23
|
+
point.z = z + vz * lead;
|
|
24
|
+
lastX = x;
|
|
25
|
+
lastZ = z;
|
|
26
|
+
lastTime = time;
|
|
27
|
+
return point;
|
|
28
|
+
};
|
|
29
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "roamwright",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "A
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Enes TAYLAN",
|
package/rendering/cell-lod.js
CHANGED
|
@@ -23,7 +23,7 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
|
|
|
23
23
|
shown = { value: null }, // the table, as the uniform the far materials and the far shadow body share
|
|
24
24
|
batches = [];
|
|
25
25
|
let batchShows = null,
|
|
26
|
-
depth = null;
|
|
26
|
+
depth = null, distanceMaterial = null;
|
|
27
27
|
|
|
28
28
|
// Hides, in the vertex shader, a copy whose cell is not showing its far copy or that lies past the cell's `count`.
|
|
29
29
|
function hideUnshown(sh) {
|
|
@@ -117,6 +117,12 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
|
|
|
117
117
|
mesh.castShadow = casts; // as the near copies do
|
|
118
118
|
if (casts) {
|
|
119
119
|
mesh.customDepthMaterial = depthMaterial();
|
|
120
|
+
if (!distanceMaterial) {
|
|
121
|
+
distanceMaterial = new THREE.MeshDistanceMaterial();
|
|
122
|
+
distanceMaterial.onBeforeCompile = hideUnshown;
|
|
123
|
+
distanceMaterial.customProgramCacheKey = () => 'far-batch-distance';
|
|
124
|
+
}
|
|
125
|
+
mesh.customDistanceMaterial = distanceMaterial;
|
|
120
126
|
mesh.userData.partShown = true; // a pass drawing heights with a plain depth material would show every copy
|
|
121
127
|
}
|
|
122
128
|
mesh.matrixAutoUpdate = false;
|
|
@@ -131,14 +137,15 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
|
|
|
131
137
|
// Where a cell lies and how far it is drawn, kept on it in a record of one shape: cells come from builders of many shapes,
|
|
132
138
|
// and a number read from objects of so many shapes is made anew at every read. A cell does not move.
|
|
133
139
|
const lodOf = t =>
|
|
134
|
-
(t.lod ??= { cx: t.cx, cz: t.cz, r: t.r, until: t.until ?? Infinity, near: t.near ?? Infinity, batch: t.farBatch ?? -1 });
|
|
140
|
+
(t.lod ??= { cx: t.cx, cy: t.cy ?? 0, cz: t.cz, r: t.r, until: t.until ?? Infinity, near: t.near ?? Infinity, batch: t.farBatch ?? -1 });
|
|
135
141
|
|
|
136
142
|
/**
|
|
137
143
|
* Each frame: near cells show their detailed mesh, far ones their batched copy, thinned beyond `thinFrom` of the drawing
|
|
138
144
|
* distance. (cx, cz): the eye; `distance` metres past which nothing is drawn, `detail` metres within which the near mesh is,
|
|
139
|
-
* `density` the share of a thinned cell's instances kept.
|
|
145
|
+
* `density` the share of a thinned cell's instances kept. Optional eye height `cy` includes altitude above the cell's
|
|
146
|
+
* centre in the near/far decision. The visibility range stays horizontal. `rangeScale` scales both thresholds, including the radius.
|
|
140
147
|
*/
|
|
141
|
-
function update(cells, cx, cz, distance, detail, density) {
|
|
148
|
+
function update(cells, cx, cz, distance, detail, density, cy, rangeScale = 1) {
|
|
142
149
|
let changed = false;
|
|
143
150
|
if (batchShows) batchShows.fill(0);
|
|
144
151
|
for (let i = 0; i < cells.length; i++) {
|
|
@@ -146,10 +153,12 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
|
|
|
146
153
|
at = lodOf(t),
|
|
147
154
|
dx = cx - at.cx,
|
|
148
155
|
dz = cz - at.cz,
|
|
149
|
-
|
|
156
|
+
horizontalSq = dx * dx + dz * dz,
|
|
157
|
+
d = Math.sqrt(horizontalSq) / rangeScale - at.r,
|
|
150
158
|
hasFar = t.lo || t.far !== undefined;
|
|
151
159
|
const vis = d < Math.min(distance, at.until),
|
|
152
|
-
|
|
160
|
+
nearDistance = cy === undefined ? d : Math.sqrt(horizontalSq + (cy - at.cy) ** 2) / rangeScale - at.r,
|
|
161
|
+
hi = !hasFar || nearDistance < Math.min(detail, at.near);
|
|
153
162
|
t.mesh.visible = vis && hi;
|
|
154
163
|
if (t.lo) t.lo.visible = vis && !hi;
|
|
155
164
|
let count = t.farN;
|
package/rendering/piece-batch.js
CHANGED
|
@@ -67,7 +67,8 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
67
67
|
const DEPTH_STEP = 1 / 16,
|
|
68
68
|
DEPTH_FROM = -1024,
|
|
69
69
|
PIECES_MOST = 65536;
|
|
70
|
-
|
|
70
|
+
const keyBuffers = []; // one scratch buffer per power of two, shared by all passes
|
|
71
|
+
let _keys;
|
|
71
72
|
// The i-th of `seen` pieces in order, nearest first (farthest first, from the end of the keys, where `far`)
|
|
72
73
|
const nthSeen = (i, seen, far) => _seen[_keys[far ? seen - 1 - i : i] % PIECES_MOST];
|
|
73
74
|
let multi; // the multi-draw extension, or null where the browser has none (the pieces are then drawn one by one)
|
|
@@ -85,6 +86,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
85
86
|
this.layout = null; // [name, array type, item size, normalized] of each attribute, from the first piece
|
|
86
87
|
this.indices = null; // an indexed batch keeps its indices here as well, to fill a larger buffer from when it grows
|
|
87
88
|
this.pieces = []; // by id: { vertexStart, vertexCount, start, count, sphere, shown, depth }, or null where one was removed
|
|
89
|
+
this.views = new Map(); // child meshes drawing pieces with alternate materials from these same buffers
|
|
88
90
|
this.spare = []; // ids to give out again
|
|
89
91
|
this.starts = new Int32Array(16); // the pieces after the first that the pass being drawn sees: where each begins (in bytes, if indexed)
|
|
90
92
|
this.counts = new Int32Array(16);
|
|
@@ -117,6 +119,43 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
117
119
|
if (!geometry.boundingSphere) geometry.computeBoundingSphere();
|
|
118
120
|
return this.record({ vertexStart, vertexCount, start, count, sphere: geometry.boundingSphere.clone() });
|
|
119
121
|
}
|
|
122
|
+
// A second material pass over a disjoint subset of this batch, sharing its buffers and
|
|
123
|
+
// transform. Only setView changes membership. Empty views skip drawing altogether.
|
|
124
|
+
materialView(material) {
|
|
125
|
+
const mesh = new THREE.Mesh(this.geometry, material);
|
|
126
|
+
const members = new Set();
|
|
127
|
+
this.views.set(mesh, members);
|
|
128
|
+
mesh.visible = false;
|
|
129
|
+
mesh.matrixAutoUpdate = false;
|
|
130
|
+
mesh.layers.mask = this.layers.mask;
|
|
131
|
+
mesh.castShadow = this.castShadow;
|
|
132
|
+
mesh.receiveShadow = this.receiveShadow;
|
|
133
|
+
mesh.boundingSphere = this.boundingSphere.clone();
|
|
134
|
+
mesh.raycast = this.raycast;
|
|
135
|
+
mesh.onBeforeRender = (_r, _s, viewer) => this.choose(viewer, mesh, members);
|
|
136
|
+
mesh.onAfterRender = (_r, _s, _c, _g, drawnWith) => this.drawRest(drawnWith);
|
|
137
|
+
mesh.onBeforeShadow = (_r, _o, _c, viewer, _g, drawnWith) => this.chooseShadow(viewer, drawnWith, mesh, members);
|
|
138
|
+
mesh.onAfterShadow = (_r, _o, _c, _v, _g, drawnWith) => this.drawRest(drawnWith);
|
|
139
|
+
super.add(mesh);
|
|
140
|
+
return mesh;
|
|
141
|
+
}
|
|
142
|
+
setView(id, mesh = null) {
|
|
143
|
+
const piece = this.pieces[id];
|
|
144
|
+
if (piece.view === mesh) return;
|
|
145
|
+
const members = mesh && this.views.get(mesh);
|
|
146
|
+
if (mesh && !members) throw new Error('Material view belongs to another batch');
|
|
147
|
+
if (piece.view) {
|
|
148
|
+
const previous = this.views.get(piece.view);
|
|
149
|
+
previous.delete(piece);
|
|
150
|
+
piece.view.visible = previous.size > 0;
|
|
151
|
+
}
|
|
152
|
+
piece.view = mesh;
|
|
153
|
+
if (mesh) {
|
|
154
|
+
members.add(piece);
|
|
155
|
+
mesh.visible = true;
|
|
156
|
+
}
|
|
157
|
+
this.changes++;
|
|
158
|
+
}
|
|
120
159
|
// Moves a piece into another batch of the same layout (one drawn in another material), copied from buffer to buffer on the card;
|
|
121
160
|
// returns its id there
|
|
122
161
|
move(id, to) {
|
|
@@ -164,7 +203,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
164
203
|
// A piece whose vertices are in place: its id
|
|
165
204
|
record(piece) {
|
|
166
205
|
const id = this.spare.length ? this.spare.pop() : this.pieces.length;
|
|
167
|
-
this.pieces[id] = { ...piece, shown: true, depth: 0 };
|
|
206
|
+
this.pieces[id] = { ...piece, shown: true, depth: 0, view: null };
|
|
168
207
|
this.changes++;
|
|
169
208
|
this.used.vertices += piece.vertexCount;
|
|
170
209
|
if (this.indices) this.used.indices += piece.count;
|
|
@@ -173,6 +212,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
173
212
|
}
|
|
174
213
|
remove(id) {
|
|
175
214
|
const piece = this.pieces[id];
|
|
215
|
+
if (piece.view) this.setView(id);
|
|
176
216
|
this.pieces[id] = null;
|
|
177
217
|
this.spare.push(id);
|
|
178
218
|
this.changes++;
|
|
@@ -207,18 +247,22 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
207
247
|
}
|
|
208
248
|
// The bounds of all pieces, by which Three decides whether the batch is in view at all; with no piece it never is
|
|
209
249
|
bound() {
|
|
210
|
-
const all = new THREE.Sphere(
|
|
250
|
+
const all = (this.geometry.boundingSphere ??= new THREE.Sphere());
|
|
251
|
+
all.makeEmpty();
|
|
211
252
|
for (const piece of this.pieces) if (piece) all.union(piece.sphere);
|
|
212
253
|
if (all.isEmpty()) all.radius = -Infinity;
|
|
213
|
-
this.
|
|
214
|
-
|
|
254
|
+
(this.boundingSphere ??= new THREE.Sphere()).copy(all);
|
|
255
|
+
for (const mesh of this.views.keys()) {
|
|
256
|
+
mesh.geometry = this.geometry;
|
|
257
|
+
mesh.boundingSphere.copy(all);
|
|
258
|
+
}
|
|
215
259
|
}
|
|
216
260
|
// Three sorts the opaque things of a pass nearest first by the centre of this sphere, so that what stands in front hides what is
|
|
217
261
|
// behind before it is shaded: the batch is placed where its nearest piece in the viewer's picture stands, as that piece's own mesh
|
|
218
262
|
// was, with a radius that still holds every piece (the sphere is also what Three culls the whole batch by)
|
|
219
|
-
sortBy(nearest) {
|
|
263
|
+
sortBy(nearest, mesh) {
|
|
220
264
|
const all = this.geometry.boundingSphere,
|
|
221
|
-
at =
|
|
265
|
+
at = mesh.boundingSphere;
|
|
222
266
|
at.center.copy(nearest.sphere.center);
|
|
223
267
|
at.radius = all.radius + at.center.distanceTo(all.center);
|
|
224
268
|
}
|
|
@@ -237,9 +281,12 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
237
281
|
// Packs the pieces together, one after another, into buffers `room` times what they fill, once they fill less than `use`
|
|
238
282
|
// of the ones they are in (a buffer only ever grows, and pieces are let go): what each piece holds is copied across on the card,
|
|
239
283
|
// and its indices are written again from the copy kept here; a batch with no piece left gives its room back. Returns whether it did either.
|
|
284
|
+
needsPack(use = this.fit.use) {
|
|
285
|
+
return this.held.vertices >= PACK_LEAST && this.used.vertices < this.held.vertices * use;
|
|
286
|
+
}
|
|
240
287
|
pack() {
|
|
241
288
|
const { vertices: filled, indices: filledIndices } = this.used;
|
|
242
|
-
if (this.
|
|
289
|
+
if (!this.needsPack()) return false;
|
|
243
290
|
if (!filled) {
|
|
244
291
|
this.empty();
|
|
245
292
|
return true;
|
|
@@ -313,6 +360,7 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
313
360
|
}
|
|
314
361
|
gl.bindBuffer(gl.COPY_WRITE_BUFFER, null);
|
|
315
362
|
this.geometry.boundingSphere = old.boundingSphere;
|
|
363
|
+
for (const mesh of this.views.keys()) mesh.geometry = this.geometry;
|
|
316
364
|
this.discard(old);
|
|
317
365
|
}
|
|
318
366
|
// Frees the batch's buffers on the card, once it is let go
|
|
@@ -328,23 +376,26 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
328
376
|
}
|
|
329
377
|
// The pieces a camera sees, nearest first (farthest first in a see-through material): the first becomes the range Three draws,
|
|
330
378
|
// the others are listed for the multi-draw that follows it
|
|
331
|
-
choose(viewer) {
|
|
379
|
+
choose(viewer, mesh = this, pieces = this.pieces) {
|
|
332
380
|
_view.setFromProjectionMatrix(_clip.multiplyMatrices(viewer.projectionMatrix, viewer.matrixWorldInverse).multiply(this.matrixWorld));
|
|
333
381
|
const e = _clip.elements;
|
|
334
382
|
let seen = 0;
|
|
335
|
-
for (const piece of
|
|
336
|
-
if (!piece || !piece.shown || !_view.intersectsSphere(piece.sphere)) continue;
|
|
383
|
+
for (const piece of pieces) {
|
|
384
|
+
if (!piece || (mesh === this && piece.view) || !piece.shown || !_view.intersectsSphere(piece.sphere)) continue;
|
|
337
385
|
const c = piece.sphere.center;
|
|
338
386
|
piece.depth = e[2] * c.x + e[6] * c.y + e[10] * c.z + e[14];
|
|
339
387
|
_seen[seen++] = piece;
|
|
340
388
|
}
|
|
341
|
-
if (seen >
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
389
|
+
if (seen > 1) {
|
|
390
|
+
const size = Math.ceil(Math.log2(seen));
|
|
391
|
+
_keys = keyBuffers[size] ??= new Float64Array(2 ** size);
|
|
392
|
+
for (let i = 0; i < seen; i++) _keys[i] = Math.max(0, Math.floor((_seen[i].depth - DEPTH_FROM) / DEPTH_STEP)) * PIECES_MOST + i;
|
|
393
|
+
_keys.fill(Infinity, seen);
|
|
394
|
+
_keys.sort();
|
|
395
|
+
}
|
|
396
|
+
const far = mesh.material.transparent,
|
|
397
|
+
first = seen > 1 ? nthSeen(0, seen, far) : seen ? _seen[0] : null;
|
|
398
|
+
if (first && camera === viewer && !far) this.sortBy(first, mesh);
|
|
348
399
|
if (first) this.geometry.setDrawRange(first.start, first.count);
|
|
349
400
|
else this.geometry.setDrawRange(0, -1); // a range Three takes for nothing to draw
|
|
350
401
|
this.rest = Math.max(0, seen - 1);
|
|
@@ -394,8 +445,11 @@ export function createPieceBatch({ renderer, camera, markStill = () => {}, isSti
|
|
|
394
445
|
}
|
|
395
446
|
// In a point light's shadow it is drawn only where it casts there, and not where a cached point shadow already contains its current revision
|
|
396
447
|
onBeforeShadow(_renderer, _object, _camera, shadowCamera, _geometry, drawnWith) {
|
|
397
|
-
|
|
398
|
-
|
|
448
|
+
this.chooseShadow(shadowCamera, drawnWith, this, this.pieces);
|
|
449
|
+
}
|
|
450
|
+
chooseShadow(shadowCamera, drawnWith, mesh, pieces) {
|
|
451
|
+
if (!drawnWith.isMeshDistanceMaterial || (this.pointShadow && !(isStill(mesh) && keptAway(mesh, this.changes))))
|
|
452
|
+
this.choose(shadowCamera, mesh, pieces);
|
|
399
453
|
else {
|
|
400
454
|
this.geometry.setDrawRange(0, -1);
|
|
401
455
|
this.rest = 0;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Register synchronous, indivisible steps once. The caller retains its queue, priorities and
|
|
2
|
+
// cancellation policy. A rejected step did no work and can be tried again next frame.
|
|
3
|
+
export function createFrameBudget({ frameMs = 1000 / 60, workMs = 3, reserveMs = 6, maxWaitMs = 100, now = () => performance.now() } = {}) {
|
|
4
|
+
if (!(frameMs > 0 && workMs > 0 && reserveMs >= 0 && reserveMs < frameMs && maxWaitMs >= 0)) throw new RangeError('Invalid frame budget');
|
|
5
|
+
let previous,
|
|
6
|
+
deadline = Infinity,
|
|
7
|
+
remaining = Infinity,
|
|
8
|
+
allowance = workMs;
|
|
9
|
+
let reserved,
|
|
10
|
+
next,
|
|
11
|
+
oldest = Infinity;
|
|
12
|
+
function begin(timestamp = now()) {
|
|
13
|
+
if (previous !== undefined && timestamp - previous > 1.5 * frameMs) allowance = Math.max(workMs / 4, allowance / 2);
|
|
14
|
+
else allowance = Math.min(workMs, allowance + workMs / 8);
|
|
15
|
+
previous = timestamp;
|
|
16
|
+
deadline = timestamp + frameMs - reserveMs;
|
|
17
|
+
remaining = allowance;
|
|
18
|
+
reserved = next;
|
|
19
|
+
next = undefined;
|
|
20
|
+
oldest = Infinity;
|
|
21
|
+
}
|
|
22
|
+
function task(step) {
|
|
23
|
+
let waitingSince;
|
|
24
|
+
return function tryStep(...args) {
|
|
25
|
+
const start = now();
|
|
26
|
+
if (remaining <= 0 || start >= deadline) {
|
|
27
|
+
waitingSince ??= start;
|
|
28
|
+
// Give the longest-waiting producer from the previous frame one turn. If its
|
|
29
|
+
// work disappears, callers simply stop retrying and the reservation expires.
|
|
30
|
+
if (reserved !== tryStep || start - waitingSince < maxWaitMs) {
|
|
31
|
+
if (waitingSince < oldest) {
|
|
32
|
+
oldest = waitingSince;
|
|
33
|
+
next = tryStep;
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (reserved === tryStep) reserved = undefined;
|
|
39
|
+
waitingSince = undefined;
|
|
40
|
+
try {
|
|
41
|
+
step.apply(this, args);
|
|
42
|
+
} finally {
|
|
43
|
+
remaining -= now() - start;
|
|
44
|
+
}
|
|
45
|
+
return true;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return { begin, task };
|
|
49
|
+
}
|
package/runtime/gpu-timing.js
CHANGED
|
@@ -31,15 +31,18 @@ export function createGpuTiming(renderer) {
|
|
|
31
31
|
return new Promise(resolve => {
|
|
32
32
|
const ask = () => {
|
|
33
33
|
const at = performance.now(),
|
|
34
|
-
|
|
34
|
+
status = gl.clientWaitSync(fence, 0, 0),
|
|
35
|
+
waiting = status === gl.TIMEOUT_EXPIRED;
|
|
35
36
|
if (waiting && at - since < GIVE_UP_MS) {
|
|
36
37
|
asked++;
|
|
37
|
-
|
|
38
|
+
// A queued GPU frame can take tens of milliseconds. Leave the page thread
|
|
39
|
+
// free between observations. The channel resets nested timer clamping.
|
|
40
|
+
setTimeout(() => nextTask(ask), 1);
|
|
38
41
|
return;
|
|
39
42
|
}
|
|
40
43
|
gl.deleteSync(fence);
|
|
41
44
|
if (waiting && !globalThis.document?.hidden) blocks = true; // not passed in all that time on a page that is being shown: fences do not work here
|
|
42
|
-
resolve({ at, prompt: asked === 0, gaveUp: waiting });
|
|
45
|
+
resolve({ at, prompt: asked === 0, gaveUp: waiting || status === gl.WAIT_FAILED });
|
|
43
46
|
};
|
|
44
47
|
nextTask(ask);
|
|
45
48
|
});
|