Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion builder/web/src/lib/trailview/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ export class TrailView {
this.trees = new TreeModels(this.instances, () => this.request(), () => this.treesNear(), signal, TREE_VERSION);
this.forest = new Forest(config, this.groundLook.rules, this.trees, this.instances, () => this.request(), signal, budget);
this.plants = new Plants(this.groundLook.rules, this.trees, this.instances, () => this.request(), signal);
this.rows = new Rows(this.groundLook.rules, this.trees, this.plants, this.instances);
this.rows = new Rows(config, this.groundLook.rules, this.trees, this.plants, this.instances);
this.kindPoints = new KindPoints(this.instances);
this.dressing = new Dressing(this.groundLook.rules, this.instances);
// A still has a size of its own and no input: the controls listen for keys on the whole window.
Expand Down
67 changes: 54 additions & 13 deletions builder/web/src/lib/trailview/vegetation/rows.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { PlannerConfig } from '../../planner/config';
import { worldPixel } from '../../planner/layers/mercator';
import { anchorAt, UNITS } from '../frame/space';
import type { Gpu } from '../gpu/device';
Expand All @@ -15,7 +16,20 @@ const CROPS = 4, BASE = 2 ** 11, NO_CROP = 0xffffffff, NO_MODEL = 0xffff, WINDWA
/** Words of `Data` in rows.wgsl before its models: the crop of each material code, then the crops. */
const MODELS_AT = 64 + 4 * CROPS;

interface Resources { gpu: Gpu; pipeline: GPUComputePipeline; groups: GPUBindGroup[]; params: GPUBuffer; surface: GPUBindGroup; features: GPUBindGroup }
/** Bytes of the header of `RowCells` in rows.wgsl and of a listed cell. */
const HEADER_BYTES = 16, CELL_BYTES = 16;

interface Resources {
gpu: Gpu;
findRows: GPUComputePipeline;
plantings: GPUComputePipeline;
/** Per view the group 0 of `find_rows`, which lists the cells in view, and of `plantings`, which reads them and dispatches by their count. */
groups: [GPUBindGroup, GPUBindGroup][];
cells: GPUBuffer[];
params: GPUBuffer;
surface: GPUBindGroup;
features: GPUBindGroup;
}

/**
* The plantings (rows.wgsl): the plants of the materials whose `rows` (materials.json) say how they are
Expand All @@ -27,9 +41,14 @@ export class Rows implements Producer {
private resources?: Resources;
private readonly data: Uint32Array<ArrayBuffer>;
private readonly reach: number;
/**
* Base cells a side of the window at the highest latitude that the view serves: the cell list's size. `plantings`
* dispatches one dimension, at most 65,535 workgroups: the reach of 2 km holds fewer cells up to about 79° N.
*/
private readonly most: number;
private side = 0;

constructor(rules: Rules, trees: TreeModels, plants: Plants, private readonly instances: Instances) {
constructor(config: PlannerConfig, rules: Rules, trees: TreeModels, plants: Plants, private readonly instances: Instances) {
instances.produce(this);
// tools/trailview/rules.py checks that CROPS materials at most have rows.
const crops = rules.vocabulary.materials.flatMap(({ rows }, code) => (rows ? [{ code, rows }] : [])).slice(0, CROPS);
Expand All @@ -53,6 +72,7 @@ export class Rows implements Producer {
}));
this.data = data;
this.reach = Math.max(0, ...crops.map(({ rows }) => rows.reach_m));
this.most = this.sideAt(Math.max(Math.abs(config.bounds[1]), Math.abs(config.bounds[3])));
}

async attach(gpu: Gpu, { surface, features }: Surfaces): Promise<void> {
Expand All @@ -61,10 +81,17 @@ export class Rows implements Producer {
const data = gpu.buffer('vegetation', this.data.byteLength, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST);
const params = gpu.buffer('vegetation', 16, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
device.queue.writeBuffer(data, 0, this.data);
const pipeline = await gpu.once(rowsPipeline);
const cells = VIEWS.map(() => gpu.buffer('vegetation', HEADER_BYTES + CELL_BYTES * Math.max(1, this.most ** 2), GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST));
const [findRows, plantings] = await gpu.once(rowsPipelines);
this.resources = {
gpu, pipeline, params, surface, features,
groups: VIEWS.map(view => device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [...this.instances.emitResources(view), { binding: 8, resource: { buffer: data } }, { binding: 9, resource: { buffer: params } }] })),
gpu, findRows, plantings, cells, params, surface, features,
groups: VIEWS.map(view => {
const entries = [...this.instances.emitResources(view), { binding: 8, resource: { buffer: data } }, { binding: 9, resource: { buffer: params } }];
return [
device.createBindGroup({ layout: findRows.getBindGroupLayout(0), entries: [...entries, { binding: 10, resource: { buffer: cells[view] } }] }),
device.createBindGroup({ layout: plantings.getBindGroupLayout(0), entries: [...entries, { binding: 11, resource: { buffer: cells[view] } }] }),
];
}),
};
}

