roamwright 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,248 @@
1
+ import { clamp } from '../math/scalar.js';
2
+
3
+ /**
4
+ * A first-person controller for a createSpaces registry. Distances are metres,
5
+ * speeds are metres per second, angles are radians, and update takes seconds.
6
+ * Set input.right, forward and up to signed axes, and run, jump and fly to booleans.
7
+ * Camera application accepts a Three.js camera with YXZ rotation order.
8
+ */
9
+ export function createPlayer(spatial, options = {}) {
10
+ const {
11
+ eye = 1.7,
12
+ radius = 0.35,
13
+ gravity = 9.81,
14
+ jumpSpeed = 4,
15
+ pitchLimit = Math.PI / 2,
16
+ walk = 2,
17
+ run = 4,
18
+ fly = 10,
19
+ flyFast = 20,
20
+ flySet = fly,
21
+ flySetFast = flyFast,
22
+ flightMargin = 0,
23
+ flightCeiling = Infinity,
24
+ flightHeadroom = 50,
25
+ flightBoost = 2,
26
+ flyEase = 6,
27
+ walkEase = 10,
28
+ arrivalHeight = 0,
29
+ liftSpeed = 4,
30
+ liftRange = 1,
31
+ obstacleScan = 2,
32
+ overheadStep = 0.4,
33
+ wadingDepth = 0.5,
34
+ stepHeight = 0.3,
35
+ stepProbe = 0.6,
36
+ stepSlope = 1,
37
+ maxStep = 0.5,
38
+ slopeProbe = 0.8,
39
+ maxSlope = 1,
40
+ flightFloorProbe = 0.1,
41
+ dropHeight = 0.4,
42
+ groundEase = 15,
43
+ bobStart = 0.3,
44
+ bobRate = 1,
45
+ bobAmplitude = 0,
46
+ restingPitch = 0,
47
+ start = {},
48
+ } = options;
49
+ const player = { x: 0, y: eye, z: 0, vx: 0, vy: 0, vz: 0, yaw: 0, pitch: restingPitch, grounded: true, bob: 0, moved: 0, ...start };
50
+ const input = { right: 0, forward: 0, up: 0, run: false, jump: false, fly: false };
51
+ const { collide, hit, overhead } = spatial;
52
+
53
+ function canStand(space, nx, nz, dirx, dirz) {
54
+ const feet = player.y - eye,
55
+ ceiling = feet + obstacleScan;
56
+ const rock = overhead.ground(nx, nz, ceiling),
57
+ g = Math.max(space.ground(nx, nz), rock);
58
+ if ((g === rock && g - feet > overheadStep) || overhead.wall(player.x, player.z, nx, nz, feet)) return false;
59
+ if (space.water && g < space.waterLevel - wadingDepth) return false;
60
+ if (g - feet > stepHeight) {
61
+ const x2 = nx + dirx * stepProbe,
62
+ z2 = nz + dirz * stepProbe;
63
+ const g2 = Math.max(space.ground(x2, z2), overhead.ground(x2, z2, ceiling));
64
+ return (g2 - feet) / stepProbe <= stepSlope && g - feet <= maxStep;
65
+ }
66
+ const x2 = nx + dirx * slopeProbe,
67
+ z2 = nz + dirz * slopeProbe;
68
+ const g2 = Math.max(space.ground(x2, z2), overhead.ground(x2, z2, ceiling));
69
+ return (g2 - g) / slopeProbe <= maxSlope;
70
+ }
71
+
72
+ function keepWithin(space) {
73
+ if (space.round) {
74
+ const rx = player.x - space.cx,
75
+ rz = player.z - space.cz,
76
+ r = Math.hypot(rx, rz);
77
+ if (r > space.bound) {
78
+ player.x = space.cx + (rx / r) * space.bound;
79
+ player.z = space.cz + (rz / r) * space.bound;
80
+ }
81
+ } else {
82
+ const bx = space.bx ?? space.bound,
83
+ bz = space.bz ?? space.bound;
84
+ player.x = clamp(player.x, space.cx - bx, space.cx + bx);
85
+ player.z = clamp(player.z, space.cz - bz, space.cz + bz);
86
+ }
87
+ }
88
+
89
+ function flyStep(space, dt, mx, mz, sinYaw, cosYaw) {
90
+ const flight = space.flight;
91
+ let speed = input.run ? flySetFast : flySet;
92
+ if (space.flyable) speed = input.run ? flyFast : fly;
93
+ else if (flight?.speed !== undefined) speed = input.run ? flight.speed * flightBoost : flight.speed;
94
+
95
+ const cosPitch = Math.cos(player.pitch),
96
+ sinPitch = Math.sin(player.pitch);
97
+ const wantX = (-sinYaw * cosPitch * mz + cosYaw * mx) * speed,
98
+ wantZ = (-cosYaw * cosPitch * mz - sinYaw * mx) * speed,
99
+ wantY = (sinPitch * mz + input.up) * speed;
100
+ const ease = 1 - Math.exp(-dt * flyEase);
101
+ player.vx += (wantX - player.vx) * ease;
102
+ player.vy += (wantY - player.vy) * ease;
103
+ player.vz += (wantZ - player.vz) * ease;
104
+ const previousFeet = player.y - eye;
105
+ player.x += player.vx * dt;
106
+ player.y += player.vy * dt;
107
+ player.z += player.vz * dt;
108
+ const cx = flight?.cx ?? space.cx,
109
+ cz = flight?.cz ?? space.cz;
110
+ const bx = flight?.bx ?? (space.bx ?? space.bound) + flightMargin,
111
+ bz = flight?.bz ?? (space.bz ?? space.bound) + flightMargin;
112
+ player.x = clamp(player.x, cx - bx, cx + bx);
113
+ player.z = clamp(player.z, cz - bz, cz + bz);
114
+ const outside = overhead.keepOut(player.x, player.y, player.z);
115
+ if (outside) {
116
+ player.x = outside[0];
117
+ player.z = outside[1];
118
+ }
119
+ const under = flight?.ground ? flight.ground(player.x, player.z) : space.ground(player.x, player.z);
120
+ const floor =
121
+ Math.max(under, space.water ? space.waterLevel : -Infinity, overhead.ground(player.x, player.z, previousFeet + flightFloorProbe)) +
122
+ eye;
123
+ if (player.y < floor) {
124
+ player.y = floor;
125
+ player.vy = 0;
126
+ }
127
+ let ceiling = space.flyable
128
+ ? Math.max(flightCeiling, floor + flightHeadroom)
129
+ : Math.max(floor, flight?.ceiling ?? floor + flightHeadroom);
130
+ if (space.flightRoom !== undefined) {
131
+ ceiling = Math.max(floor, floor - eye + space.ceiling(player.x, player.z) - space.flightRoom);
132
+ if (collide(player.x, player.z, radius)) {
133
+ player.x = hit.x;
134
+ player.z = hit.z;
135
+ }
136
+ }
137
+ if (player.y > ceiling) player.y = ceiling;
138
+ player.grounded = false;
139
+ }
140
+
141
+ function walkStep(space, dt, mx, mz, sinYaw, cosYaw) {
142
+ const speed = input.run ? run : walk;
143
+ const wantX = (-sinYaw * mz + cosYaw * mx) * speed,
144
+ wantZ = (-cosYaw * mz - sinYaw * mx) * speed;
145
+ const ease = 1 - Math.exp(-dt * walkEase);
146
+ player.vx += (wantX - player.vx) * ease;
147
+ player.vz += (wantZ - player.vz) * ease;
148
+ const stepx = player.vx * dt,
149
+ stepz = player.vz * dt,
150
+ stepLength = Math.hypot(stepx, stepz);
151
+ if (stepLength > 1e-5) {
152
+ let nx = player.x + stepx,
153
+ nz = player.z + stepz;
154
+ if (collide(nx, nz, radius)) {
155
+ nx = hit.x;
156
+ nz = hit.z;
157
+ }
158
+ if (canStand(space, nx, nz, stepx / stepLength, stepz / stepLength)) {
159
+ player.x = nx;
160
+ player.z = nz;
161
+ } else if (Math.abs(stepx) > 1e-5 && canStand(space, nx, player.z, Math.sign(stepx), 0)) {
162
+ player.x = nx;
163
+ player.vz *= 0.5;
164
+ } else if (Math.abs(stepz) > 1e-5 && canStand(space, player.x, nz, 0, Math.sign(stepz))) {
165
+ player.z = nz;
166
+ player.vx *= 0.5;
167
+ } else {
168
+ player.vx = player.vz = 0;
169
+ }
170
+ }
171
+ // A flight envelope can extend past the walking surface. On landing,
172
+ // restore its bounds even if the player has no horizontal velocity.
173
+ if (stepLength > 1e-5 || space.flight) keepWithin(space);
174
+ const eyes = Math.max(space.ground(player.x, player.z), overhead.ground(player.x, player.z, player.y - eye + overheadStep)) + eye;
175
+ if (player.grounded) {
176
+ if (input.jump) {
177
+ player.vy = jumpSpeed;
178
+ player.grounded = false;
179
+ } else if (player.y - eyes > dropHeight) {
180
+ player.grounded = false;
181
+ player.vy = 0;
182
+ } else player.y += (eyes - player.y) * Math.min(1, dt * groundEase);
183
+ }
184
+ if (!player.grounded) {
185
+ player.vy -= gravity * dt;
186
+ player.y += player.vy * dt;
187
+ if (player.y <= eyes) {
188
+ player.y = eyes;
189
+ player.vy = 0;
190
+ player.grounded = true;
191
+ }
192
+ }
193
+ const pace = Math.hypot(player.vx, player.vz);
194
+ player.moved += pace * dt;
195
+ if (player.grounded && pace > bobStart) player.bob += dt * pace * bobRate;
196
+ }
197
+
198
+ function update(dt) {
199
+ let mx = input.right,
200
+ mz = input.forward;
201
+ const magnitude = Math.hypot(mx, mz);
202
+ if (magnitude > 1) {
203
+ mx /= magnitude;
204
+ mz /= magnitude;
205
+ }
206
+ const sinYaw = Math.sin(player.yaw),
207
+ cosYaw = Math.cos(player.yaw);
208
+ if (input.fly) flyStep(spatial.space, dt, mx, mz, sinYaw, cosYaw);
209
+ else walkStep(spatial.space, dt, mx, mz, sinYaw, cosYaw);
210
+ player.pitch = clamp(player.pitch, -pitchLimit, pitchLimit);
211
+ }
212
+
213
+ function place(x, z, yaw) {
214
+ const space = spatial.space;
215
+ player.x = x;
216
+ player.z = z;
217
+ player.vx = player.vy = player.vz = 0;
218
+ const ground = space.ground(x, z),
219
+ floor = input.fly && space.water ? Math.max(ground, space.waterLevel) : ground;
220
+ player.y = floor + eye + (input.fly ? arrivalHeight : 0);
221
+ player.grounded = !input.fly;
222
+ if (yaw !== undefined) {
223
+ player.yaw = yaw;
224
+ player.pitch = restingPitch;
225
+ }
226
+ }
227
+ function applyCamera(camera) {
228
+ const pace = Math.hypot(player.vx, player.vz);
229
+ const bob = !input.fly && player.grounded ? Math.sin(player.bob) * bobAmplitude * Math.min(1, pace / walk) : 0;
230
+ camera.position.set(player.x, player.y + bob, player.z);
231
+ camera.rotation.set(player.pitch, player.yaw, 0);
232
+ }
233
+ function look(dx, dy, sensitivity) {
234
+ player.yaw -= dx * sensitivity;
235
+ player.pitch = clamp(player.pitch - dy * sensitivity, -pitchLimit, pitchLimit);
236
+ }
237
+ function liftOff() {
238
+ const space = spatial.space,
239
+ feet = player.y - eye;
240
+ const floor = Math.max(
241
+ space.ground(player.x, player.z),
242
+ space.water ? space.waterLevel : -Infinity,
243
+ overhead.ground(player.x, player.z, feet + overheadStep),
244
+ );
245
+ if (feet < floor + liftRange) player.vy = liftSpeed;
246
+ }
247
+ return { player, input, update, place, applyCamera, look, liftOff };
248
+ }
@@ -0,0 +1,206 @@
1
+ // Keep common cells as small numeric keys. A row outside the packed range uses
2
+ // a separate key so two distant places can never share a collider bucket.
3
+ function cellKey(column, row) {
4
+ if (row >= -2048 && row < 2048 && Math.abs(column) < 2 ** 39) return (column + 2048) * 4096 + row + 2048;
5
+ return column + ',' + row;
6
+ }
7
+
8
+ /** Highest rotated rectangular deck at a point. k is rise per unit of local z. */
9
+ export function deckTop(list, x, z) {
10
+ let best = -Infinity;
11
+ for (let i = 0; i < list.length; i++) {
12
+ const d = list[i],
13
+ dx = x - d.x,
14
+ dz = z - d.z,
15
+ lx = dx * d.c - dz * d.s,
16
+ lz = dx * d.s + dz * d.c;
17
+ if (Math.abs(lx) <= d.hx && Math.abs(lz) <= d.hz) {
18
+ const y = d.k ? d.y + lz * d.k : d.y;
19
+ if (y > best) best = y;
20
+ }
21
+ }
22
+ return best;
23
+ }
24
+
25
+ const turns = [0, 0.6, -0.6, 1.2, -1.2, 1.8, -1.8, 2.4, -2.4];
26
+
27
+ /**
28
+ * Create an independent registry around a root space with an id and optional
29
+ * terrain height function. Other spaces supply their own ground and collider grid.
30
+ * maxRadius is the largest querying body's radius, in the same units as the grid.
31
+ */
32
+ export function createSpaces(definition, { deckCellSize = 32, colliderCellSize = 16, maxRadius = 1 } = {}) {
33
+ if (!(Number.isFinite(deckCellSize) && deckCellSize > 0 && Number.isFinite(colliderCellSize) && colliderCellSize > 0))
34
+ throw new RangeError('Grid cells must have finite positive dimensions');
35
+ if (!(Number.isFinite(maxRadius) && maxRadius >= 0)) throw new RangeError('maxRadius must be finite and nonnegative');
36
+ const decks = [],
37
+ deckGrid = new Map(),
38
+ built = new Set(),
39
+ hit = { x: 0, z: 0 };
40
+ let indexedDecks = -1,
41
+ terrain = definition.ground ?? (() => 0);
42
+
43
+ function setTerrain(heightAt) {
44
+ terrain = heightAt;
45
+ }
46
+ // Length changes are observed automatically. Call this after editing a deck in place.
47
+ function invalidateDecks() {
48
+ indexedDecks = -1;
49
+ }
50
+ function deckHeight(x, z) {
51
+ if (indexedDecks !== decks.length) {
52
+ deckGrid.clear();
53
+ indexedDecks = decks.length;
54
+ for (const deck of decks) {
55
+ const reach = Math.hypot(deck.hx, deck.hz);
56
+ for (let i = Math.floor((deck.x - reach) / deckCellSize); i <= Math.floor((deck.x + reach) / deckCellSize); i++)
57
+ for (let j = Math.floor((deck.z - reach) / deckCellSize); j <= Math.floor((deck.z + reach) / deckCellSize); j++) {
58
+ const key = cellKey(i, j);
59
+ let list = deckGrid.get(key);
60
+ if (!list) deckGrid.set(key, (list = []));
61
+ list.push(deck);
62
+ }
63
+ }
64
+ }
65
+ const list = deckGrid.get(cellKey(Math.floor(x / deckCellSize), Math.floor(z / deckCellSize)));
66
+ return list ? deckTop(list, x, z) : -Infinity;
67
+ }
68
+ const onDeck = (x, z) => deckHeight(x, z) !== -Infinity;
69
+ const worldSpace = {
70
+ cx: 0,
71
+ cz: 0,
72
+ bound: Infinity,
73
+ ...definition,
74
+ colliders: definition.colliders ?? 0,
75
+ grid: definition.grid ?? new Map(),
76
+ ground(x, z) {
77
+ const height = terrain(x, z);
78
+ return decks.length ? Math.max(height, deckHeight(x, z)) : height;
79
+ },
80
+ };
81
+ let space = worldSpace;
82
+ const spaces = Object.assign(Object.create(null), { [worldSpace.id]: worldSpace });
83
+ function useSpace(next) {
84
+ space = next;
85
+ }
86
+ const isBuilt = id => built.has(id);
87
+ function markBuilt(id) {
88
+ built.add(id);
89
+ }
90
+ const overhead = { ground: () => -Infinity, wall: () => false, keepOut: () => null };
91
+ function setOverhead(ground, wall, keepOut) {
92
+ overhead.ground = ground;
93
+ overhead.wall = wall;
94
+ overhead.keepOut = keepOut;
95
+ }
96
+ // File the obstacle in every cell a querying body's centre could occupy.
97
+ function addCollider(target, obstacle) {
98
+ target.colliders = (target.colliders ?? 0) + 1;
99
+ const reach = (obstacle.r !== undefined ? obstacle.r : Math.hypot(obstacle.hx, obstacle.hz)) + maxRadius;
100
+ const x0 = Math.floor((obstacle.x - reach) / colliderCellSize),
101
+ x1 = Math.floor((obstacle.x + reach) / colliderCellSize),
102
+ z0 = Math.floor((obstacle.z - reach) / colliderCellSize),
103
+ z1 = Math.floor((obstacle.z + reach) / colliderCellSize);
104
+ for (let ix = x0; ix <= x1; ix++)
105
+ for (let iz = z0; iz <= z1; iz++) {
106
+ const key = cellKey(ix, iz);
107
+ let list = target.grid.get(key);
108
+ if (!list) target.grid.set(key, (list = []));
109
+ list.push(obstacle);
110
+ }
111
+ }
112
+ const addBox = (target, x, z, hx, hz, angle = 0) => addCollider(target, { x, z, hx, hz, c: Math.cos(angle), s: Math.sin(angle) });
113
+ const addCircle = (target, x, z, r) => addCollider(target, { x, z, r });
114
+ // Broad-phase candidates in all intersecting cells, in insertion order within each cell.
115
+ function collidersOver(target, x0, z0, x1, z1) {
116
+ const found = new Set();
117
+ for (let ix = Math.floor(x0 / colliderCellSize); ix <= Math.floor(x1 / colliderCellSize); ix++)
118
+ for (let iz = Math.floor(z0 / colliderCellSize); iz <= Math.floor(z1 / colliderCellSize); iz++)
119
+ for (const obstacle of target.grid.get(cellKey(ix, iz)) ?? []) found.add(obstacle);
120
+ return [...found];
121
+ }
122
+ function colliderGrid(list) {
123
+ const holder = { grid: new Map() };
124
+ for (const obstacle of list) addCollider(holder, obstacle);
125
+ return holder.grid;
126
+ }
127
+ // Two passes allow a push away from one wall to meet an adjacent face. A resolved
128
+ // point is written into this instance's hit record so a frame needs no allocation.
129
+ function collideIn(grid, x, z, r) {
130
+ if (!grid) return false;
131
+ let moved = false;
132
+ for (let pass = 0; pass < 2; pass++) {
133
+ const list = grid.get(cellKey(Math.floor(x / colliderCellSize), Math.floor(z / colliderCellSize)));
134
+ if (!list) break;
135
+ let any = false;
136
+ for (let i = 0; i < list.length; i++) {
137
+ const c = list[i],
138
+ dx = x - c.x,
139
+ dz = z - c.z;
140
+ if (c.r !== undefined) {
141
+ const d = Math.hypot(dx, dz),
142
+ clearance = c.r + r;
143
+ if (d < clearance && d > 1e-4) {
144
+ x = c.x + (dx / d) * clearance;
145
+ z = c.z + (dz / d) * clearance;
146
+ any = true;
147
+ }
148
+ } else {
149
+ let lx = dx * c.c - dz * c.s,
150
+ lz = dx * c.s + dz * c.c;
151
+ const px = c.hx + r - Math.abs(lx),
152
+ pz = c.hz + r - Math.abs(lz);
153
+ if (px > 0 && pz > 0) {
154
+ if (px < pz) lx = (lx < 0 ? -1 : 1) * (c.hx + r);
155
+ else lz = (lz < 0 ? -1 : 1) * (c.hz + r);
156
+ x = c.x + lx * c.c + lz * c.s;
157
+ z = c.z - lx * c.s + lz * c.c;
158
+ any = true;
159
+ }
160
+ }
161
+ }
162
+ if (!any) break;
163
+ moved = true;
164
+ }
165
+ hit.x = x;
166
+ hit.z = z;
167
+ return moved;
168
+ }
169
+ const collide = (x, z, r) => collideIn(space.grid, x, z, r);
170
+ // Try offsets on alternating sides of the desired heading. A body already
171
+ // inside a solid is free to move out along its desired heading.
172
+ function steer(x, z, want, step, r, lean = 1) {
173
+ if (collide(x, z, r)) return want;
174
+ for (let i = 0; i < turns.length; i++) {
175
+ const a = want + turns[i] * lean;
176
+ if (!collide(x + Math.sin(a) * step, z + Math.cos(a) * step, r)) return a;
177
+ }
178
+ return undefined;
179
+ }
180
+ return {
181
+ worldSpace,
182
+ spaces,
183
+ get space() {
184
+ return space;
185
+ },
186
+ useSpace,
187
+ isBuilt,
188
+ markBuilt,
189
+ decks,
190
+ deckHeight,
191
+ onDeck,
192
+ invalidateDecks,
193
+ setTerrain,
194
+ overhead,
195
+ setOverhead,
196
+ hit,
197
+ addBox,
198
+ addCircle,
199
+ addCollider,
200
+ collidersOver,
201
+ colliderGrid,
202
+ collide,
203
+ collideIn,
204
+ steer,
205
+ };
206
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A modular Three.js engine for procedural worlds in the browser.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Enes TAYLAN",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/enestaylan/roamwright.git"
11
+ },
12
+ "exports": {
13
+ ".": "./index.js",
14
+ "./geometry/*.js": "./geometry/*.js",
15
+ "./math/*.js": "./math/*.js",
16
+ "./motion/*.js": "./motion/*.js",
17
+ "./rendering/*.js": "./rendering/*.js",
18
+ "./runtime/*.js": "./runtime/*.js"
19
+ },
20
+ "files": [
21
+ "index.js",
22
+ "geometry",
23
+ "math",
24
+ "motion",
25
+ "rendering",
26
+ "runtime",
27
+ "examples",
28
+ "licenses",
29
+ "LICENSE",
30
+ "README.md",
31
+ "CONTRIBUTING.md"
32
+ ],
33
+ "scripts": {
34
+ "test": "node --test test/*.test.js",
35
+ "demo": "python3 -m http.server 8080 --bind 127.0.0.1",
36
+ "test:browser": "node test/browser.mjs"
37
+ },
38
+ "peerDependencies": {
39
+ "three": "0.170.0 || 0.187.0"
40
+ },
41
+ "devDependencies": {
42
+ "playwright": "1.65.1",
43
+ "three": "0.187.0"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "homepage": "https://github.com/enestaylan/roamwright",
49
+ "bugs": {
50
+ "url": "https://github.com/enestaylan/roamwright/issues"
51
+ }
52
+ }
@@ -0,0 +1,20 @@
1
+ import * as THREE from 'three';
2
+
3
+ export function createRenderContext(canvas, { antialias = true, fov = 68, near = 0.25, far = 7000 } = {}) {
4
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias, powerPreference: 'high-performance', stencil: false });
5
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
6
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
7
+ renderer.toneMappingExposure = 1.0;
8
+ renderer.shadowMap.enabled = true;
9
+ renderer.shadowMap.type = Number(THREE.REVISION) === 170 ? THREE.PCFSoftShadowMap : THREE.PCFShadowMap;
10
+ renderer.info.autoReset = false;
11
+ const scene = new THREE.Scene();
12
+ const camera = new THREE.PerspectiveCamera(fov, 1, near, far);
13
+ camera.rotation.order = 'YXZ';
14
+ scene.add(camera);
15
+ camera.layers.enable(1);
16
+ const worldGroup = new THREE.Group();
17
+ scene.add(worldGroup);
18
+ const fxScene = new THREE.Scene();
19
+ return { renderer, scene, camera, worldGroup, fxScene };
20
+ }
@@ -0,0 +1,59 @@
1
+ import * as THREE from 'three';
2
+ import { DOF_COC, QUAD_VS } from './post-shaders.js';
3
+
4
+ // ════════════════════════════════════════════════════════════════════════
5
+ // Depth of field, as a long lens has it in a scene's closer shot: the subject sharp, what stands behind softening the further
6
+ // it lies, and what passes close before the lens soft too. A scene's shot names its focus each frame (focusOn); with none named this frame the pass is skipped and costs nothing. The picture is gathered at half size, each
7
+ // pixel from a disk of samples as wide as its circle of confusion, each sample counting only as far as its own circle reaches
8
+ // this pixel (so a sharp subject does not smear over the blurred ground behind it); the final pass mixes that in by the circle.
9
+ // ════════════════════════════════════════════════════════════════════════
10
+ const DOF_BLUR = 0.0045, // the circle of confusion far behind the subject, as a share of the picture's height (a 30-degree lens near f/2.8)
11
+ DOF_MOST = 0.009, // the widest circle, as a share of the picture's height (what passes close before the lens)
12
+ TAPS = 16; // samples in the gather's disk, laid out on a golden-angle spiral
13
+
14
+ const DOF_FS = `/* glsl */ uniform sampler2D tScene, tDepth; uniform vec4 uDof; uniform vec2 uNF, uPx; varying vec2 vUv;
15
+ float viewDepth(vec2 uv){ return -uNF.x * uNF.y / ((uNF.y - uNF.x) * texture2D(tDepth, uv).x - uNF.y); }
16
+ ${DOF_COC}
17
+ void main(){
18
+ float r = cocAt(viewDepth(vUv));
19
+ vec3 sum = texture2D(tScene, vUv).rgb; float wsum = 1.0;
20
+ for (int i = 1; i < ${TAPS}; i++) {
21
+ float f = float(i) / ${TAPS}.0, a = float(i) * 2.39996;
22
+ vec2 o = vec2(cos(a), sin(a)) * sqrt(f) * max(r, 0.5);
23
+ vec2 uv = vUv + o * uPx;
24
+ float rs = cocAt(viewDepth(uv)), d = length(o);
25
+ float w = clamp(min(rs, r) - d + 1.0, 0.0, 1.0); // a sample counts as far as its own circle, and this one's, reach here
26
+ sum += clamp(texture2D(tScene, uv).rgb, 0.0, 48.0) * w; wsum += w;
27
+ }
28
+ gl_FragColor = vec4(sum / wsum, 1.0);
29
+ }`;
30
+ export function createDepthOfField() {
31
+ const dof = {
32
+ target: null,
33
+ material: new THREE.ShaderMaterial({
34
+ depthTest: false,
35
+ depthWrite: false,
36
+ vertexShader: QUAD_VS,
37
+ fragmentShader: DOF_FS,
38
+ uniforms: {
39
+ tScene: { value: null },
40
+ tDepth: { value: null },
41
+ uDof: { value: new THREE.Vector4() },
42
+ uNF: { value: new THREE.Vector2() },
43
+ uPx: { value: new THREE.Vector2() },
44
+ },
45
+ }),
46
+ focus: 0, // metres to what the lens is focused on, while a shot names one
47
+ named: -1, // the frame it was last named on
48
+ weight: 0, // eased in and out, so the background softens as the shot settles
49
+ };
50
+ // The shot's focus for this frame: the distance from the lens to its subject.
51
+ function focusOn(metres, frame) {
52
+ dof.focus = metres;
53
+ dof.named = frame;
54
+ }
55
+
56
+ return { dof, focusOn };
57
+ }
58
+
59
+ export { DOF_BLUR, DOF_MOST };