Refactor & improve

This commit is contained in:
Andras Schmelczer 2023-05-01 12:14:36 +01:00
commit b3d9229af5
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
22 changed files with 713 additions and 334 deletions

View file

@ -1,31 +1,39 @@
import random from '../../utils/graphics/random.wgsl';
import { smartCompile } from '../../utils/graphics/smart-compile';
import { CommonParameters } from '../common-parameters';
import { CommonState } from '../common-state/common-state';
import { AGENT_SIZE_IN_BYTES, Agent } from './agent';
import { AgentSettings } from './agent-settings';
import shader from './agent.wgsl';
export class AgentPipeline {
private static readonly WORKGROUP_SIZE = 64;
private static readonly UNIFORM_COUNT = 10;
private static readonly UNIFORM_COUNT = 5;
private readonly bindGroupLayout: GPUBindGroupLayout;
private readonly pipeline: GPUComputePipeline;
private readonly uniforms: GPUBuffer;
private readonly agentsBuffer: GPUBuffer;
private bindGroup?: GPUBindGroup;
private previousTrailMapIn?: GPUTexture;
private previousTrailMapOut?: GPUTexture;
private previousTrailMapIn?: GPUTextureView;
private previousTrailMapOut?: GPUTextureView;
public constructor(private readonly device: GPUDevice, agents: Array<Agent>) {
public constructor(
private readonly device: GPUDevice,
agents: Array<Agent>,
private readonly commonState: CommonState
) {
if (agents.length === 0) {
throw new Error('No agents provided');
}
this.bindGroupLayout = device.createBindGroupLayout(AgentPipeline.bindGroupLayout);
this.pipeline = device.createComputePipeline({
layout: 'auto',
layout: device.createPipelineLayout({
bindGroupLayouts: [commonState.bindGroupLayout, this.bindGroupLayout],
}),
compute: {
module: smartCompile(device, random, shader),
module: smartCompile(device, CommonState.shaderCode, shader),
entryPoint: 'main',
},
});
@ -55,42 +63,36 @@ export class AgentPipeline {
}
public setParameters({
canvasSize,
deltaTime,
time,
brushTrailWeight,
moveSpeed,
turnSpeed,
sensorAngleDegrees,
sensorOffsetDst,
}: CommonParameters & AgentSettings) {
}: AgentSettings) {
this.device.queue.writeBuffer(
this.uniforms,
0,
new Float32Array([
canvasSize[0],
canvasSize[1],
deltaTime,
time,
brushTrailWeight,
moveSpeed * deltaTime,
turnSpeed * deltaTime,
moveSpeed,
turnSpeed,
(sensorAngleDegrees * Math.PI) / 180,
sensorOffsetDst,
])
);
}
public execute(
public executeRenderPass(
commandEncoder: GPUCommandEncoder,
trailMapIn: GPUTexture,
trailMapOut: GPUTexture
trailMapIn: GPUTextureView,
trailMapOut: GPUTextureView
) {
this.ensureBindGroupExists(trailMapIn, trailMapOut);
const passEncoder = commandEncoder.beginComputePass();
passEncoder.setPipeline(this.pipeline);
passEncoder.setBindGroup(0, this.bindGroup);
this.commonState.execute(passEncoder);
passEncoder.setBindGroup(1, this.bindGroup);
passEncoder.dispatchWorkgroups(
Math.ceil(
this.agentsBuffer.size / AGENT_SIZE_IN_BYTES / AgentPipeline.WORKGROUP_SIZE
@ -99,13 +101,32 @@ export class AgentPipeline {
passEncoder.end();
}
private ensureBindGroupExists(trailMapIn: GPUTexture, trailMapOut: GPUTexture) {
public execute(
commandEncoder: GPUCommandEncoder,
trailMapIn: GPUTextureView,
trailMapOut: GPUTextureView
) {
this.ensureBindGroupExists(trailMapIn, trailMapOut);
const passEncoder = commandEncoder.beginComputePass();
passEncoder.setPipeline(this.pipeline);
this.commonState.execute(passEncoder);
passEncoder.setBindGroup(1, this.bindGroup);
passEncoder.dispatchWorkgroups(
Math.ceil(
this.agentsBuffer.size / AGENT_SIZE_IN_BYTES / 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.pipeline.getBindGroupLayout(0),
layout: this.bindGroupLayout,
entries: [
{
binding: 0,
@ -121,11 +142,11 @@ export class AgentPipeline {
},
{
binding: 2,
resource: trailMapIn.createView(),
resource: trailMapIn,
},
{
binding: 3,
resource: trailMapOut.createView(),
resource: trailMapOut,
},
],
});
@ -139,4 +160,39 @@ export class AgentPipeline {
this.uniforms.destroy();
this.agentsBuffer.destroy();
}
private static get bindGroupLayout(): GPUBindGroupLayoutDescriptor {
return {
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: 'uniform',
},
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: 'storage',
},
},
{
binding: 2,
visibility: GPUShaderStage.COMPUTE,
texture: {
sampleType: 'float',
},
},
{
binding: 3,
visibility: GPUShaderStage.COMPUTE,
storageTexture: {
format: 'rgba16float',
},
},
],
};
}
}

View file

@ -6,10 +6,6 @@ struct Agent {
}
struct Settings {
size: vec2<f32>,
deltaTime: f32,
time: f32,
brushTrailWeight: f32,
moveRate: f32,
turnRate: f32,
@ -17,10 +13,10 @@ struct Settings {
sensorOffset: f32,
};
@group(0) @binding(0) var<uniform> settings: Settings;
@group(0) @binding(1) var<storage, read_write> agents: array<Agent>;
@group(0) @binding(2) var TrailMapIn: texture_2d<f32>;
@group(0) @binding(3) var TrailMapOut: texture_storage_2d<rgba16float, write>;
@group(1) @binding(0) var<uniform> settings: Settings;
@group(1) @binding(1) var<storage, read_write> agents: array<Agent>;
@group(1) @binding(2) var TrailMapIn: texture_2d<f32>;
@group(1) @binding(3) var TrailMapOut: texture_storage_2d<rgba16float, write>;
@compute @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
@ -34,17 +30,17 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
if (agent.timeToLive <= 0.) {
agent.position = vec2(
random_with_seed(agent.position, f32(id) + settings.time),
random_with_seed(agent.position, f32(id) + settings.time + 12),
random_with_seed(agent.position, f32(id) + state.time),
random_with_seed(agent.position, f32(id) + state.time + 12),
);
agent.angle = random_with_seed(vec2(agent.angle), f32(id) + settings.time);
agent.angle = random_with_seed(vec2(agent.angle), f32(id) + state.time);
agent.species = 1;
agent.timeToLive = 1000;
agents[id] = agent;
return;
}
let random = random_with_seed(agent.position, f32(id) + settings.time);
let random = random_with_seed(agent.position, f32(id) + state.time);
let trailCurrent = sense(agent, 0, 0);
var weight: f32;
@ -76,15 +72,15 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
}
if (weightForward < weightLeft && weightForward < weightRight) {
agent.angle += (random - 0.5) * 2. * settings.turnRate;
agent.angle += (random - 0.5) * 2. * settings.turnRate * state.deltaTime;
} else if (weightLeft < weightRight) {
agent.angle -= random * settings.turnRate;
agent.angle -= random * settings.turnRate * state.deltaTime;
} else if (weightRight < weightLeft) {
agent.angle += random * settings.turnRate;
agent.angle += random * settings.turnRate * state.deltaTime;
}
let direction = vec2(cos(agent.angle), sin(agent.angle));
var newPos = agent.position + direction / normalize(settings.size) * settings.moveRate;
var newPos = agent.position + direction / normalize(state.size) * settings.moveRate * state.deltaTime;
newPos = clamp(newPos, vec2<f32>(0, 0), vec2<f32>(1, 1));
if (newPos.x == 0. || newPos.x == 1. || newPos.y == 0. || newPos.y == 1.) {
agent.angle += 3.14159265359 + random - 0.5;
@ -94,19 +90,23 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
if (agent.species == 0) {
trail = vec4(1, 0, 0, 0);
}
textureStore(TrailMapOut, vec2<i32>(newPos * settings.size), trail);
textureStore(TrailMapOut, vec2<i32>(newPos * state.size), trail);
agent.position = newPos;
agent.timeToLive -= settings.deltaTime;
agent.timeToLive -= state.deltaTime;
agents[id] = agent;
}
fn sense(agent: Agent, sensorOffset: f32, sensorOffsetAngle: f32) -> vec4<f32> {
let sensorAngle = agent.angle + sensorOffsetAngle;
let sensorDir: vec2<f32> = vec2(cos(sensorAngle), sin(sensorAngle)) / normalize(settings.size);
let sensorDir: vec2<f32> = vec2(cos(sensorAngle), sin(sensorAngle)) / normalize(state.size);
let sensorPos: vec2<f32> = agent.position + sensorDir * sensorOffset;
return textureLoad(TrailMapIn, vec2<i32>(sensorPos * settings.size), 0);
return textureLoad(TrailMapIn, vec2<i32>(sensorPos * state.size), 0);
}
fn random_with_seed(uv: vec2<f32>, seed: f32) -> f32 {
return fract(sin(dot(uv, vec2(12.9898 + seed, 78.233 + seed)))* 43758.5453123 + seed);
}