Expand All @@ -73,30 +100,44 @@ export class Rows implements Producer {
const r = this.resources;
if (!r) return;
const [ux, uy] = worldPixel(lonLat, UNITS);
this.side = this.reach ? 2 * Math.ceil(this.reach / (BASE * anchorAt(...lonLat).unit)) + 2 : 0;
// An eye past the bounds' highest latitude keeps the window of the list's size, as the forest does: the list holds every cell.
this.side = Math.min(this.most, this.sideAt(lonLat[1]));
// Base cell b starts at (b + 1) × BASE, half a field cell past a whole one.
const params = new Int32Array([Math.floor(ux / BASE) - 1 - this.side / 2, Math.floor(uy / BASE) - 1 - this.side / 2, this.side, 0]);
new Float32Array(params.buffer)[3] = this.reach;
r.gpu.device.queue.writeBuffer(r.params, 0, params);
for (const cells of r.cells) r.gpu.device.queue.writeBuffer(cells, 0, new Uint32Array([0, 1, 1, 0]));
}

/** Base cells a side of the window about an eye at a latitude: the reach each way, and a cell more. */
private sideAt(lat: number): number {
return this.reach ? 2 * Math.ceil(this.reach / (BASE * anchorAt(0, lat).unit)) + 2 : 0;
}

encode(pass: GPUComputePassEncoder, ground: GPUBindGroup, view: number): void {
const r = this.resources;
if (!r || !this.side) return;
pass.setBindGroup(0, r.groups[view]);
pass.setBindGroup(0, r.groups[view][0]);
pass.setBindGroup(1, r.surface);
pass.setBindGroup(2, ground);
pass.setBindGroup(3, r.features);
pass.setPipeline(r.pipeline);
pass.dispatchWorkgroups(this.side, this.side);
pass.setPipeline(r.findRows);
pass.dispatchWorkgroups(Math.ceil(this.side / 8), Math.ceil(this.side / 8));
pass.setPipeline(r.plantings);
pass.setBindGroup(0, r.groups[view][1]);
pass.dispatchWorkgroupsIndirect(r.cells[view], 0);
}
}

