WIP
This commit is contained in:
parent
34ac200437
commit
39b0160064
136 changed files with 7129 additions and 1950 deletions
36
src/pipelines/agents/agent-generation/agent-compaction.wgsl
Normal file
36
src/pipelines/agents/agent-generation/agent-compaction.wgsl
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
struct Settings {
|
||||
agentCount: u32,
|
||||
padding0: u32,
|
||||
padding1: u32,
|
||||
padding2: u32,
|
||||
};
|
||||
|
||||
struct Counters {
|
||||
aliveAgentCount: atomic<u32>,
|
||||
padding0: atomic<u32>,
|
||||
padding1: atomic<u32>,
|
||||
};
|
||||
|
||||
@group(1) @binding(0) var<uniform> settings: Settings;
|
||||
@group(1) @binding(2) var<storage, read_write> counters: Counters;
|
||||
@group(1) @binding(3) var<storage, read_write> compactedAgents: array<Agent>;
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn main(
|
||||
@builtin(global_invocation_id) global_id: vec3<u32>,
|
||||
@builtin(num_workgroups) workgroup_count: vec3<u32>
|
||||
) {
|
||||
let id = get_id(global_id, workgroup_count);
|
||||
|
||||
if id >= settings.agentCount {
|
||||
return;
|
||||
}
|
||||
|
||||
let agent = agents[id];
|
||||
if agent.colorIndex < 0.0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let compactedIndex = atomicAdd(&counters.aliveAgentCount, 1);
|
||||
compactedAgents[compactedIndex] = agent;
|
||||
}
|
||||
|
|
@ -5,8 +5,8 @@ struct Settings {
|
|||
@group(1) @binding(0) var<uniform> settings: Settings;
|
||||
|
||||
struct Counters {
|
||||
evenGenerationAlive: atomic<u32>,
|
||||
oddGenerationAlive: atomic<u32>,
|
||||
redAgentsAlive: atomic<u32>,
|
||||
greenAgentsAlive: atomic<u32>,
|
||||
};
|
||||
|
||||
@group(1) @binding(2) var<storage, read_write> counters: Counters;
|
||||
|
|
@ -23,9 +23,13 @@ fn main(
|
|||
return;
|
||||
}
|
||||
|
||||
if agents[id].generation % 2 == 0 {
|
||||
atomicAdd(&counters.evenGenerationAlive, 1);
|
||||
if agents[id].colorIndex < 0.0 {
|
||||
return;
|
||||
}
|
||||
|
||||
if agents[id].colorIndex < 0.5 {
|
||||
atomicAdd(&counters.redAgentsAlive, 1);
|
||||
} else {
|
||||
atomicAdd(&counters.oddGenerationAlive, 1);
|
||||
atomicAdd(&counters.greenAgentsAlive, 1);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,5 +30,8 @@ fn main(
|
|||
randomPosition.xz * state.size,
|
||||
random.r * 3.14 * 2,
|
||||
0,
|
||||
vec2<f32>(-1.0, -1.0),
|
||||
0.0,
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +1,42 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
|
||||
import { getWorkgroupCounts } from '../../../utils/graphics/get-workgroup-counts';
|
||||
import { smartCompile } from '../../../utils/graphics/smart-compile';
|
||||
import { CommonState } from '../../common-state/common-state';
|
||||
import { AGENT_SIZE_IN_BYTES } from './agent';
|
||||
import compactionShader from './agent-compaction.wgsl?raw';
|
||||
import countingShader from './agent-counting.wgsl?raw';
|
||||
import firstGenerationShader from './agent-first-generation.wgsl?raw';
|
||||
import resizeShader from './agent-resize.wgsl?raw';
|
||||
import agentSchema from './agent-schema.wgsl?raw';
|
||||
import { GenerationCounts } from './generation-counts';
|
||||
|
||||
export class AgentGenerationPipeline {
|
||||
private static readonly WORKGROUP_SIZE = 64;
|
||||
private static readonly UNIFORM_COUNT = 1;
|
||||
private static readonly UNIFORM_COUNT = 4;
|
||||
private static readonly COUNTER_COUNT = 3;
|
||||
|
||||
private readonly bindGroupLayout: GPUBindGroupLayout;
|
||||
private readonly compactionBindGroupLayout: GPUBindGroupLayout;
|
||||
private readonly uniforms: GPUBuffer;
|
||||
private readonly bindGroup: GPUBindGroup;
|
||||
private readonly compactionBindGroup: GPUBindGroup;
|
||||
|
||||
private readonly firstGenerationPipeline: GPUComputePipeline;
|
||||
private readonly countingPipeline: GPUComputePipeline;
|
||||
private readonly resizePipeline: GPUComputePipeline;
|
||||
private readonly compactionPipeline: GPUComputePipeline;
|
||||
|
||||
public readonly agentsBuffer: GPUBuffer;
|
||||
private readonly compactedAgentsBuffer: GPUBuffer;
|
||||
public readonly countersBuffer: GPUBuffer;
|
||||
public readonly countersStagingBuffer: GPUBuffer;
|
||||
private readonly counterClearValues = new Uint32Array(
|
||||
AgentGenerationPipeline.COUNTER_COUNT
|
||||
);
|
||||
private readonly agentCountUniformValues = new Uint32Array(
|
||||
AgentGenerationPipeline.UNIFORM_COUNT
|
||||
);
|
||||
|
||||
public constructor(
|
||||
private readonly device: GPUDevice,
|
||||
|
|
@ -54,9 +69,47 @@ export class AgentGenerationPipeline {
|
|||
],
|
||||
});
|
||||
|
||||
this.compactionBindGroupLayout = device.createBindGroupLayout({
|
||||
entries: [
|
||||
{
|
||||
binding: 0,
|
||||
visibility: GPUShaderStage.COMPUTE,
|
||||
buffer: {
|
||||
type: 'uniform',
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 1,
|
||||
visibility: GPUShaderStage.COMPUTE,
|
||||
buffer: {
|
||||
type: 'storage',
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 2,
|
||||
visibility: GPUShaderStage.COMPUTE,
|
||||
buffer: {
|
||||
type: 'storage',
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 3,
|
||||
visibility: GPUShaderStage.COMPUTE,
|
||||
buffer: {
|
||||
type: 'storage',
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
this.agentsBuffer = this.device.createBuffer({
|
||||
size: this.maxAgentCount * AGENT_SIZE_IN_BYTES,
|
||||
usage: GPUBufferUsage.STORAGE,
|
||||
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
|
||||
});
|
||||
|
||||
this.compactedAgentsBuffer = this.device.createBuffer({
|
||||
size: this.maxAgentCount * AGENT_SIZE_IN_BYTES,
|
||||
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
|
||||
});
|
||||
|
||||
this.countersBuffer = this.device.createBuffer({
|
||||
|
|
@ -98,6 +151,36 @@ export class AgentGenerationPipeline {
|
|||
],
|
||||
});
|
||||
|
||||
this.compactionBindGroup = this.device.createBindGroup({
|
||||
layout: this.compactionBindGroupLayout,
|
||||
entries: [
|
||||
{
|
||||
binding: 0,
|
||||
resource: {
|
||||
buffer: this.uniforms,
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 1,
|
||||
resource: {
|
||||
buffer: this.agentsBuffer,
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 2,
|
||||
resource: {
|
||||
buffer: this.countersBuffer,
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 3,
|
||||
resource: {
|
||||
buffer: this.compactedAgentsBuffer,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
this.firstGenerationPipeline = device.createComputePipeline({
|
||||
layout: device.createPipelineLayout({
|
||||
bindGroupLayouts: [commonState.bindGroupLayout, this.bindGroupLayout],
|
||||
|
|
@ -122,16 +205,79 @@ export class AgentGenerationPipeline {
|
|||
entryPoint: 'main',
|
||||
},
|
||||
});
|
||||
|
||||
this.resizePipeline = device.createComputePipeline({
|
||||
layout: device.createPipelineLayout({
|
||||
bindGroupLayouts: [commonState.bindGroupLayout, this.bindGroupLayout],
|
||||
}),
|
||||
compute: {
|
||||
module: smartCompile(device, CommonState.shaderCode, agentSchema, resizeShader),
|
||||
entryPoint: 'main',
|
||||
},
|
||||
});
|
||||
|
||||
this.compactionPipeline = device.createComputePipeline({
|
||||
layout: device.createPipelineLayout({
|
||||
bindGroupLayouts: [commonState.bindGroupLayout, this.compactionBindGroupLayout],
|
||||
}),
|
||||
compute: {
|
||||
module: smartCompile(
|
||||
device,
|
||||
CommonState.shaderCode,
|
||||
agentSchema,
|
||||
compactionShader
|
||||
),
|
||||
entryPoint: 'main',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public get maxAgentCount(): number {
|
||||
return Math.min(
|
||||
this.maxAgentCountUpperLimit,
|
||||
Number.isFinite(this.maxAgentCountUpperLimit)
|
||||
? this.maxAgentCountUpperLimit
|
||||
: Number.POSITIVE_INFINITY,
|
||||
Math.floor(this.device.limits.maxBufferSize / AGENT_SIZE_IN_BYTES) - 1,
|
||||
this.device.limits.maxComputeWorkgroupsPerDimension ** 3
|
||||
);
|
||||
}
|
||||
|
||||
public writeAgents(agentOffset: number, data: Float32Array): void {
|
||||
this.device.queue.writeBuffer(
|
||||
this.agentsBuffer,
|
||||
agentOffset * AGENT_SIZE_IN_BYTES,
|
||||
data
|
||||
);
|
||||
}
|
||||
|
||||
public resizeAgents(agentCount: number, scale: vec2): void {
|
||||
if (agentCount <= 0 || vec2.equals(scale, vec2.fromValues(1, 1))) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.device.queue.writeBuffer(
|
||||
this.uniforms,
|
||||
0,
|
||||
new Float32Array([scale[0], scale[1], agentCount, 0])
|
||||
);
|
||||
|
||||
const commandEncoder = this.device.createCommandEncoder();
|
||||
const passEncoder = commandEncoder.beginComputePass();
|
||||
this.commonState.execute(passEncoder);
|
||||
passEncoder.setPipeline(this.resizePipeline);
|
||||
passEncoder.setBindGroup(1, this.bindGroup);
|
||||
passEncoder.dispatchWorkgroups(
|
||||
...getWorkgroupCounts(
|
||||
this.device,
|
||||
agentCount,
|
||||
AgentGenerationPipeline.WORKGROUP_SIZE
|
||||
)
|
||||
);
|
||||
passEncoder.end();
|
||||
|
||||
this.device.queue.submit([commandEncoder.finish()]);
|
||||
}
|
||||
|
||||
public spawnFirstGeneration(): void {
|
||||
const commandEncoder = this.device.createCommandEncoder();
|
||||
|
||||
|
|
@ -152,8 +298,11 @@ export class AgentGenerationPipeline {
|
|||
}
|
||||
|
||||
public async countAgents(agentCount: number): Promise<GenerationCounts> {
|
||||
this.device.queue.writeBuffer(this.countersBuffer, 0, new Uint32Array([0, 0]));
|
||||
this.device.queue.writeBuffer(this.uniforms, 0, new Uint32Array([agentCount]));
|
||||
this.counterClearValues.fill(0);
|
||||
this.agentCountUniformValues.fill(0);
|
||||
this.agentCountUniformValues[0] = agentCount;
|
||||
this.device.queue.writeBuffer(this.countersBuffer, 0, this.counterClearValues);
|
||||
this.device.queue.writeBuffer(this.uniforms, 0, this.agentCountUniformValues);
|
||||
|
||||
const commandEncoder = this.device.createCommandEncoder();
|
||||
|
||||
|
|
@ -190,10 +339,62 @@ export class AgentGenerationPipeline {
|
|||
};
|
||||
}
|
||||
|
||||
public async compactAgents(agentCount: number): Promise<number> {
|
||||
if (agentCount <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.counterClearValues.fill(0);
|
||||
this.agentCountUniformValues.fill(0);
|
||||
this.agentCountUniformValues[0] = agentCount;
|
||||
this.device.queue.writeBuffer(this.countersBuffer, 0, this.counterClearValues);
|
||||
this.device.queue.writeBuffer(this.uniforms, 0, this.agentCountUniformValues);
|
||||
|
||||
const commandEncoder = this.device.createCommandEncoder();
|
||||
const passEncoder = commandEncoder.beginComputePass();
|
||||
passEncoder.setPipeline(this.compactionPipeline);
|
||||
this.commonState.execute(passEncoder);
|
||||
passEncoder.setBindGroup(1, this.compactionBindGroup);
|
||||
passEncoder.dispatchWorkgroups(
|
||||
...getWorkgroupCounts(
|
||||
this.device,
|
||||
agentCount,
|
||||
AgentGenerationPipeline.WORKGROUP_SIZE
|
||||
)
|
||||
);
|
||||
passEncoder.end();
|
||||
|
||||
commandEncoder.copyBufferToBuffer(
|
||||
this.compactedAgentsBuffer,
|
||||
0,
|
||||
this.agentsBuffer,
|
||||
0,
|
||||
agentCount * AGENT_SIZE_IN_BYTES
|
||||
);
|
||||
commandEncoder.copyBufferToBuffer(
|
||||
this.countersBuffer,
|
||||
0,
|
||||
this.countersStagingBuffer,
|
||||
0,
|
||||
Uint32Array.BYTES_PER_ELEMENT
|
||||
);
|
||||
|
||||
this.device.queue.submit([commandEncoder.finish()]);
|
||||
|
||||
await this.countersStagingBuffer.mapAsync(GPUMapMode.READ);
|
||||
const compactedCount = new Uint32Array(
|
||||
this.countersStagingBuffer.getMappedRange().slice(0, Uint32Array.BYTES_PER_ELEMENT)
|
||||
)[0];
|
||||
this.countersStagingBuffer.unmap();
|
||||
|
||||
return compactedCount;
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
this.uniforms.destroy();
|
||||
this.countersBuffer.destroy();
|
||||
this.countersStagingBuffer.destroy();
|
||||
this.compactedAgentsBuffer.destroy();
|
||||
this.agentsBuffer.destroy();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
74
src/pipelines/agents/agent-generation/agent-schema.test.ts
Normal file
74
src/pipelines/agents/agent-generation/agent-schema.test.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { AGENT_FLOAT_COUNT, AGENT_SIZE_IN_BYTES } from './agent';
|
||||
import compactionShader from './agent-compaction.wgsl?raw';
|
||||
import countingShader from './agent-counting.wgsl?raw';
|
||||
import firstGenerationShader from './agent-first-generation.wgsl?raw';
|
||||
import resizeShader from './agent-resize.wgsl?raw';
|
||||
import agentSchema from './agent-schema.wgsl?raw';
|
||||
|
||||
const wgslFloatCountByType: Record<string, number> = {
|
||||
f32: 1,
|
||||
'vec2<f32>': 2,
|
||||
};
|
||||
|
||||
const getAgentStructFields = () => {
|
||||
const match = /struct Agent\s*\{(?<body>[\s\S]*?)\n\}/.exec(agentSchema);
|
||||
if (!match?.groups?.body) {
|
||||
throw new Error('Agent struct was not found in agent-schema.wgsl');
|
||||
}
|
||||
|
||||
return match.groups.body
|
||||
.split('\n')
|
||||
.map((line) => line.trim().replace(/,$/, ''))
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const fieldMatch = /^(?<name>\w+):\s*(?<type>[^,]+)$/.exec(line);
|
||||
if (!fieldMatch?.groups) {
|
||||
throw new Error(`Unsupported Agent field syntax: ${line}`);
|
||||
}
|
||||
|
||||
return {
|
||||
name: fieldMatch.groups.name,
|
||||
type: fieldMatch.groups.type,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
describe('Agent TS/WGSL contract', () => {
|
||||
it('keeps the TypeScript float count aligned with the WGSL Agent struct', () => {
|
||||
const fields = getAgentStructFields();
|
||||
const wgslFloatCount = fields.reduce((sum, field) => {
|
||||
const count = wgslFloatCountByType[field.type];
|
||||
if (!count) {
|
||||
throw new Error(`Unsupported WGSL Agent field type: ${field.type}`);
|
||||
}
|
||||
|
||||
return sum + count;
|
||||
}, 0);
|
||||
|
||||
expect(fields.map((field) => field.name)).toEqual([
|
||||
'position',
|
||||
'angle',
|
||||
'colorIndex',
|
||||
'targetPosition',
|
||||
'targetAngle',
|
||||
'introDelay',
|
||||
]);
|
||||
expect(wgslFloatCount).toBe(AGENT_FLOAT_COUNT);
|
||||
expect(AGENT_SIZE_IN_BYTES).toBe(AGENT_FLOAT_COUNT * Float32Array.BYTES_PER_ELEMENT);
|
||||
});
|
||||
|
||||
it('keeps generation shader workgroup sizes aligned with agent indexing', () => {
|
||||
[firstGenerationShader, countingShader, resizeShader, compactionShader].forEach(
|
||||
(shader) => {
|
||||
expect(shader).toMatch(/@workgroup_size\(64\)/);
|
||||
}
|
||||
);
|
||||
|
||||
expect(agentSchema).toContain('workgroup_count.x * 64');
|
||||
expect(agentSchema).toContain('workgroup_count.x * workgroup_count.y * 64');
|
||||
expect(compactionShader).toContain('let id = get_id(global_id, workgroup_count);');
|
||||
expect(compactionShader).toContain('if id >= settings.agentCount');
|
||||
});
|
||||
});
|
||||
|
|
@ -3,7 +3,11 @@ import { vec2 } from 'gl-matrix';
|
|||
export interface Agent {
|
||||
position: vec2;
|
||||
angle: number;
|
||||
generation: number;
|
||||
colorIndex: number;
|
||||
targetPosition: vec2;
|
||||
targetAngle: number;
|
||||
introDelay: number;
|
||||
}
|
||||
|
||||
export const AGENT_SIZE_IN_BYTES = 4 * Float32Array.BYTES_PER_ELEMENT;
|
||||
export const AGENT_FLOAT_COUNT = 8;
|
||||
export const AGENT_SIZE_IN_BYTES = AGENT_FLOAT_COUNT * Float32Array.BYTES_PER_ELEMENT;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
|
||||
import {
|
||||
createCachedFloat32BufferWrite,
|
||||
writeFloat32BufferIfChanged,
|
||||
} from '../../utils/graphics/cached-buffer-write';
|
||||
import { getWorkgroupCounts } from '../../utils/graphics/get-workgroup-counts';
|
||||
import { smartCompile } from '../../utils/graphics/smart-compile';
|
||||
import { CommonState } from '../common-state/common-state';
|
||||
|
|
@ -9,14 +11,19 @@ import shader from './agent.wgsl?raw';
|
|||
|
||||
export class AgentPipeline {
|
||||
private static readonly WORKGROUP_SIZE = 64;
|
||||
private static readonly UNIFORM_COUNT = 19;
|
||||
private static readonly UNIFORM_COUNT = 8;
|
||||
|
||||
private readonly bindGroupLayout: GPUBindGroupLayout;
|
||||
private readonly pipeline: GPUComputePipeline;
|
||||
private readonly uniforms: GPUBuffer;
|
||||
private bindGroup?: GPUBindGroup;
|
||||
private previousTrailMapIn?: GPUTextureView;
|
||||
private previousTrailMapOut?: GPUTextureView;
|
||||
private readonly uniformValues = new Float32Array(AgentPipeline.UNIFORM_COUNT);
|
||||
private readonly uniformCache = createCachedFloat32BufferWrite(
|
||||
AgentPipeline.UNIFORM_COUNT
|
||||
);
|
||||
private readonly bindGroupsByTexture = new WeakMap<
|
||||
GPUTextureView,
|
||||
WeakMap<GPUTextureView, WeakMap<GPUTextureView, GPUBindGroup>>
|
||||
>();
|
||||
|
||||
private agentCount = 0;
|
||||
|
||||
|
|
@ -45,115 +52,108 @@ export class AgentPipeline {
|
|||
|
||||
public setParameters({
|
||||
deltaTime,
|
||||
center,
|
||||
radius,
|
||||
brushTrailWeight,
|
||||
moveSpeed,
|
||||
turnSpeed,
|
||||
sensorOffsetAngle,
|
||||
sensorOffsetDistance,
|
||||
nextGenerationSensorOffsetDistance,
|
||||
currentGenerationAggression,
|
||||
nextGenerationAggression,
|
||||
nextGenerationSpeed,
|
||||
isNextGenerationOdd,
|
||||
turnWhenLost,
|
||||
individualTrailWeight,
|
||||
infectionProbability,
|
||||
agentCount,
|
||||
introProgress,
|
||||
}: AgentSettings & {
|
||||
deltaTime: number;
|
||||
currentGenerationAggression: number;
|
||||
nextGenerationAggression: number;
|
||||
nextGenerationSensorOffsetDistance: number;
|
||||
nextGenerationSpeed: number;
|
||||
isNextGenerationOdd: number;
|
||||
center: vec2;
|
||||
radius: number;
|
||||
infectionProbability: number;
|
||||
agentCount: number;
|
||||
introProgress?: number;
|
||||
}) {
|
||||
this.agentCount = agentCount;
|
||||
this.device.queue.writeBuffer(
|
||||
this.uniformValues[0] = moveSpeed * deltaTime;
|
||||
this.uniformValues[1] = turnSpeed * deltaTime;
|
||||
this.uniformValues[2] = (sensorOffsetAngle * Math.PI) / 180;
|
||||
this.uniformValues[3] = sensorOffsetDistance;
|
||||
this.uniformValues[4] = turnWhenLost;
|
||||
this.uniformValues[5] = individualTrailWeight;
|
||||
this.uniformValues[6] = agentCount;
|
||||
this.uniformValues[7] = introProgress ?? 1;
|
||||
writeFloat32BufferIfChanged(
|
||||
this.device,
|
||||
this.uniforms,
|
||||
0,
|
||||
new Float32Array([
|
||||
...center,
|
||||
radius,
|
||||
|
||||
brushTrailWeight,
|
||||
moveSpeed * deltaTime,
|
||||
turnSpeed * deltaTime,
|
||||
|
||||
(sensorOffsetAngle * Math.PI) / 180,
|
||||
sensorOffsetDistance,
|
||||
|
||||
currentGenerationAggression,
|
||||
nextGenerationAggression,
|
||||
nextGenerationSensorOffsetDistance,
|
||||
nextGenerationSpeed * deltaTime,
|
||||
isNextGenerationOdd,
|
||||
|
||||
turnWhenLost,
|
||||
individualTrailWeight,
|
||||
infectionProbability,
|
||||
|
||||
agentCount,
|
||||
])
|
||||
this.uniformValues,
|
||||
this.uniformCache
|
||||
);
|
||||
}
|
||||
|
||||
public execute(
|
||||
commandEncoder: GPUCommandEncoder,
|
||||
trailMapIn: GPUTextureView,
|
||||
trailMapOut: GPUTextureView
|
||||
trailMapOut: GPUTextureView,
|
||||
sourceMap: GPUTextureView
|
||||
) {
|
||||
this.ensureBindGroupExists(trailMapIn, trailMapOut);
|
||||
const bindGroup = this.getBindGroup(trailMapIn, trailMapOut, sourceMap);
|
||||
|
||||
const passEncoder = commandEncoder.beginComputePass();
|
||||
passEncoder.setPipeline(this.pipeline);
|
||||
this.commonState.execute(passEncoder);
|
||||
passEncoder.setBindGroup(1, this.bindGroup);
|
||||
passEncoder.setBindGroup(1, bindGroup);
|
||||
passEncoder.dispatchWorkgroups(
|
||||
...getWorkgroupCounts(this.device, this.agentCount, AgentPipeline.WORKGROUP_SIZE)
|
||||
);
|
||||
passEncoder.end();
|
||||
}
|
||||
|
||||
private ensureBindGroupExists(trailMapIn: GPUTextureView, trailMapOut: GPUTextureView) {
|
||||
if (
|
||||
this.previousTrailMapIn !== trailMapIn ||
|
||||
this.previousTrailMapOut !== trailMapOut
|
||||
) {
|
||||
this.bindGroup = this.device.createBindGroup({
|
||||
layout: this.bindGroupLayout,
|
||||
entries: [
|
||||
{
|
||||
binding: 0,
|
||||
resource: {
|
||||
buffer: this.uniforms,
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 1,
|
||||
resource: {
|
||||
buffer: this.agentsBuffer,
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 2,
|
||||
resource: trailMapIn,
|
||||
},
|
||||
{
|
||||
binding: 3,
|
||||
resource: trailMapOut,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
this.previousTrailMapIn = trailMapIn;
|
||||
this.previousTrailMapOut = trailMapOut;
|
||||
private getBindGroup(
|
||||
trailMapIn: GPUTextureView,
|
||||
trailMapOut: GPUTextureView,
|
||||
sourceMap: GPUTextureView
|
||||
): GPUBindGroup {
|
||||
let outputCache = this.bindGroupsByTexture.get(trailMapIn);
|
||||
if (!outputCache) {
|
||||
outputCache = new WeakMap<GPUTextureView, WeakMap<GPUTextureView, GPUBindGroup>>();
|
||||
this.bindGroupsByTexture.set(trailMapIn, outputCache);
|
||||
}
|
||||
|
||||
let sourceCache = outputCache.get(trailMapOut);
|
||||
if (!sourceCache) {
|
||||
sourceCache = new WeakMap<GPUTextureView, GPUBindGroup>();
|
||||
outputCache.set(trailMapOut, sourceCache);
|
||||
}
|
||||
|
||||
const cached = sourceCache.get(sourceMap);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const bindGroup = this.device.createBindGroup({
|
||||
layout: this.bindGroupLayout,
|
||||
entries: [
|
||||
{
|
||||
binding: 0,
|
||||
resource: {
|
||||
buffer: this.uniforms,
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 1,
|
||||
resource: {
|
||||
buffer: this.agentsBuffer,
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 2,
|
||||
resource: trailMapIn,
|
||||
},
|
||||
{
|
||||
binding: 3,
|
||||
resource: trailMapOut,
|
||||
},
|
||||
{
|
||||
binding: 4,
|
||||
resource: sourceMap,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
sourceCache.set(sourceMap, bindGroup);
|
||||
return bindGroup;
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
|
|
@ -191,6 +191,13 @@ export class AgentPipeline {
|
|||
format: 'rgba16float',
|
||||
},
|
||||
},
|
||||
{
|
||||
binding: 4,
|
||||
visibility: GPUShaderStage.COMPUTE,
|
||||
texture: {
|
||||
sampleType: 'float',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,8 @@
|
|||
export interface AgentSettings {
|
||||
brushTrailWeight: number;
|
||||
moveSpeed: number;
|
||||
turnSpeed: number;
|
||||
sensorOffsetAngle: number;
|
||||
sensorOffsetDistance: number;
|
||||
turnWhenLost: number;
|
||||
individualTrailWeight: number;
|
||||
currentGenerationAggression: number;
|
||||
nextGenerationAggression: number;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,37 +1,18 @@
|
|||
struct Settings {
|
||||
center: vec2<f32>,
|
||||
radius: f32,
|
||||
|
||||
brushTrailWeight: f32,
|
||||
currentGenerationMoveRate: f32,
|
||||
moveRate: f32,
|
||||
turnRate: f32,
|
||||
|
||||
sensorAngle: f32,
|
||||
sensorOffset: f32,
|
||||
|
||||
currentGenerationAggression: f32,
|
||||
nextGenerationAggression: f32,
|
||||
nextGenerationSensorOffsetDistance: f32,
|
||||
nextGenerationMoveRate: f32,
|
||||
isNextGenerationOdd: f32,
|
||||
|
||||
turnWhenLost: f32,
|
||||
individualTrailWeight: f32,
|
||||
infectionProbability: f32,
|
||||
|
||||
agentCount: f32 // might be smaller than the length of the agents array
|
||||
agentCount: f32,
|
||||
introProgress: f32,
|
||||
};
|
||||
|
||||
|
||||
@group(1) @binding(0) var<uniform> settings: Settings;
|
||||
|
||||
// even generation's trail -> red channel
|
||||
// odd generation's trail -> green channel
|
||||
// unused -> blue channel
|
||||
// brush -> alpha channel
|
||||
@group(1) @binding(2) var trailMapIn: texture_2d<f32>;
|
||||
@group(1) @binding(3) var trailMapOut: texture_storage_2d<rgba16float, write>;
|
||||
|
||||
@group(1) @binding(4) var sourceMap: texture_2d<f32>;
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn main(
|
||||
|
|
@ -45,90 +26,125 @@ fn main(
|
|||
}
|
||||
|
||||
var agent = agents[id];
|
||||
if agent.colorIndex < 0.0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let hasIntroTarget =
|
||||
settings.introProgress < 0.999 &&
|
||||
agent.targetPosition.x >= 0.0 &&
|
||||
agent.targetPosition.y >= 0.0;
|
||||
|
||||
if hasIntroTarget && settings.introProgress < agent.introDelay {
|
||||
return;
|
||||
}
|
||||
|
||||
let random = textureSampleLevel(
|
||||
noise,
|
||||
noiseSampler,
|
||||
vec2(
|
||||
f32(id) % 23647 / 2000,
|
||||
state.time % 3243 / 2000
|
||||
),
|
||||
fract(vec2(f32(id) * 0.7548777, state.time * 0.00017 + f32(id) * 0.5698403)),
|
||||
0
|
||||
);
|
||||
|
||||
let isFromCurrentGeneration = abs(agent.generation - settings.isNextGenerationOdd);
|
||||
let isFromNextGeneration = 1.0 - isFromCurrentGeneration;
|
||||
let isFromOddGeneration = agent.generation % 2;
|
||||
let forwardSensor = sensor_position(agent.position, agent.angle, settings.sensorOffset, 0);
|
||||
let leftSensor = sensor_position(agent.position, agent.angle, settings.sensorOffset, settings.sensorAngle);
|
||||
let rightSensor = sensor_position(agent.position, agent.angle, settings.sensorOffset, -settings.sensorAngle);
|
||||
|
||||
let sensorOffset = mix(settings.sensorOffset, settings.nextGenerationSensorOffsetDistance, isFromNextGeneration);
|
||||
let moveRate = mix(settings.currentGenerationMoveRate, settings.nextGenerationMoveRate, isFromNextGeneration);
|
||||
let brushWeight = mix(settings.brushTrailWeight, 0, isFromNextGeneration);
|
||||
|
||||
let trailForward = sense(agent.position, agent.angle, sensorOffset, 0);
|
||||
let trailLeft = sense(agent.position, agent.angle, sensorOffset, settings.sensorAngle);
|
||||
let trailRight = sense(agent.position, agent.angle, sensorOffset, -settings.sensorAngle);
|
||||
let trailForward = textureLoad(trailMapIn, forwardSensor, 0);
|
||||
let trailLeft = textureLoad(trailMapIn, leftSensor, 0);
|
||||
let trailRight = textureLoad(trailMapIn, rightSensor, 0);
|
||||
let sourceForwardSample = textureLoad(sourceMap, forwardSensor, 0);
|
||||
let sourceLeftSample = textureLoad(sourceMap, leftSensor, 0);
|
||||
let sourceRightSample = textureLoad(sourceMap, rightSensor, 0);
|
||||
|
||||
var weightForward = brushWeight * trailForward.a;
|
||||
var weightLeft = brushWeight * trailLeft.a;
|
||||
var weightRight = brushWeight * trailRight.a;
|
||||
let channelMask = get_channel_mask(agent.colorIndex);
|
||||
let friendForward = dot(trailForward.rgb, channelMask);
|
||||
let friendLeft = dot(trailLeft.rgb, channelMask);
|
||||
let friendRight = dot(trailRight.rgb, channelMask);
|
||||
|
||||
let agression = mix(settings.currentGenerationAggression, settings.nextGenerationAggression, isFromNextGeneration) + weightForward;
|
||||
let sourceForward = dot(sourceForwardSample.rgb, channelMask);
|
||||
let sourceLeft = dot(sourceLeftSample.rgb, channelMask);
|
||||
let sourceRight = dot(sourceRightSample.rgb, channelMask);
|
||||
|
||||
weightForward += mix(trailForward.r + agression * trailForward.g, trailForward.g + agression * trailForward.r, isFromOddGeneration);
|
||||
weightLeft += mix(trailLeft.r + agression * trailLeft.g, trailLeft.g + agression * trailLeft.r, isFromOddGeneration);
|
||||
weightRight += mix(trailRight.r + agression * trailRight.g, trailRight.g + agression * trailRight.r, isFromOddGeneration);
|
||||
|
||||
var rotation: f32;
|
||||
let weightForward = friendForward + sourceForward * 24.0;
|
||||
let weightLeft = friendLeft + sourceLeft * 24.0;
|
||||
let weightRight = friendRight + sourceRight * 24.0;
|
||||
|
||||
var rotation = (random.r - 0.5) * settings.turnWhenLost;
|
||||
if weightForward >= weightLeft && weightForward >= weightRight {
|
||||
rotation = 0;
|
||||
rotation = rotation * 0.25;
|
||||
} else {
|
||||
rotation = sign(weightLeft - weightRight) * settings.turnRate;
|
||||
rotation += sign(weightLeft - weightRight) * settings.turnRate;
|
||||
}
|
||||
|
||||
let nextPosition = clamp(
|
||||
agent.position + vec2(cos(agent.angle), sin(agent.angle)) * moveRate,
|
||||
vec2<f32>(0, 0),
|
||||
state.size
|
||||
);
|
||||
if nextPosition.x == 0 || nextPosition.x == state.size.x || nextPosition.y == 0 || nextPosition.y == state.size.y {
|
||||
rotation = 3.14159265359 + random.a - 0.5;
|
||||
let sourceAtAgent = textureLoad(sourceMap, vec2<i32>(agent.position), 0);
|
||||
let sourceAtAgentStrength = clamp(dot(sourceAtAgent.rgb, channelMask), 0.0, 1.0);
|
||||
var moveRate = settings.moveRate * mix(1.0, 0.08, sourceAtAgentStrength);
|
||||
var introTargetOffset = vec2<f32>(0.0, 0.0);
|
||||
var introTargetDistance = 0.0;
|
||||
|
||||
if hasIntroTarget {
|
||||
introTargetOffset = agent.targetPosition - agent.position;
|
||||
introTargetDistance = length(introTargetOffset);
|
||||
let targetAngle = atan2(introTargetOffset.y, introTargetOffset.x);
|
||||
let nearTitle = 1.0 - smoothstep(4.0, max(28.0, settings.sensorOffset * 0.75), introTargetDistance);
|
||||
let desiredAngle = mix(targetAngle, agent.targetAngle, nearTitle * 0.2);
|
||||
let introTurn = angle_delta(agent.angle, desiredAngle);
|
||||
|
||||
rotation = clamp(introTurn, -settings.turnRate * 3.4, settings.turnRate * 3.4)
|
||||
+ (random.g - 0.5) * settings.turnWhenLost * 0.18;
|
||||
moveRate = min(settings.moveRate * mix(2.65, 0.01, nearTitle), introTargetDistance);
|
||||
}
|
||||
|
||||
var trail = vec4<f32>(settings.individualTrailWeight, 0, 0, 0);
|
||||
if isFromOddGeneration == 1.0 {
|
||||
trail = vec4<f32>(0, settings.individualTrailWeight, 0, 0);
|
||||
}
|
||||
|
||||
var trailBelow = textureLoad(trailMapIn, vec2<i32>(nextPosition), 0);
|
||||
|
||||
agent.angle += rotation;
|
||||
trailBelow += trail;
|
||||
|
||||
if settings.radius > 0 && length(settings.center - agent.position) < settings.radius {
|
||||
agent.generation = settings.isNextGenerationOdd;
|
||||
|
||||
// clear trail map below so the agent won't die immediately
|
||||
// trailBelow.r = (1 - settings.isNextGenerationOdd) * (trailBelow.r + trailBelow.g);
|
||||
// trailBelow.g = settings.isNextGenerationOdd * (trailBelow.r + trailBelow.g);
|
||||
} else {
|
||||
let relativeWeight = mix(trailBelow.g - trailBelow.r, trailBelow.r - trailBelow.g, isFromOddGeneration);
|
||||
if (relativeWeight > 0 && (
|
||||
(isFromCurrentGeneration == 1.0 && trailBelow.a == 0 && random.b < settings.infectionProbability)
|
||||
|| (isFromCurrentGeneration == 0.0 && trailBelow.a > 0)
|
||||
)) || (trailBelow.a > 0 && isFromCurrentGeneration == 0.0){
|
||||
// trailBelow.r = isFromOddGeneration * (trailBelow.r + trailBelow.g);
|
||||
// trailBelow.g = (1 - isFromOddGeneration) * (trailBelow.r + trailBelow.g);
|
||||
agent.generation = (agent.generation + 1) % 2;
|
||||
var step = vec2(cos(agent.angle), sin(agent.angle)) * moveRate;
|
||||
if hasIntroTarget {
|
||||
step = vec2<f32>(0.0, 0.0);
|
||||
if introTargetDistance > 0.5 {
|
||||
step = introTargetOffset / introTargetDistance * moveRate;
|
||||
}
|
||||
}
|
||||
|
||||
textureStore(trailMapOut, vec2<i32>(nextPosition), trailBelow);
|
||||
let maxPosition = state.size - vec2<f32>(1.0, 1.0);
|
||||
let nextPosition = clamp(agent.position + step, vec2<f32>(0, 0), maxPosition);
|
||||
if nextPosition.x == 0 || nextPosition.x == maxPosition.x || nextPosition.y == 0 || nextPosition.y == maxPosition.y {
|
||||
rotation = 3.14159265359 + random.a - 0.5;
|
||||
}
|
||||
|
||||
let sourceBelow = textureLoad(sourceMap, vec2<i32>(nextPosition), 0);
|
||||
let sourceBelowStrength = dot(sourceBelow.rgb, channelMask);
|
||||
let trailWeight = settings.individualTrailWeight * (1.0 + sourceBelowStrength * 16.0);
|
||||
var trailBelow = textureLoad(trailMapIn, vec2<i32>(nextPosition), 0);
|
||||
trailBelow = vec4<f32>(
|
||||
trailBelow.rgb + channelMask * trailWeight,
|
||||
max(trailBelow.a, 0.0)
|
||||
);
|
||||
|
||||
agent.angle += rotation;
|
||||
agent.position = nextPosition;
|
||||
|
||||
textureStore(trailMapOut, vec2<i32>(nextPosition), trailBelow);
|
||||
agents[id] = agent;
|
||||
}
|
||||
|
||||
fn sense(agentPosition: vec2<f32>, agentAngle: f32, sensorOffset: f32, sensorOffsetAngle: f32) -> vec4<f32> {
|
||||
fn sensor_position(agentPosition: vec2<f32>, agentAngle: f32, sensorOffset: f32, sensorOffsetAngle: f32) -> vec2<i32> {
|
||||
let sensorAngle = agentAngle + sensorOffsetAngle;
|
||||
let sensorPosition = vec2<i32>(agentPosition + vec2(cos(sensorAngle), sin(sensorAngle)) * sensorOffset);
|
||||
return textureLoad(trailMapIn, sensorPosition, 0);
|
||||
return vec2<i32>(clamp(
|
||||
agentPosition + vec2(cos(sensorAngle), sin(sensorAngle)) * sensorOffset,
|
||||
vec2<f32>(0, 0),
|
||||
state.size - vec2<f32>(1, 1)
|
||||
));
|
||||
}
|
||||
|
||||
fn get_channel_mask(colorIndex: f32) -> vec3<f32> {
|
||||
if colorIndex < 0.5 {
|
||||
return vec3<f32>(1, 0, 0);
|
||||
}
|
||||
if colorIndex < 1.5 {
|
||||
return vec3<f32>(0, 1, 0);
|
||||
}
|
||||
return vec3<f32>(0, 0, 1);
|
||||
}
|
||||
|
||||
fn angle_delta(sourceAngle: f32, targetAngle: f32) -> f32 {
|
||||
return atan2(sin(targetAngle - sourceAngle), cos(targetAngle - sourceAngle));
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue