roamwright 0.58.0 → 0.59.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,461 @@
1
+ import { ringContains, segmentDistance } from './path-field.js';
2
+ import { softenFieldCoverage, extendFieldBorders } from './field-map.js';
3
+ import { clamp, lerp, sstep } from '../math/scalar.js';
4
+ import { spacedCurve } from '../math/curve.js';
5
+ import { mulberry32 } from '../math/random.js';
6
+
7
+ /** What a parcel is put to. The numbers are the field map's (times `kindStep` in its green channel), so the ground shader, the
8
+ * grass and the builders all read the same. */
9
+ export const FIELD_USE = Object.freeze({ plough: 0, grain: 1, grass: 2, fallow: 3, orchard: 4, yard: 5, shoots: 6 });
10
+
11
+ /**
12
+ * The shape of a survey of farmland, in metres: the wander that bends every reading of a straight-chained plan (boundaries,
13
+ * crop rows, hedges, walls and drains all curve together), the jitter of its corners, how the season's work is shared out
14
+ * among parcels, the field map's encoding, and the noise seeds.
15
+ */
16
+ export const FIELD_SURVEY = Object.freeze({
17
+ /** A broad swing and a finer wobble on it, each over its span, and how far a parcel's drawing reaches past its outline. */
18
+ bend: { broad: 6.5, broadSpan: 52, fine: 1.4, fineSpan: 17, reach: 8 },
19
+ bendSeeds: [911, 912],
20
+ /** Metres a survey corner may stand off its chain, along and across, and how far the rows slant with it. */
21
+ chainJitter: 25,
22
+ slant: 0.095,
23
+ /** How far each corner of a parcel is pulled towards its middle: its chain corners, and the middle of each side. */
24
+ corner: 0.045,
25
+ cornerAcross: 0.055,
26
+ side: 0.05,
27
+ sideAcross: 0.06,
28
+ sideJitter: [6, 5],
29
+ /** Of the ploughed parcels, those already sown and showing green. */
30
+ shootsShare: 0.4,
31
+ /** How far the season's work has got in a parcel, as [share of such parcels, least, most of the parcel done]. */
32
+ progress: {
33
+ [FIELD_USE.plough]: [
34
+ [0.5, 1, 1],
35
+ [0.5, 0.3, 0.8],
36
+ ],
37
+ [FIELD_USE.shoots]: [[1, 1, 1]],
38
+ [FIELD_USE.grain]: [
39
+ [0.3, 0, 0],
40
+ [0.4, 0.25, 0.8],
41
+ [0.3, 1, 1],
42
+ ],
43
+ [FIELD_USE.grass]: [
44
+ [0.62, 0, 0],
45
+ [0.38, 0.4, 1],
46
+ ],
47
+ },
48
+ /** The uses a surveyed parcel is drawn from, each as likely as its share of the list. */
49
+ draw: [
50
+ FIELD_USE.plough,
51
+ FIELD_USE.grain,
52
+ FIELD_USE.grass,
53
+ FIELD_USE.fallow,
54
+ FIELD_USE.grain,
55
+ FIELD_USE.plough,
56
+ FIELD_USE.grass,
57
+ FIELD_USE.fallow,
58
+ FIELD_USE.orchard,
59
+ FIELD_USE.grass,
60
+ ],
61
+ /** The field map's step between uses, as a ground shader reads it (`field-surface.js`'s `kindStep`). */
62
+ kindStep: 42,
63
+ /** The field map: metres a byte of distance stands for, the byte where the season's work stops and the steps of it to a metre
64
+ * from that line, how far across the rows an edge must run to be a row end, and the bend map's step in texels. */
65
+ lotMetres: 255 / 12.75,
66
+ workLevel: 127.5,
67
+ workMetres: 20,
68
+ endEdge: 0.5,
69
+ bendStep: 4,
70
+ /** The raggedness of a parcel's edge and the noise on its work line: the span of each noise and its seed, and the metres. */
71
+ ragged: { span: 2.7, seed: 915, metres: 0.8 },
72
+ workNoise: { span: 6, seed: 916, metres: 1.6 },
73
+ edgeLeast: 0.23,
74
+ fieldSeeds: [3530, 3571],
75
+ });
76
+
77
+ /**
78
+ * A survey of farmland: parcels laid out in rows from a few chained areas, each given a use and a stage of the season's work,
79
+ * with farmyards, their tracks to the nearest road and the drains between parcels; and the field maps that the ground, the
80
+ * grass and the builders read (a use, a coverage, how far the work has reached, and the distance to the parcel's edge). The
81
+ * plan lives in a `fields` record the caller keeps between calls: `{ x, z, w, d, scale, parcels, yards, tracks, ditches, ditchD,
82
+ * sites }` before the maps are laid out, then `width`, `height`, `data`, `lots`, `bend`... Pure arithmetic over the caller's
83
+ * readers, for the page or a worker.
84
+ *
85
+ * @param {object} readers
86
+ * @param {(x: number, z: number, seed: number) => number} readers.noise - Seeded value noise (`createNoise`).
87
+ * @param {(x: number, z: number) => number} [readers.road] - Metres from a place to the nearest road (used when drawing maps).
88
+ * @param {(x: number, z: number) => number} [readers.ditchRoad] - Metres from a place to the nearest road when planning drains (defaults to `road`).
89
+ * @param {(x: number, z: number) => number} [readers.river] - Metres from a place to the nearest stream.
90
+ * @param {(x: number, z: number) => number} [readers.height] - The terrain's height at a place, metres.
91
+ * @param {(x: number, z: number) => boolean} [readers.clear] - Whether a place may be farmed at all: the caller keeps its towns,
92
+ * its waters and its landmarks out.
93
+ * @param {(path: number[][], radius: number, distances: Float32Array) => void} [readers.stamp] - Writes the distance to a path's
94
+ * nearest point, up to `radius` metres, into a grid (one value to the ground's cell).
95
+ * @param {Function} [readers.random] - A repeatable stream maker, called with a seed (`mulberry32`).
96
+ * @param {Partial<typeof FIELD_SURVEY>} [readers.shape] - Changes to {@link FIELD_SURVEY}.
97
+ * @returns {{ USE: typeof FIELD_USE, bend: Function, unbend: Function, plan: Function, boundary: Function, yardAt: Function,
98
+ * trackAt: Function, layOut: Function, draw: Function, maps: Function, lot: Function, points: Function, pixel: Function,
99
+ * cleared: Function }}
100
+ */
101
+ export function createFieldSurvey({
102
+ noise,
103
+ road = () => Infinity,
104
+ ditchRoad = road,
105
+ river = () => Infinity,
106
+ height = () => 10,
107
+ clear = () => true,
108
+ stamp = () => {},
109
+ random = mulberry32,
110
+ shape = {},
111
+ }) {
112
+ const {
113
+ bend: BEND,
114
+ bendSeeds,
115
+ chainJitter,
116
+ slant,
117
+ corner,
118
+ cornerAcross,
119
+ side,
120
+ sideAcross,
121
+ sideJitter,
122
+ shootsShare,
123
+ progress: PROGRESS,
124
+ draw: USE_DRAW,
125
+ lotMetres: LOT_METRES,
126
+ workLevel: WORK_LEVEL,
127
+ workMetres: WORK_METRES,
128
+ endEdge: END_EDGE,
129
+ bendStep: BEND_STEP,
130
+ ragged,
131
+ workNoise,
132
+ edgeLeast,
133
+ fieldSeeds,
134
+ kindStep,
135
+ } = { ...FIELD_SURVEY, ...shape };
136
+ const _bent = [0, 0];
137
+
138
+ // The survey is drawn with straight chains, but the land it was laid on is not: every reading of the plan first moves the
139
+ // point by a slow wander, so boundaries, crop rows, hedges, walls and drains all curve together.
140
+ const wander = (x, z, seed) =>
141
+ (noise(x / BEND.broadSpan, z / BEND.broadSpan, seed) - 0.5) * 2 * BEND.broad +
142
+ (noise(x / BEND.fineSpan, z / BEND.fineSpan, seed + 2) - 0.5) * 2 * BEND.fine;
143
+ // The point of the plan that lies under a point of the land.
144
+ function bend(x, z, out) {
145
+ out[0] = x + wander(x, z, bendSeeds[0]);
146
+ out[1] = z + wander(x, z, bendSeeds[1]);
147
+ return out;
148
+ }
149
+ // The point of the land for a point of the plan: the bend undone, by a few fixed-point steps.
150
+ function unbend(px, pz, out) {
151
+ let x = px,
152
+ z = pz;
153
+ for (let step = 0; step < 4; step++) {
154
+ bend(x, z, _bent);
155
+ x += px - _bent[0];
156
+ z += pz - _bent[1];
157
+ }
158
+ out[0] = x;
159
+ out[1] = z;
160
+ return out;
161
+ }
162
+
163
+ // Gives a parcel what the survey's outline does not say: its own tint, the stage of its work, and its extent along and across
164
+ // its rows.
165
+ function describeParcel(parcel, rng) {
166
+ if (parcel.use === FIELD_USE.plough && rng() < shootsShare) parcel.use = FIELD_USE.shoots;
167
+ parcel.tint = rng();
168
+ parcel.progress = 0;
169
+ let pick = rng();
170
+ for (const [share, least, most] of PROGRESS[parcel.use] || []) {
171
+ if (pick < share) {
172
+ parcel.progress = lerp(least, most, rng());
173
+ break;
174
+ }
175
+ pick -= share;
176
+ }
177
+ const c = Math.cos(parcel.angle),
178
+ s = Math.sin(parcel.angle);
179
+ parcel.axis = [c, s];
180
+ parcel.along = [Infinity, -Infinity];
181
+ parcel.across = [Infinity, -Infinity];
182
+ for (const [x, z] of parcel.ring) {
183
+ const u = x * c + z * s,
184
+ v = z * c - x * s;
185
+ parcel.along = [Math.min(parcel.along[0], u), Math.max(parcel.along[1], u)];
186
+ parcel.across = [Math.min(parcel.across[0], v), Math.max(parcel.across[1], v)];
187
+ }
188
+ }
189
+ // How many metres a point of the plan lies inside the part of its parcel the season's work has reached (negative: not reached).
190
+ function workedDepth(parcel, px, pz) {
191
+ if (parcel.progress <= 0) return -Infinity;
192
+ if (parcel.progress >= 1) return Infinity;
193
+ const v = pz * parcel.axis[0] - px * parcel.axis[1];
194
+ return lerp(parcel.across[0], parcel.across[1], parcel.progress) - v;
195
+ }
196
+
197
+ // How far a place lies in a farmyard (0..1): a rectangle round each yard's middle, turned to face its way.
198
+ function yardAt(fields, x, z) {
199
+ let mask = 0;
200
+ for (const { x: cx, z: cz, c, s } of fields.yards) {
201
+ const dx = x - cx,
202
+ dz = z - cz;
203
+ if (Math.abs(dx) > 20 || Math.abs(dz) > 20) continue;
204
+ mask = Math.max(mask, sstep(1.16, 0.91, Math.max(Math.abs(dx * c - dz * s) / 12.5, Math.abs(dx * s + dz * c) / 11.7)));
205
+ }
206
+ return mask;
207
+ }
208
+ // Metres from a place to the nearest farmyard's track, or `radius` where none is nearer.
209
+ function trackAt(fields, x, z, radius) {
210
+ let d = radius;
211
+ for (const path of fields.tracks) {
212
+ const a = path[0],
213
+ b = path[path.length - 1];
214
+ if (x < Math.min(a[0], b[0]) - 13 || x > Math.max(a[0], b[0]) + 13 || z < Math.min(a[1], b[1]) - 13 || z > Math.max(a[1], b[1]) + 13)
215
+ continue;
216
+ for (let i = 1; i < path.length; i++) {
217
+ if (Math.abs(x - path[i][0]) > radius + 2 || Math.abs(z - path[i][1]) > radius + 2) continue;
218
+ d = Math.min(d, segmentDistance(x, z, path[i - 1], path[i]));
219
+ }
220
+ }
221
+ return d;
222
+ }
223
+
224
+ /**
225
+ * Surveys the farmland into `fields`: a parcel to each cell of each area's chained grid, the farmyards and their tracks, and
226
+ * the drains between parcels.
227
+ *
228
+ * @param {object} fields - The record to fill (its `parcels`, `yards`, `tracks`, `ditches`, `ditchD` and `sites`).
229
+ * @param {object} farmland - `areas`: each `{ x, z, dx: number[], dz: number[], slant }`, the chain's corner, the lengths
230
+ * of its cells along and across in metres, and how far the rows slant; `yards`: each `{ x, z, angle, road, bend }`, the
231
+ * yard's middle and facing, the road its track joins and the point of the road it joins at; `roads`: by a yard's `road`,
232
+ * each `{ fine: number[][] }`, the road's line; and `seed`.
233
+ * @param {number[][]} sites - The grounds the countryside's scenes are played on, which the plan keeps clear.
234
+ * @param {number} [gridLength] - The cells of the ground's grid, for the drains' distances.
235
+ */
236
+ function plan(fields, farmland, sites, gridLength = 0) {
237
+ fields.sites = sites;
238
+ const rng = random(farmland.seed + fieldSeeds[0]),
239
+ stageRng = random(farmland.seed + fieldSeeds[1]);
240
+ for (const area of farmland.areas) {
241
+ const rows = [];
242
+ let zz = area.z;
243
+ for (let j = 0; j <= area.dz.length; j++) {
244
+ const row = [];
245
+ let xx = area.x;
246
+ for (let i = 0; i <= area.dx.length; i++) {
247
+ row.push([
248
+ xx + (zz - area.z) * area.slant + (rng() - 0.5) * chainJitter,
249
+ zz + (rng() - 0.5) * chainJitter + (xx - area.x) * slant,
250
+ ]);
251
+ xx += area.dx[i] || 0;
252
+ }
253
+ rows.push(row);
254
+ zz += area.dz[j] || 0;
255
+ }
256
+ for (let j = 0; j < area.dz.length; j++)
257
+ for (let i = 0; i < area.dx.length; i++) {
258
+ const corners = [rows[j][i], rows[j][i + 1], rows[j + 1][i + 1], rows[j + 1][i]];
259
+ const center = corners.reduce((p, q) => [p[0] + q[0] / 4, p[1] + q[1] / 4], [0, 0]);
260
+ const ring = [];
261
+ for (let k = 0; k < 4; k++) {
262
+ const a = corners[k],
263
+ b = corners[(k + 1) % 4];
264
+ ring.push([lerp(a[0], center[0], corner), lerp(a[1], center[1], cornerAcross)]);
265
+ ring.push([
266
+ lerp((a[0] + b[0]) / 2, center[0], side) + (rng() - 0.5) * sideJitter[0],
267
+ lerp((a[1] + b[1]) / 2, center[1], sideAcross) + (rng() - 0.5) * sideJitter[1],
268
+ ]);
269
+ }
270
+ const use = USE_DRAW[Math.floor(rng() * USE_DRAW.length)];
271
+ const a = corners[0],
272
+ b = corners[area.dx[i] > area.dz[j] * (0.85 + rng() * 0.4) ? 1 : 3];
273
+ const angle = (Math.atan2(b[1] - a[1], b[0] - a[0]) + Math.PI * 2) % Math.PI;
274
+ const edges = [0, 1, 2, 3].map(k => (k === 1 || k === 2 ? Math.floor(rng() * 9) : -1));
275
+ fields.parcels.push({ ring, use, angle, edges, row: j, col: i });
276
+ }
277
+ }
278
+ for (const parcel of fields.parcels) describeParcel(parcel, stageRng);
279
+ for (const { x, z, angle, road: roadId, bend: bendAt } of farmland.yards) {
280
+ const line = farmland.roads[roadId].fine;
281
+ const end = line.reduce((a, b) =>
282
+ Math.hypot(a[0] - bendAt[0], a[1] - bendAt[1]) < Math.hypot(b[0] - bendAt[0], b[1] - bendAt[1]) ? a : b,
283
+ );
284
+ const mouth = [x + Math.sin(angle) * 11.5, z + Math.cos(angle) * 11.5];
285
+ fields.yards.push({ x, z, angle, c: Math.cos(angle), s: Math.sin(angle) });
286
+ fields.tracks.push(spacedCurve([mouth, bendAt, end], 1.4));
287
+ }
288
+ // a drain down the far side of every other row of parcels, where nothing else stands in its way
289
+ for (const parcel of fields.parcels)
290
+ for (let e = 0; e < 4; e++) {
291
+ if (parcel.edges[e] !== 0 || parcel.row % 2 === 0) continue;
292
+ const line = boundary(parcel, e, 9);
293
+ if (!line.every(p => clear(...p) && ditchRoad(...p) > 12 && yardAt(fields, ...p) < 0.01 && trackAt(fields, ...p, 6) > 5.5))
294
+ continue;
295
+ fields.ditches.push(spacedCurve(line, 2));
296
+ }
297
+ fields.ditchD = new Float32Array(gridLength).fill(99);
298
+ for (const ditch of fields.ditches) stamp(ditch, 5, fields.ditchD);
299
+ }
300
+
301
+ /**
302
+ * One side of a parcel as it lies on the land: points about `spacing` metres apart along the surveyed edge, each bent with the plan.
303
+ */
304
+ function boundary(parcel, edge, spacing) {
305
+ const line = [];
306
+ for (let half = 0; half < 2; half++) {
307
+ const a = parcel.ring[edge * 2 + half],
308
+ b = parcel.ring[(edge * 2 + half + 1) % 8];
309
+ const steps = Math.max(1, Math.round(Math.hypot(b[0] - a[0], b[1] - a[1]) / spacing));
310
+ for (let i = half ? 1 : 0; i <= steps; i++) line.push(unbend(lerp(a[0], b[0], i / steps), lerp(a[1], b[1], i / steps), [0, 0]));
311
+ }
312
+ return line;
313
+ }
314
+
315
+ // Lays the maps out empty: their sizes follow from the farmland's own.
316
+ function layOut(fields) {
317
+ const width = (fields.width = Math.ceil(fields.w / fields.scale)),
318
+ height = (fields.height = Math.ceil(fields.d / fields.scale));
319
+ fields.data = new Uint8Array(width * height * 4);
320
+ fields.lots = new Uint8Array(width * height * 4);
321
+ fields.bendWidth = Math.ceil(width / BEND_STEP);
322
+ fields.bendHeight = Math.ceil(height / BEND_STEP);
323
+ fields.bend = new Uint8Array(fields.bendWidth * fields.bendHeight * 2);
324
+ fields.bendRange = BEND.broad + BEND.fine;
325
+ }
326
+ // The maps `draw` fills, and nothing else.
327
+ const maps = fields => [fields.data, fields.lots, fields.bend];
328
+
329
+ /**
330
+ * Draws the field maps: `fields.data` (the row angle, the use, the wheel ruts' strength and the coverage), `fields.lots` (the
331
+ * parcel's tint, the distance to the nearest row end, how far inside the season's work the point lies, and the distance to the
332
+ * nearest edge) and `fields.bend` (how far the plan lies from the land, for the shader to run its rows by), once `layOut` has
333
+ * been called and after `plan`.
334
+ */
335
+ function draw(fields) {
336
+ const { width, height: mapHeight, data: rgba, lots } = fields;
337
+ const raster = (x0, z0, x1, z1, paint) => {
338
+ const i0 = clamp(Math.floor((x0 - fields.x) / fields.scale), 0, width - 1),
339
+ i1 = clamp(Math.ceil((x1 - fields.x) / fields.scale), 0, width - 1);
340
+ const j0 = clamp(Math.floor((z0 - fields.z) / fields.scale), 0, mapHeight - 1),
341
+ j1 = clamp(Math.ceil((z1 - fields.z) / fields.scale), 0, mapHeight - 1);
342
+ for (let j = j0; j <= j1; j++)
343
+ for (let i = i0; i <= i1; i++) paint(fields.x + (i + 0.5) * fields.scale, fields.z + (j + 0.5) * fields.scale, (j * width + i) * 4);
344
+ };
345
+ const planPoint = [0, 0];
346
+ for (const parcel of fields.parcels) {
347
+ const { ring, use, angle, tint } = parcel;
348
+ const xs = ring.map(p => p[0]),
349
+ zs = ring.map(p => p[1]);
350
+ const ends = ring.map((a, i) => {
351
+ const b = ring[(i + 1) % ring.length];
352
+ return Math.abs(Math.cos(Math.atan2(b[1] - a[1], b[0] - a[0]) - angle)) < END_EDGE;
353
+ });
354
+ raster(
355
+ Math.min(...xs) - BEND.reach,
356
+ Math.min(...zs) - BEND.reach,
357
+ Math.max(...xs) + BEND.reach,
358
+ Math.max(...zs) + BEND.reach,
359
+ (x, z, k) => {
360
+ // the cheap test first (is the point in this parcel at all?), then the land's own say, then the distances
361
+ const [px, pz] = bend(x, z, planPoint);
362
+ if (!ringContains(ring, px, pz)) return;
363
+ const roadHere = road(x, z);
364
+ if (roadHere < 8 || river(x, z) < 12 || height(x, z) < 8.9 || !clear(x, z)) return;
365
+ let edge = 12.75,
366
+ end = 12.75;
367
+ for (let i = 0; i < ring.length; i++) {
368
+ const d = segmentDistance(px, pz, ring[i], ring[(i + 1) % ring.length]);
369
+ edge = Math.min(edge, d);
370
+ if (ends[i]) end = Math.min(end, d);
371
+ }
372
+ const raggedEdge = edge + (noise(x / ragged.span, z / ragged.span, ragged.seed) - 0.5) * ragged.metres;
373
+ if (raggedEdge < edgeLeast) return;
374
+ rgba[k] = Math.round((angle / Math.PI) * 255);
375
+ rgba[k + 1] = kindStep * use;
376
+ rgba[k + 3] = Math.round(sstep(0.09, 1.4, raggedEdge) * sstep(8, 11, roadHere) * 255);
377
+ lots[k] = Math.round(tint * 255);
378
+ lots[k + 1] = Math.round(end * LOT_METRES);
379
+ const depth =
380
+ workedDepth(parcel, px, pz) + (noise(x / workNoise.span, z / workNoise.span, workNoise.seed) - 0.5) * workNoise.metres;
381
+ lots[k + 2] = clamp(Math.round(WORK_LEVEL + depth * WORK_METRES), 0, 255);
382
+ lots[k + 3] = Math.round(edge * LOT_METRES);
383
+ },
384
+ );
385
+ }
386
+ softenFieldCoverage(rgba, width, mapHeight, { coverageChannel: 3 });
387
+ extendFieldBorders(rgba, lots, width, mapHeight, { coverageChannel: 3, fieldChannels: [0, 1], attributeChannels: [0, 1, 2, 3] });
388
+ for (const path of fields.tracks) {
389
+ const xs = path.map(p => p[0]),
390
+ zs = path.map(p => p[1]);
391
+ raster(Math.min(...xs) - 4, Math.min(...zs) - 4, Math.max(...xs) + 4, Math.max(...zs) + 4, (x, z, k) => {
392
+ if (!clear(x, z)) return;
393
+ const d = trackAt(fields, x, z, 3.1);
394
+ rgba[k + 2] = Math.round(sstep(2.5, 1.3, d) * (1 - sstep(0.38, 0.9, Math.abs(d - 0.77))) * 255);
395
+ rgba[k + 3] *= sstep(1.3, 3.1, d);
396
+ });
397
+ }
398
+ for (const { x, z } of fields.yards)
399
+ raster(x - 20, z - 20, x + 20, z + 20, (px, pz, k) => {
400
+ const mask = yardAt(fields, px, pz);
401
+ if (mask < 0.02 || !clear(px, pz) || road(px, pz) < 7) return;
402
+ rgba[k + 1] = kindStep * FIELD_USE.yard;
403
+ rgba[k + 3] = Math.round(mask * 255);
404
+ });
405
+ const { bendWidth: bendW, bendHeight: bendH, bend: bendMap } = fields;
406
+ for (let j = 0; j < bendH; j++)
407
+ for (let i = 0; i < bendW; i++) {
408
+ const x = fields.x + (i + 0.5) * BEND_STEP * fields.scale,
409
+ z = fields.z + (j + 0.5) * BEND_STEP * fields.scale;
410
+ bend(x, z, planPoint);
411
+ bendMap[(j * bendW + i) * 2] = Math.round(((planPoint[0] - x) / fields.bendRange) * 127.5 + 127.5);
412
+ bendMap[(j * bendW + i) * 2 + 1] = Math.round(((planPoint[1] - z) / fields.bendRange) * 127.5 + 127.5);
413
+ }
414
+ }
415
+
416
+ // The index of the map's pixel at (x, z) in its arrays, or -1 off the map.
417
+ function pixel(fields, x, z) {
418
+ const i = Math.floor((x - fields.x) / fields.scale),
419
+ j = Math.floor((z - fields.z) / fields.scale);
420
+ return i >= 0 && i < fields.width && j >= 0 && j < fields.height ? (j * fields.width + i) * 4 : -1;
421
+ }
422
+ /**
423
+ * What the field map says of a point of the land: [use, coverage 0..1, worked 0 or 1, metres to the parcel's edge], or null off
424
+ * the map.
425
+ */
426
+ function lot(fields, x, z, out) {
427
+ const k = pixel(fields, x, z);
428
+ if (k < 0) return null;
429
+ out[0] = Math.round(fields.data[k + 1] / kindStep);
430
+ out[1] = fields.data[k + 3] / 255;
431
+ out[2] = fields.lots[k + 2] > WORK_LEVEL ? 1 : 0;
432
+ out[3] = fields.lots[k + 3] / LOT_METRES;
433
+ return out;
434
+ }
435
+ /**
436
+ * Visits points of one parcel on a grid laid along its rows (`alongStep` by `acrossStep` metres, each shaken by up to `shake`),
437
+ * as they lie on the land: visit(x, z, lot), where lot is the map's reading there. Points the parcel does not cover are passed over.
438
+ */
439
+ function points(fields, parcel, alongStep, acrossStep, shake, rng, visit) {
440
+ const [c, s] = parcel.axis,
441
+ land = [0, 0],
442
+ lotAt = [0, 0, 0, 0],
443
+ angle = Math.round((parcel.angle / Math.PI) * 255);
444
+ for (let v = parcel.across[0] + acrossStep * 0.5; v < parcel.across[1]; v += acrossStep)
445
+ for (let u = parcel.along[0] + alongStep * 0.5; u < parcel.along[1]; u += alongStep) {
446
+ const pu = u + (rng() - 0.5) * 2 * shake,
447
+ pv = v + (rng() - 0.5) * 2 * shake;
448
+ unbend(pu * c - pv * s, pu * s + pv * c, land);
449
+ const k = pixel(fields, land[0], land[1]);
450
+ if (k < 0 || fields.data[k] !== angle || !lot(fields, land[0], land[1], lotAt) || lotAt[0] !== parcel.use) continue;
451
+ visit(land[0], land[1], lotAt);
452
+ }
453
+ }
454
+ // Whether a place is farmed ground or a farmyard's track (covered by the field map or rutted by the track).
455
+ const cleared = (fields, x, z) => {
456
+ const k = pixel(fields, x, z);
457
+ return k >= 0 && (fields.data[k + 3] > 30 || fields.data[k + 2] > 30);
458
+ };
459
+
460
+ return { USE: FIELD_USE, bend, unbend, plan, boundary, yardAt, trackAt, layOut, draw, maps, lot, points, pixel, cleared };
461
+ }