function rowsPipeline(gpu: Gpu): Promise<GPUComputePipeline> {
/** The base cells of the rows in view, and the plants in them. */
function rowsPipelines(gpu: Gpu): Promise<GPUComputePipeline[]> {
const { device } = gpu, C = GPUShaderStage.COMPUTE, { surface, ground, features } = gpu.once(layouts);
const group = device.createBindGroupLayout({ entries: [
const shared: GPUBindGroupLayoutEntry[] = [
...Instances.emitEntries(), { binding: 8, visibility: C, buffer: { type: 'read-only-storage' } }, { binding: 9, visibility: C, buffer: { type: 'uniform' } },
] });
];
const module = device.createShaderModule({ label: 'rows', code: wgsl('vegetation/rows.wgsl') });
return device.createComputePipelineAsync({ label: 'plantings', layout: device.createPipelineLayout({ bindGroupLayouts: [group, surface, ground, features] }), compute: { module, entryPoint: 'plantings' } });
return Promise.all(([['find_rows', { binding: 10, visibility: C, buffer: { type: 'storage' } }], ['plantings', { binding: 11, visibility: C, buffer: { type: 'read-only-storage' } }]] as const).map(([entryPoint, list]) => {
const group = device.createBindGroupLayout({ entries: [...shared, list] });
return device.createComputePipelineAsync({ label: entryPoint, layout: device.createPipelineLayout({ bindGroupLayouts: [group, surface, ground, features] }), compute: { module, entryPoint } });
}));
}
85 changes: 65 additions & 20 deletions builder/web/src/lib/trailview/vegetation/rows.wgsl
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// The plantings: the plants of the materials planted in rows, on the rows of the material fields
// (ground/fields.wgsl), placed on the GPU each frame with no stored position.
//
// One workgroup per base cell, half a field cell, laid so that each point of it looks at the same
// 2 × 2 field cells. A cell samples which crops its ground holds, then walks the row points of each
// `find_rows` lists the base cells in view, one thread per base cell of the window; `plantings` runs
// one workgroup per listed cell. A base cell is half a field cell, laid so that each point of it looks
// at the same 2 × 2 field cells. A cell samples which crops its ground holds, then walks the row points of each
// crop's fields that may lie in it. A crop thins past THIN times the square root of the area of a
// plant: point (i, j) of a field, i along the rows and j across them, stands to that distance times
// 2^r, where 2^r divides both i and j. So the far rows keep every 2^r-th plant of every 2^r-th row, a
Expand Down Expand Up @@ -39,6 +40,25 @@ struct Data {
@group(0) @binding(8) var<storage, read> data: Data;
@group(0) @binding(9) var<uniform> window: Window;

// The base cells in view, which `find_rows` lists: each as its base cell and the bits of its middle's
// height. Its count is the indirect dispatch of `plantings`.
struct RowCells {
groups: atomic<u32>,
y: u32,
z: u32,
unused: u32,
list: array<vec4i>,
}

// The list as `plantings` reads it.
struct ListedRows {
header: vec4u,
list: array<vec4i>,
}

@group(0) @binding(10) var<storage, read_write> found_rows: RowCells;
@group(0) @binding(11) var<storage, read> listed_rows: ListedRows;

const CROPS: u32 = 4u;
const NO_CROP: u32 = 0xffffffffu;
const NO_MODEL: u32 = 0xffffu;
Expand All @@ -60,7 +80,6 @@ const TALLEST_M: f32 = 12.0;
const MOST: u32 = 8192u;
const LANES: u32 = 256u;

var<workgroup> cell_ground: f32;
var<workgroup> found: atomic<u32>;
var<workgroup> crops_here: u32;

Expand All @@ -72,30 +91,56 @@ fn plant_hash(u: vec2i, salt: u32) -> f32 {
return unit_float(mix_bits3(u.x, u.y, salt));
}

// Half a field cell past a whole one, so the cell's points look at the field cells from base / 2.
fn row_corner(base: vec2i) -> vec2i {
return (base << vec2u(BASE_SHIFT)) + vec2i(BASE);
}

// The metres from the eye to the nearest point of a base cell.
fn row_nearest(base: vec2i) -> f32 {
let half = 0.5 * f32(BASE) * surface.unit;
return length(max(abs(lod_at(row_corner(base) + vec2i(BASE / 2))) - half, vec2f(0.0)));
}

// One thread per base cell of the window: the cell, listed with its middle's height, if it lies within
// the reach and its box is in view. The box holds its ground within SLOPE_M of its middle's, and its plants.
@compute @workgroup_size(8, 8)
fn find_rows(@builtin(global_invocation_id) id: vec3u) {
if (any(id.xy >= vec2u(window.side))) {
return;
}
let base = window.origin + vec2i(id.xy);
if (row_nearest(base) > window.reach) {
return;
}
let middle = row_corner(base) + vec2i(BASE / 2);
let centre_s = lod_at(middle);
let height = units_height(middle, u32(ceil(lod(centre_s))));
let radius = 1.5 * (0.5 * f32(BASE) * surface.unit) + SLOPE_M + TALLEST_M;
let centre = render_at(centre_s, height + 0.5 * TALLEST_M);
if (!known(height) || !visible(centre, radius) || hidden(centre, radius)) {
return;
}
let k = atomicAdd(&found_rows.groups, 1u);
if (k < arrayLength(&found_rows.list)) {
found_rows.list[k] = vec4i(base, bitcast<i32>(height), 0);
}
}

@compute @workgroup_size(LANES)
fn plantings(@builtin(workgroup_id) group: vec3u, @builtin(local_invocation_index) lane: u32) {
let base = window.origin + vec2i(group.xy);
// Half a field cell past a whole one, so the cell's points look at the field cells from base / 2.
let corner = (base << vec2u(BASE_SHIFT)) + vec2i(BASE);
let middle = corner + vec2i(BASE / 2);
let centre_s = lod_at(middle);
let half = 0.5 * f32(BASE) * surface.unit;
let nearest = length(max(abs(centre_s) - half, vec2f(0.0)));
if (nearest > window.reach) {
if (group.x >= arrayLength(&listed_rows.list)) {
return;
}
// One lane culls the cell: its box holds its ground within SLOPE_M of its middle's, and its plants.
let entry = listed_rows.list[group.x];
let base = entry.xy;
let corner = row_corner(base);
let nearest = row_nearest(base);
let ground = bitcast<f32>(entry.z);
if (lane == 0u) {
let height = units_height(middle, u32(ceil(lod(centre_s))));
let radius = 1.5 * half + SLOPE_M + TALLEST_M;
let centre = render_at(centre_s, height + 0.5 * TALLEST_M);
cell_ground = select(NONE, height, known(height) && visible(centre, radius) && !hidden(centre, radius));
atomicStore(&found, 0u);
}
let ground = workgroupUniformLoad(&cell_ground);
if (!known(ground)) {
return;
}
workgroupBarrier();
// The crops of the cell: its ground on an 8 × 8 grid.
if (lane < 64u) {
let sampled = finest_cell(lod_at(corner + vec2i((vec2f(f32(lane % 8u), f32(lane / 8u)) + 0.5) * f32(BASE / 8))));
Expand Down
Loading