Added NodeJS Demo.
This commit is contained in:
98
demos/Graphics/GpuWorker.js
Normal file
98
demos/Graphics/GpuWorker.js
Normal file
@@ -0,0 +1,98 @@
|
||||
// worker.js
|
||||
|
||||
|
||||
import { ParticleSimulation } from "./demo.js";
|
||||
|
||||
|
||||
var particleSimulation = new ParticleSimulation();
|
||||
|
||||
export class Controller {
|
||||
|
||||
setup( request ) {
|
||||
|
||||
var canvas = request.canvas;
|
||||
|
||||
console.log( canvas );
|
||||
|
||||
particleSimulation.setup( canvas, request.width, request.height );
|
||||
|
||||
//self.postMessage({ type: "pong", id: request.id });
|
||||
}
|
||||
|
||||
resetParticlePositions() {
|
||||
|
||||
particleSimulation.resetParticlePositions();
|
||||
|
||||
}
|
||||
|
||||
mousemove( request ) {
|
||||
|
||||
particleSimulation.eventManager.mousemove( request );
|
||||
|
||||
}
|
||||
|
||||
mousedown( request ) {
|
||||
|
||||
console.log("onMouseDown");
|
||||
|
||||
particleSimulation.eventManager.mousedown( request );
|
||||
|
||||
}
|
||||
|
||||
mouseup( request ) {
|
||||
|
||||
particleSimulation.eventManager.mouseup( request );
|
||||
|
||||
}
|
||||
|
||||
mouseleave( request ) {
|
||||
|
||||
particleSimulation.eventManager.mouseleave( request );
|
||||
|
||||
}
|
||||
|
||||
wheel( request ) {
|
||||
|
||||
particleSimulation.eventManager.wheel( request );
|
||||
|
||||
}
|
||||
|
||||
resize( request ) {
|
||||
|
||||
particleSimulation.eventManager.resize( request );
|
||||
|
||||
}
|
||||
|
||||
resetParticlePositions() {
|
||||
|
||||
particleSimulation.resetParticlePositions( );
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
const controller = new Controller();
|
||||
|
||||
self.onmessage = function (event) {
|
||||
|
||||
const data = event.data;
|
||||
|
||||
if (typeof data !== "object" || typeof data.method !== "string") {
|
||||
console.warn("Invalid request received:", data);
|
||||
return;
|
||||
}
|
||||
|
||||
// Optional: wrap the data into a Request instance (if you need its methods)
|
||||
// const request = new Request(data.method, data.payload);
|
||||
|
||||
// Or just use plain data object
|
||||
const request = data;
|
||||
|
||||
const methodName = request.method;
|
||||
|
||||
if (typeof controller[methodName] !== "function") {
|
||||
console.warn("No method found for:", request.method);
|
||||
return;
|
||||
}
|
||||
|
||||
controller[methodName](request);
|
||||
};
|
||||
544
demos/Graphics/demo.js
Normal file
544
demos/Graphics/demo.js
Normal file
@@ -0,0 +1,544 @@
|
||||
|
||||
import Shader from "../../framework/WebGpu.js"
|
||||
|
||||
import Matrix4 from "../../framework/Matrix4.js"
|
||||
|
||||
import Vector3 from "../../framework/Vector3.js"
|
||||
|
||||
import Camera from "../../framework/Camera.js";
|
||||
|
||||
import EventManager from "../../framework/eventManager.js";
|
||||
|
||||
import ShaderInpector from "../../framework/ShaderInpector.js";
|
||||
|
||||
|
||||
export class ParticleSimulation {
|
||||
|
||||
canvas;
|
||||
|
||||
device;
|
||||
|
||||
camera;
|
||||
|
||||
useLocalSort = true;
|
||||
|
||||
eventManager = new EventManager();
|
||||
|
||||
frameCount = 0;
|
||||
|
||||
setCanvas( canvas ) {
|
||||
|
||||
this.canvas = canvas;
|
||||
|
||||
this.eventManager.setCanvas( canvas );
|
||||
|
||||
}
|
||||
|
||||
async setup( offscreenCanvas, width, height ) {
|
||||
|
||||
offscreenCanvas.width = width;
|
||||
|
||||
offscreenCanvas.height = height;
|
||||
|
||||
this.canvas = offscreenCanvas;
|
||||
|
||||
//console.log( this.canvas.width, this.canvas.height );
|
||||
|
||||
const context = offscreenCanvas.getContext("webgpu");
|
||||
|
||||
|
||||
|
||||
|
||||
this.camera = new Camera( [0, 0, 5], [0, -.3, 0], [0, 1, 0] );
|
||||
|
||||
this.eventManager.setup( offscreenCanvas, this.camera );
|
||||
|
||||
//this.eventManager.registerEventListenersNode();
|
||||
|
||||
const adapter = await self.navigator.gpu.requestAdapter();
|
||||
|
||||
if ( !adapter ) {
|
||||
|
||||
throw new Error("Failed to get GPU adapter");
|
||||
|
||||
}
|
||||
|
||||
this.device = await adapter.requestDevice();
|
||||
|
||||
this.particleCount = 8192 * 2;
|
||||
|
||||
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
|
||||
|
||||
context.configure({
|
||||
device: this.device,
|
||||
format: presentationFormat,
|
||||
alphaMode: "opaque"
|
||||
});
|
||||
|
||||
let boundsMinimum = new Vector3( -2, -2, -2 );
|
||||
|
||||
let boundsMaximum = new Vector3( 2, 2, 2 );
|
||||
|
||||
let cellsPerDimension = 12;
|
||||
|
||||
let gravity = -2.3;
|
||||
|
||||
this.workgroupSize = 64;
|
||||
|
||||
this.numWorkgroups = Math.ceil( this.particleCount / this.workgroupSize );
|
||||
|
||||
|
||||
var jArray = new Array();
|
||||
|
||||
var kArray = new Array();
|
||||
|
||||
if( this.useLocalSort ) {
|
||||
|
||||
var startK = this.workgroupSize * 2; // 2 * 256; 256 = this.workgroupSize
|
||||
|
||||
} else {
|
||||
|
||||
var startK = 2;
|
||||
|
||||
}
|
||||
|
||||
for (let k = startK; k <= this.particleCount; k <<= 1 ) {
|
||||
|
||||
for (let j = k >> 1; j > 0; j >>= 1 ) {
|
||||
|
||||
jArray.push( j );
|
||||
|
||||
kArray.push( k );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
this.gravityShader = new Shader( this.device );
|
||||
|
||||
await this.gravityShader.setup( "../../shaders/gravity.wgsl" );
|
||||
|
||||
this.gravityShader.setVariable("gravity", gravity );
|
||||
|
||||
this.gravityShader.setVariable("updateDistancesAndIndices", 1);
|
||||
|
||||
|
||||
this.resetParticlePositions();
|
||||
|
||||
|
||||
this.copyIndicesShader = new Shader( this.device );
|
||||
|
||||
await this.copyIndicesShader.setup( "../../shaders/copyBuffer.wgsl" );
|
||||
|
||||
|
||||
this.renderShader = new Shader( this.device );
|
||||
|
||||
|
||||
this.renderShader.setCanvas( this.canvas );
|
||||
|
||||
await this.renderShader.setup("../../shaders/points.wgsl");
|
||||
|
||||
|
||||
|
||||
const quadOffsets = new Float32Array( [
|
||||
// Triangle 1
|
||||
-1, -1, // bottom-left
|
||||
1, -1, // bottom-right
|
||||
1, 1, // top-right
|
||||
|
||||
// Triangle 2
|
||||
-1, -1, // bottom-left
|
||||
1, 1, // top-right
|
||||
-1, 1 // top-left
|
||||
]);
|
||||
|
||||
this.renderShader.setAttribute( "quadOffset", quadOffsets );
|
||||
|
||||
|
||||
this.findGridHashShader = new Shader( this.device );
|
||||
|
||||
await this.findGridHashShader.setup( "../../shaders/findGridHash.wgsl" );
|
||||
|
||||
//console.log("this.gravityShader.getBuffer(\"positions\")", this.gravityShader.getBuffer("positions"));
|
||||
|
||||
this.findGridHashShader.setBuffer( "positions", this.gravityShader.getBuffer("positions") );
|
||||
|
||||
this.findGridHashShader.setVariable( "cellCount", cellsPerDimension );
|
||||
|
||||
this.findGridHashShader.setVariable( "gridMin", boundsMinimum );
|
||||
|
||||
this.findGridHashShader.setVariable( "gridMax", boundsMaximum );
|
||||
|
||||
|
||||
if( this.useLocalSort ) {
|
||||
|
||||
this.localSortShader = new Shader( this.device );
|
||||
|
||||
await this.localSortShader.setup( "../../shaders/localSort.wgsl" );
|
||||
|
||||
this.localSortShader.setBuffer( "gridHashes", this.findGridHashShader.getBuffer("gridHashes" ) );
|
||||
|
||||
this.localSortShader.setBuffer( "indices", this.findGridHashShader.getBuffer("indices" ) );
|
||||
|
||||
this.localSortShader.setVariable( "totalCount", this.particleCount );
|
||||
|
||||
}
|
||||
|
||||
this.bitonicSortGridHashShader = new Shader( this.device );
|
||||
|
||||
await this.bitonicSortGridHashShader.setup( "../../shaders/bitonicSortUIntMultiPass.wgsl" );
|
||||
|
||||
if( this.useLocalSort ) {
|
||||
|
||||
this.bitonicSortGridHashShader.setBuffer( "gridHashes", this.localSortShader.getBuffer("gridHashes") );
|
||||
|
||||
this.bitonicSortGridHashShader.setBuffer( "indices", this.localSortShader.getBuffer("indices") );
|
||||
|
||||
} else {
|
||||
|
||||
this.bitonicSortGridHashShader.setBuffer( "gridHashes", this.findGridHashShader.getBuffer("gridHashes" ) );
|
||||
|
||||
this.bitonicSortGridHashShader.setBuffer( "indices", this.findGridHashShader.getBuffer("indices") );
|
||||
|
||||
}
|
||||
|
||||
this.bitonicSortGridHashShader.setVariable( "totalCount", this.particleCount );
|
||||
|
||||
this.bitonicSortGridHashShader.setVariable( "jArray", jArray );
|
||||
|
||||
this.bitonicSortGridHashShader.setVariable( "kArray", kArray );
|
||||
|
||||
|
||||
this.findGridHashRangeShader = new Shader( this.device );
|
||||
|
||||
await this.findGridHashRangeShader.setup( "../../shaders/findGridHashRanges.wgsl" );
|
||||
|
||||
|
||||
this.collisionDetectionShader = new Shader( this.device );
|
||||
|
||||
await this.collisionDetectionShader.setup( "../../shaders/collisionDetection.wgsl" );
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "positions", this.gravityShader.getBuffer("positions" ) );
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "velocities", this.gravityShader.getBuffer("velocities") );
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "positions", this.gravityShader.getBuffer("positions" ) );
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "velocities", this.gravityShader.getBuffer("velocities") );
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "gridHashes", this.findGridHashShader.getBuffer("gridHashes") );
|
||||
|
||||
|
||||
if( this.useLocalSort ) {
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "hashSortedIndices", this.localSortShader.getBuffer("indices") );
|
||||
|
||||
} else {
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "hashSortedIndices", this.bitonicSortGridHashShader.getBuffer("indices") );
|
||||
|
||||
}
|
||||
|
||||
|
||||
this.collisionDetectionShader.setVariable( "cellCount", cellsPerDimension );
|
||||
|
||||
this.collisionDetectionShader.setVariable( "gridMin", boundsMinimum );
|
||||
|
||||
this.collisionDetectionShader.setVariable( "gridMax", boundsMaximum );
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "startIndices", this.findGridHashRangeShader.getBuffer("startIndices") );
|
||||
|
||||
this.collisionDetectionShader.setBuffer( "endIndices", this.findGridHashRangeShader.getBuffer("endIndices") );
|
||||
|
||||
this.collisionDetectionShader.setVariable( "collisionRadius", 0.06 );
|
||||
|
||||
|
||||
this.bitonicSortShader = new Shader(this.device, "../../shaders/bitonicSort.wgsl");
|
||||
|
||||
await this.bitonicSortShader.addStage("main", GPUShaderStage.COMPUTE );
|
||||
|
||||
|
||||
this.bitonicSortShader.setBuffer( "compare", this.gravityShader.getBuffer("distances") );
|
||||
|
||||
this.bitonicSortShader.setBuffer( "indices", this.gravityShader.getBuffer("indices") );
|
||||
|
||||
this.bitonicSortShader.setVariable( "totalCount", this.particleCount );
|
||||
|
||||
|
||||
this.findGridHashRangeShader.setBuffer( "gridHashes", this.bitonicSortGridHashShader.getBuffer("gridHashes") );
|
||||
|
||||
this.findGridHashRangeShader.setBuffer( "indices", this.bitonicSortGridHashShader.getBuffer("indices") );
|
||||
|
||||
this.findGridHashRangeShader.setVariable( "totalCount", this.particleCount );
|
||||
|
||||
|
||||
this.copyIndicesShader.setBuffer( "indices", this.bitonicSortShader.getBuffer("indices") );
|
||||
|
||||
|
||||
this.renderShader.setBuffer( "positions", this.gravityShader.getBuffer("positions") );
|
||||
|
||||
this.renderShader.setBuffer( "sortedIndices", this.copyIndicesShader.getBuffer("sortedIndices") );
|
||||
|
||||
this.renderShader.setCanvas( this.canvas );
|
||||
|
||||
//var simulation = new particleSimulation();
|
||||
|
||||
this.render();
|
||||
|
||||
|
||||
return;
|
||||
|
||||
//document.getElementById("resetParticlesButton").addEventListener("click", resetParticlePositions);
|
||||
|
||||
|
||||
}
|
||||
|
||||
resetParticlePositions() {
|
||||
|
||||
const positions = new Float32Array( this.particleCount * 3 );
|
||||
|
||||
const velocities = new Float32Array( this.particleCount * 3 );
|
||||
|
||||
|
||||
for (var i = 0; i < this.particleCount; i++) {
|
||||
|
||||
positions[ i * 3 + 0 ] = Math.random() * 2.0 - 1.0;
|
||||
|
||||
positions[ i * 3 + 1 ] = Math.random() * 2.0 - 1.0;
|
||||
|
||||
positions[ i * 3 + 2 ] = Math.random() * 2.0 - 1.0;
|
||||
|
||||
velocities[ i * 3 + 0 ] = 0;
|
||||
|
||||
velocities[ i * 3 + 1 ] = 0;
|
||||
|
||||
velocities[ i * 3 + 2 ] = 0;
|
||||
|
||||
}
|
||||
|
||||
this.gravityShader.setVariable("positions", positions);
|
||||
|
||||
this.gravityShader.setVariable("velocities", velocities);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
updateTimeDelta() {
|
||||
|
||||
const now = performance.now();
|
||||
|
||||
this.deltaTimeValue = ( now - this.lastFrameTime ) / 1000;
|
||||
|
||||
this.lastFrameTime = now;
|
||||
|
||||
}
|
||||
|
||||
async sortGridHash() {
|
||||
|
||||
const commandEncoder = this.device.createCommandEncoder();
|
||||
|
||||
// Local sort 256 items
|
||||
if( this.useLocalSort ) {
|
||||
|
||||
const passEncoder = commandEncoder.beginComputePass();
|
||||
|
||||
passEncoder.setPipeline( this.localSortShader.pipeline );
|
||||
|
||||
for ( const [ index, bindGroup ] of this.localSortShader.bindGroups.entries() ) {
|
||||
|
||||
passEncoder.setBindGroup( index, bindGroup );
|
||||
|
||||
}
|
||||
|
||||
passEncoder.dispatchWorkgroups( this.numWorkgroups );
|
||||
|
||||
passEncoder.end();
|
||||
|
||||
}
|
||||
|
||||
// Bitonic global merge
|
||||
{
|
||||
const threadPassIndices = new Uint32Array( this.particleCount );
|
||||
|
||||
for (var i = 0; i < this.particleCount; i++) {
|
||||
|
||||
threadPassIndices[0] = 0;
|
||||
|
||||
}
|
||||
|
||||
this.bitonicSortGridHashShader.setVariable("threadPassIndices", threadPassIndices);
|
||||
|
||||
const passEncoder = commandEncoder.beginComputePass();
|
||||
|
||||
passEncoder.setPipeline( this.bitonicSortGridHashShader.pipeline );
|
||||
|
||||
for ( const [ index, bindGroup ] of this.bitonicSortGridHashShader.bindGroups.entries() ) {
|
||||
|
||||
passEncoder.setBindGroup( index, bindGroup );
|
||||
|
||||
}
|
||||
|
||||
if( this.useLocalSort ) {
|
||||
|
||||
var startK = this.workgroupSize * 2;
|
||||
|
||||
} else {
|
||||
|
||||
var startK = 2;
|
||||
|
||||
}
|
||||
|
||||
for (let k = startK; k <= this.particleCount; k <<= 1 ) {
|
||||
|
||||
for (let j = k >> 1; j > 0; j >>= 1 ) {
|
||||
|
||||
passEncoder.dispatchWorkgroups( this.numWorkgroups );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
passEncoder.end();
|
||||
|
||||
}
|
||||
|
||||
const commandBuffer = commandEncoder.finish();
|
||||
|
||||
await this.device.queue.submit( [ commandBuffer ] );
|
||||
|
||||
await this.device.queue.onSubmittedWorkDone();
|
||||
|
||||
}
|
||||
|
||||
async sortDistance() {
|
||||
|
||||
await this.gravityShader.execute( this.numWorkgroups );
|
||||
|
||||
this.gravityShader.setVariable("updateDistancesAndIndices", 0);
|
||||
|
||||
for (let k = 2; k <= this.particleCount; k <<= 1) {
|
||||
|
||||
for (let j = k >> 1; j > 0; j >>= 1) {
|
||||
|
||||
const commandBuffers = new Array();
|
||||
|
||||
await this.bitonicSortShader.setVariable( "j", j ); // Must await uniform update
|
||||
await this.bitonicSortShader.setVariable( "k", k );
|
||||
|
||||
const commandEncoder = this.device.createCommandEncoder();
|
||||
|
||||
const passEncoder = commandEncoder.beginComputePass();
|
||||
|
||||
passEncoder.setPipeline( this.bitonicSortShader.pipeline );
|
||||
|
||||
for ( const [ index, bindGroup ] of this.bitonicSortShader.bindGroups.entries() ) {
|
||||
|
||||
passEncoder.setBindGroup( index, bindGroup );
|
||||
|
||||
}
|
||||
|
||||
passEncoder.dispatchWorkgroups( this.numWorkgroups );
|
||||
|
||||
passEncoder.end();
|
||||
|
||||
commandBuffers.push( commandEncoder.finish() );
|
||||
|
||||
this.device.queue.submit( commandBuffers );
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
this.gravityShader.setVariable( "updateDistancesAndIndices", 1 );
|
||||
|
||||
await this.copyIndicesShader.execute( this.numWorkgroups );
|
||||
|
||||
}
|
||||
|
||||
async findStartEndIndices( logBuffers ) {
|
||||
|
||||
await this.gravityShader.execute( this.numWorkgroups );
|
||||
|
||||
await this.gravityShader.setVariable("updateDistancesAndIndices", 0);
|
||||
|
||||
await this.findGridHashShader.execute( this.numWorkgroups );
|
||||
|
||||
await this.sortGridHash();
|
||||
|
||||
await this.findGridHashRangeShader.execute( this.workgroupSize );
|
||||
|
||||
if( logBuffers ) {
|
||||
|
||||
await this.bitonicSortGridHashShader.debugBuffer("indices");
|
||||
|
||||
await this.bitonicSortGridHashShader.debugBuffer("gridHashes");
|
||||
|
||||
await this.findGridHashRangeShader.debugBuffer("startIndices");
|
||||
|
||||
await this.findGridHashRangeShader.debugBuffer("endIndices");
|
||||
}
|
||||
|
||||
await this.gravityShader.setVariable("updateDistancesAndIndices", 1);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
async render() {
|
||||
|
||||
this.updateTimeDelta();
|
||||
|
||||
const viewMatrixData = this.camera.getViewMatrix();
|
||||
|
||||
const projectionMatrixData = Matrix4.createProjectionMatrix( this.camera, this.canvas )
|
||||
|
||||
const viewProjectionMatrix = Matrix4.multiply( projectionMatrixData, viewMatrixData );
|
||||
|
||||
const cameraWorldMatrix = Matrix4.invert( viewMatrixData );
|
||||
|
||||
const cameraRight = Matrix4.getColumn( cameraWorldMatrix, 0 );
|
||||
|
||||
const cameraUp = Matrix4.getColumn( cameraWorldMatrix, 1 );
|
||||
|
||||
const cameraPosition = Matrix4.getColumn( cameraWorldMatrix, 3 );
|
||||
|
||||
|
||||
this.gravityShader.execute( this.numWorkgroups );
|
||||
|
||||
this.gravityShader.setVariable( "cameraPosition", cameraPosition );
|
||||
|
||||
this.gravityShader.setVariable( "deltaTimeSeconds", this.deltaTimeValue );
|
||||
|
||||
if ( this.frameCount % 20 === 0 ) {
|
||||
|
||||
this.sortDistance();
|
||||
|
||||
}
|
||||
|
||||
this.renderShader.setVariable( "viewProjectionMatrix", viewProjectionMatrix );
|
||||
|
||||
this.renderShader.setVariable( "cameraRight", cameraRight );
|
||||
|
||||
this.renderShader.setVariable( "cameraUp", cameraUp );
|
||||
|
||||
this.renderShader.renderToCanvas( 6, this.particleCount, 0 );
|
||||
|
||||
|
||||
this.frameCount++;
|
||||
|
||||
if ( this.frameCount % 6 === 0 ) {
|
||||
|
||||
this.findStartEndIndices();
|
||||
|
||||
}
|
||||
|
||||
this.collisionDetectionShader.setVariable( "deltaTimeSeconds", this.deltaTimeValue );
|
||||
|
||||
this.collisionDetectionShader.execute( this.numWorkgroups );
|
||||
|
||||
requestAnimationFrame( this.render.bind( this ) );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
171
demos/Graphics/index.html
Normal file
171
demos/Graphics/index.html
Normal file
@@ -0,0 +1,171 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>10.000 Gpu Sphere Collision Demo.</title>
|
||||
</head>
|
||||
<base href="Graphics/" />
|
||||
<link rel="stylesheet" href="./style/main.css" >
|
||||
|
||||
<script type="module">
|
||||
|
||||
import { ParticleSimulation } from "./demo.js";
|
||||
|
||||
|
||||
var particleSimulation = new ParticleSimulation();
|
||||
|
||||
|
||||
var useWebWorker = false;
|
||||
|
||||
const canvas = document.querySelector(".mainCanvas");
|
||||
|
||||
particleSimulation.setCanvas( canvas );
|
||||
|
||||
resizeCanvasToDisplaySize( canvas );
|
||||
|
||||
|
||||
var worker;
|
||||
|
||||
if ( !useWebWorker ) {
|
||||
|
||||
|
||||
|
||||
await particleSimulation.setup( canvas, canvas.width, canvas.height, true );
|
||||
|
||||
console.log("document.bufferMap", document.bufferMap);
|
||||
|
||||
} else if ( useWebWorker ) {
|
||||
|
||||
worker = new Worker("./GpuWorker.js", { type: "module" });
|
||||
|
||||
worker.onmessage = function ( event ) {
|
||||
|
||||
console.log("From worker:", event.data);
|
||||
|
||||
};
|
||||
|
||||
const offscreen = canvas.transferControlToOffscreen();
|
||||
|
||||
worker.addEventListener("error", function ( event ) {
|
||||
|
||||
console.error( "Worker failed:",
|
||||
event.message, "at",
|
||||
event.filename + ":" +
|
||||
event.lineno + ":" +
|
||||
event.colno );
|
||||
|
||||
});
|
||||
|
||||
var request = {
|
||||
method: "setup",
|
||||
canvas: offscreen,
|
||||
width: canvas.width,
|
||||
height: canvas.height
|
||||
};
|
||||
|
||||
worker.postMessage( request, [offscreen] );
|
||||
|
||||
}
|
||||
|
||||
|
||||
var events = new Array( "mousemove", "mousedown", "mouseup", "onwheel", "wheel" );
|
||||
|
||||
for ( var i = 0; i < events.length; i++ ) {
|
||||
|
||||
let eventName = events[i];
|
||||
|
||||
console.log("createEvent", eventName);
|
||||
|
||||
canvas.addEventListener( eventName, function ( event ) {
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
|
||||
const x = event.clientX - rect.left;
|
||||
|
||||
const y = event.clientY - rect.top;
|
||||
|
||||
var request = {
|
||||
method: eventName,
|
||||
clientX: x,
|
||||
clientY: y,
|
||||
deltaY: event.deltaY
|
||||
};
|
||||
|
||||
if ( useWebWorker ) {
|
||||
|
||||
worker.postMessage( request );
|
||||
|
||||
} else {
|
||||
|
||||
particleSimulation.eventManager[ eventName ]( request );
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
document.querySelector("#resetParticlesButton").addEventListener("click", function () {
|
||||
|
||||
var request = {
|
||||
method: "resetParticlePositions"
|
||||
};
|
||||
|
||||
if ( useWebWorker ) {
|
||||
|
||||
worker.postMessage( request );
|
||||
|
||||
} else {
|
||||
|
||||
particleSimulation.resetParticlePositions();
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
function resizeCanvasToDisplaySize( canvas ) {
|
||||
|
||||
const width = window.innerWidth;
|
||||
const height = window.innerHeight;
|
||||
|
||||
var request = {
|
||||
method: "resize",
|
||||
width: width,
|
||||
height: height
|
||||
};
|
||||
|
||||
if ( useWebWorker ) {
|
||||
|
||||
worker.postMessage( request );
|
||||
|
||||
} else {
|
||||
|
||||
particleSimulation.eventManager.resize( request );
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
window.addEventListener( "resize", function () {
|
||||
|
||||
resizeCanvasToDisplaySize( canvas );
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<body>
|
||||
<div id="controlPanel">
|
||||
<div class="inputRow">
|
||||
<button id="resetParticlesButton">Reset Spheres</button>
|
||||
</div>
|
||||
</div>
|
||||
<canvas class="mainCanvas" width="1000" height="1000"></canvas>
|
||||
</body>
|
||||
</html>
|
||||
114
demos/Graphics/style/main.css
Normal file
114
demos/Graphics/style/main.css
Normal file
@@ -0,0 +1,114 @@
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background:#111111;
|
||||
}
|
||||
|
||||
canvas {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
display: block;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
#controlPanel {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
left: 10px;
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 20px;
|
||||
background: rgba(30, 30, 30, 0.6);
|
||||
backdrop-filter: blur(18px);
|
||||
-webkit-backdrop-filter: blur(18px);
|
||||
border-radius: 14px;
|
||||
box-shadow:
|
||||
0 4px 12px rgba(0, 0, 0, 0.5),
|
||||
0 0 0 1px rgba(255, 255, 255, 0.05);
|
||||
z-index: 1000;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.inputRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.inputRow label {
|
||||
color: #ccc;
|
||||
font-size: 14px;
|
||||
white-space: nowrap;
|
||||
width: 70px;
|
||||
}
|
||||
|
||||
.inputRow button,
|
||||
.inputRow input {
|
||||
flex-grow: 1;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #f0f0f5;
|
||||
background: rgba(28, 28, 30, 0.9);
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
cursor: pointer;
|
||||
box-shadow:
|
||||
0 1px 3px rgba(0, 0, 0, 0.4),
|
||||
0 0 6px rgba(28, 28, 30, 0.5);
|
||||
transition: background-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.inputRow button:hover {
|
||||
background: rgba(40, 40, 44, 0.95);
|
||||
}
|
||||
|
||||
.inputRow input {
|
||||
background: rgba(20, 20, 20, 0.8);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
outline: none;
|
||||
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
.inputRow select {
|
||||
flex-grow: 1;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #f0f0f5;
|
||||
background: rgba(28, 28, 30, 0.9);
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
cursor: pointer;
|
||||
box-shadow:
|
||||
0 1px 3px rgba(0, 0, 0, 0.4),
|
||||
0 0 6px rgba(28, 28, 30, 0.5);
|
||||
transition: background-color 0.2s ease, box-shadow 0.2s ease;
|
||||
appearance: none; /* Remove default arrow */
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
background-image:
|
||||
linear-gradient(45deg, transparent 50%, #f0f0f5 50%),
|
||||
linear-gradient(135deg, #f0f0f5 50%, transparent 50%);
|
||||
background-position:
|
||||
calc(100% - 20px) calc(50% - 3px),
|
||||
calc(100% - 15px) calc(50% - 3px);
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
.inputRow select:hover {
|
||||
background: rgba(40, 40, 44, 0.95);
|
||||
}
|
||||
|
||||
.inputRow option {
|
||||
background: rgba(28, 28, 30, 0.95);
|
||||
color: #f0f0f5;
|
||||
}
|
||||
114
demos/Graphics/webgpu_framework.md
Normal file
114
demos/Graphics/webgpu_framework.md
Normal file
@@ -0,0 +1,114 @@
|
||||
# Simplifying WebGPU with This Framework
|
||||
|
||||
WebGPU’s native API is complex and verbose. This framework reduces that complexity by providing simple classes and methods to manage shaders, buffers, and execution. Instead of handling low-level GPU commands, you focus on your logic.
|
||||
|
||||
## 1. Loading and Using a Shader
|
||||
|
||||
**Without Framework:**
|
||||
|
||||
```
|
||||
Manual setup of device, pipeline, bind groups, etc. Very verbose and error-prone
|
||||
const shaderModule = device.createShaderModule({ code: wgslSource });
|
||||
const pipeline = device.createComputePipeline({ ... });
|
||||
// Setup bind groups and command encoder manually
|
||||
```
|
||||
|
||||
**With Framework:**
|
||||
|
||||
```
|
||||
const shader = new Shader( "myComputeShader.wgsl" );
|
||||
|
||||
await shader.compile();
|
||||
|
||||
shader.setVariable( "someUniform", 42 );
|
||||
|
||||
shader.execute( 64 ); // runs compute with 64 workgroups
|
||||
```
|
||||
|
||||
The framework loads, compiles, sets uniforms, and dispatches the compute shader with simple method calls.
|
||||
|
||||
## 2. Setting Buffers
|
||||
|
||||
**Without Framework:**
|
||||
|
||||
```
|
||||
Create GPU buffer, write data, create bind group manually
|
||||
```
|
||||
|
||||
**With Framework:**
|
||||
|
||||
```
|
||||
const dataBuffer = gpu.createBuffer( new Float32Array([1, 2, 3]) );
|
||||
|
||||
shader.setBuffer( "inputBuffer", dataBuffer );
|
||||
```
|
||||
|
||||
Buffers are bound by name with a simple call.
|
||||
|
||||
## 3. Rendering to Canvas
|
||||
|
||||
**Without Framework:**
|
||||
|
||||
```
|
||||
Create render pipeline, set vertex buffers, encode commands manually
|
||||
```
|
||||
|
||||
**With Framework:**
|
||||
|
||||
```
|
||||
shader.setCanvas( canvasElement );
|
||||
|
||||
shader.setAttributes( vertexData );
|
||||
|
||||
shader.execute();
|
||||
```
|
||||
|
||||
The framework handles pipeline creation, drawing commands, and presentation automatically.
|
||||
|
||||
## 4. Camera and Matrix Utilities
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
const camera = new Camera();
|
||||
|
||||
camera.position.set( 0, 1, 5 );
|
||||
|
||||
camera.updateViewMatrix();
|
||||
|
||||
shader.setVariable( "viewMatrix", camera.viewMatrix );
|
||||
```
|
||||
|
||||
The framework provides built-in classes for common math tasks.
|
||||
|
||||
## 5. Event Handling
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
const events = new EventManager( canvasElement );
|
||||
|
||||
events.on( "mouseMove", (event) => {
|
||||
camera.rotate( event.deltaX, event.deltaY );
|
||||
shader.setVariable( "viewMatrix", camera.viewMatrix );
|
||||
shader.execute();
|
||||
});
|
||||
```
|
||||
|
||||
Separates input handling cleanly from GPU logic.
|
||||
|
||||
## Summary Table
|
||||
|
||||
| Task | WebGPU Native API | This Framework |
|
||||
| --- | --- | --- |
|
||||
| Load and compile shader | Many steps, manual setup | One line with `new Shader()` + `compile()` |
|
||||
| Set uniforms | Define bind groups and layouts | Simple `setVariable()` calls |
|
||||
| Bind buffers | Manual buffer creation and binding | `setBuffer()` by name |
|
||||
| Execute compute | Command encoder and dispatch calls | `execute(workgroupCount)` method |
|
||||
| Render to canvas | Complex pipeline and draw calls | `setCanvas()`, `setAttributes()`, `execute()` |
|
||||
| Handle math and camera | External libs or manual math | Built-in Matrix4, Camera classes |
|
||||
| Input handling | Manual event listeners | `EventManager` handles input cleanly |
|
||||
|
||||
---
|
||||
|
||||
This framework hides the low-level complexity behind a clean, simple API that accelerates WebGPU development and makes GPU programming accessible and maintainable.
|
||||
Reference in New Issue
Block a user