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
Original file line number Diff line number Diff line change
Expand Up @@ -208,13 +208,9 @@ function resetDrawing() {
}
}

let disposed = false;
let animationFrameId: number;

function run() {
if (disposed) {
return;
}

const scale = canvas.width / SIZE;

context.clearRect(0, 0, canvas.width, canvas.height);
Expand Down Expand Up @@ -244,7 +240,7 @@ function run() {
context.fillStyle = '#000';
context.fillText('draw here 🖌️', canvas.width / 2, canvas.height / 2);
}
requestAnimationFrame(run);
animationFrameId = requestAnimationFrame(run);
}

document.querySelector('.loading')?.classList.add('loaded');
Expand Down Expand Up @@ -397,7 +393,7 @@ export const controls = defineControls({
});

export function onCleanup() {
disposed = true;
cancelAnimationFrame(animationFrameId);
window.removeEventListener('mouseup', mouseUpEventListener);
window.removeEventListener('touchend', touchEndEventListener);
root.destroy();
Expand Down
12 changes: 4 additions & 8 deletions apps/typegpu-docs/src/examples/rendering/3d-fish/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ function enqueuePresetChanges() {
fishBehaviorBuffer.write(presets.init);

setTimeout(() => {
if (disposed) return;
fishBehaviorBuffer.write(presets.default);
spinnerBackground.style.display = 'none';
speedMultiplier = 1;
Expand Down Expand Up @@ -222,12 +221,9 @@ const computeBindGroups = [0, 1].map((idx) =>

let odd = false;
let lastTimestamp: DOMHighResTimeStamp = 0;
let disposed = false;
let animationFrameId: number;

function frame(timestamp: DOMHighResTimeStamp) {
if (disposed) {
return;
}
odd = !odd;

currentTimeBuffer.write(timestamp);
Expand Down Expand Up @@ -270,10 +266,10 @@ function frame(timestamp: DOMHighResTimeStamp) {
.with(renderFishBindGroups[odd ? 1 : 0])
.draw(fishModel.polygonCount, p.fishAmount);

requestAnimationFrame(frame);
animationFrameId = requestAnimationFrame(frame);
}
enqueuePresetChanges();
requestAnimationFrame(frame);
animationFrameId = requestAnimationFrame(frame);

// #region Example controls and cleanup

Expand Down Expand Up @@ -442,7 +438,7 @@ const resizeObserver = new ResizeObserver(() => {
resizeObserver.observe(canvas);

export function onCleanup() {
disposed = true;
cancelAnimationFrame(animationFrameId);
window.removeEventListener('mouseup', mouseUpEventListener);
window.removeEventListener('mousemove', mouseMoveEventListener);
window.removeEventListener('touchmove', touchMoveEventListener);
Expand Down
27 changes: 9 additions & 18 deletions apps/typegpu-docs/src/examples/rendering/box-raytracing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,24 +248,13 @@ const pipeline = root.createRenderPipeline({

// UI

let disposed = false;
let animationFrameId: number;
let lastTime: number | null = null;

const onFrame = (loop: (deltaTime: number) => unknown) => {
let lastTime = Date.now();
const runner = () => {
if (disposed) {
return;
}
const now = Date.now();
const dt = now - lastTime;
lastTime = now;
loop(dt);
requestAnimationFrame(runner);
};
requestAnimationFrame(runner);
};
const runner = (timestamp: number) => {
const deltaTime = lastTime !== null ? timestamp - lastTime : 0;
lastTime = timestamp;

onFrame((deltaTime) => {
const width = canvas.width;
const height = canvas.height;

Expand All @@ -283,7 +272,9 @@ onFrame((deltaTime) => {
frame += (rotationSpeed * deltaTime) / 1000;

pipeline.withColorAttachment({ view: context }).draw(3);
});
animationFrameId = requestAnimationFrame(runner);
};
animationFrameId = requestAnimationFrame(runner);

// #region Example controls and cleanup

Expand Down Expand Up @@ -330,7 +321,7 @@ export const controls = defineControls({
});

export function onCleanup() {
disposed = true;
cancelAnimationFrame(animationFrameId);
root.destroy();
}

Expand Down
4 changes: 2 additions & 2 deletions apps/typegpu-docs/src/examples/rendering/clouds/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ resizeObserver.observe(canvas);

let frameId: number;

function render() {
paramsUniform.writePartial({ time: (performance.now() / 1000) % 500 });
function render(timestamp: number) {
paramsUniform.writePartial({ time: (timestamp / 1000) % 500 });

pipeline
.with(bindGroup)
Expand Down
11 changes: 6 additions & 5 deletions apps/typegpu-docs/src/examples/rendering/disco/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,14 @@ const pipelines = fragmentShaders.map((fragment) =>

let currentPipeline = pipelines[0];

let startTime = performance.now();
let startTime: null | number = null;
let frameId: number;

function render() {
const timestamp = (performance.now() - startTime) / 1000;
if (timestamp > 500.0) startTime = performance.now();
time.write(timestamp);
function render(timestamp: number) {
if (startTime === null) {
startTime = timestamp;
}
time.write((timestamp - startTime) / 1000);
resolutionUniform.write(d.vec2f(canvas.width, canvas.height));

currentPipeline
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ const properties = Properties({

// Buffers

const propertiesUniform = root.createUniform(Properties, properties);
const propertiesUniform = root.createUniform(Properties);
queuePropertiesBufferUpdate();

// these buffers are recreated with a different size on interpolationPoints change
function createLineVerticesBuffers() {
Expand Down Expand Up @@ -101,7 +102,7 @@ const backgroundVertex = tgpu.vertexFn({
const properties = propertiesUniform.$;
const leftBot = properties.transformation.mul(d.vec4f(-1, -1, 0, 1));
const rightTop = properties.transformation.mul(d.vec4f(1, 1, 0, 1));
const canvasRatio = (rightTop.x - leftBot.x) / (rightTop.y - leftBot.y);
const aspectRatio = (rightTop.x - leftBot.x) / (rightTop.y - leftBot.y);

const transformedPoints = [
d.vec2f(leftBot.x, 0),
Expand All @@ -111,12 +112,12 @@ const backgroundVertex = tgpu.vertexFn({
];

const currentPoint = properties.inverseTransformation.mul(
d.vec4f(transformedPoints[2 * iid + vid / 2].xy, 0, 1),
d.vec4f(transformedPoints[2 * iid + d.u32(vid / 2)].xy, 0, 1),
);

return {
pos: d.vec4f(
currentPoint.x + (d.f32(iid) * std.select(d.f32(-1), 1, vid % 2 === 0) * 0.005) / canvasRatio,
currentPoint.x + (d.f32(iid) * std.select(d.f32(-1), 1, vid % 2 === 0) * 0.005) / aspectRatio,
currentPoint.y + d.f32(1 - iid) * std.select(d.f32(-1), 1, vid % 2 === 0) * 0.005,
currentPoint.zw,
),
Expand Down Expand Up @@ -294,6 +295,12 @@ async function tryRecreateComputePipeline(
}

function queuePropertiesBufferUpdate() {
const leftBot = properties.transformation.mul(d.vec4f(-1, -1, 0, 1));
const rightTop = properties.transformation.mul(d.vec4f(1, 1, 0, 1));
const currentCanvasRatio = (rightTop.x - leftBot.x) / (rightTop.y - leftBot.y);
const desiredCanvasRatio = canvas.clientWidth / canvas.clientHeight;
const rescaleMatrix = mat4.scaling([desiredCanvasRatio / currentCanvasRatio, 1, 1], d.mat4x4f());
properties.transformation = std.mul(properties.transformation, rescaleMatrix);
properties.inverseTransformation = mat4.inverse(properties.transformation, d.mat4x4f());
propertiesUniform.write(properties);
}
Expand Down Expand Up @@ -379,12 +386,7 @@ window.addEventListener('touchend', touchEndEventListener);
// Resize observer and cleanup

const resizeObserver = new ResizeObserver(() => {
const leftBot = properties.transformation.mul(d.vec4f(-1, -1, 0, 1));
const rightTop = properties.transformation.mul(d.vec4f(1, 1, 0, 1));
const currentCanvasRatio = (rightTop.x - leftBot.x) / (rightTop.y - leftBot.y);
const desiredCanvasRatio = canvas.clientWidth / canvas.clientHeight;
const rescaleMatrix = mat4.scaling([desiredCanvasRatio / currentCanvasRatio, 1, 1], d.mat4x4f());
properties.transformation = std.mul(properties.transformation, rescaleMatrix);
queuePropertiesBufferUpdate();

msTexture.destroy();
msTexture = device.createTexture({
Expand Down
10 changes: 5 additions & 5 deletions apps/typegpu-docs/src/examples/rendering/jelly-slider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ const getFakeShadow = (position: d.v3f, lightDir: d.v3f): d.v3f => {

if (position.y < -GroundParams.groundThickness) {
// Applying darkening under the ground (the shadow cast by the upper ground layer)
const fadeSharpness = 30;
const fadeSharpness = d.f32(30);
const inset = 0.02;
const cutout = rectangleCutoutDist(position.xz) + inset;
const edgeDarkening = std.saturate(1 - cutout * fadeSharpness);
Expand All @@ -386,7 +386,7 @@ const getFakeShadow = (position: d.v3f, lightDir: d.v3f): d.v3f => {

const contrast = 20 * std.saturate(finalUV.y) * (0.8 + endCapX * 0.2);
const shadowOffset = -0.3;
const featherSharpness = 10;
const featherSharpness = d.f32(10);
const uvEdgeFeather =
std.saturate(finalUV.x * featherSharpness) *
std.saturate((1 - finalUV.x) * featherSharpness) *
Expand Down Expand Up @@ -714,7 +714,7 @@ const renderPipeline = root.createRenderPipeline({
});

const eventHandler = new EventHandler(canvas);
let lastTimeStamp = performance.now();
let lastTimestamp: number | null = null;
let frameCount = 0;
const taaResolver = new TAAResolver(root, width, height);

Expand Down Expand Up @@ -752,8 +752,8 @@ let animationFrameHandle: number;
function render(timestamp: number) {
frameCount++;
camera.jitter();
const deltaTime = Math.min((timestamp - lastTimeStamp) * 0.001, 0.1);
lastTimeStamp = timestamp;
const deltaTime = Math.min(lastTimestamp !== null ? (timestamp - lastTimestamp) * 0.001 : 0, 0.1);
lastTimestamp = timestamp;

randomUniform.write(d.vec2f((Math.random() - 0.5) * 2, (Math.random() - 0.5) * 2));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ const getFakeShadow = (position: d.v3f, lightDir: d.v3f): d.v3f => {
'use gpu';
if (position.y < -GroundParams.groundThickness) {
// Applying darkening under the ground (the shadow cast by the upper ground layer)
const fadeSharpness = 30;
const fadeSharpness = d.f32(30);
const inset = 0.02;
const cutout = rectangleCutoutDist(position.xz) + inset;
const edgeDarkening = std.saturate(1 - cutout * fadeSharpness);
Expand Down Expand Up @@ -484,7 +484,7 @@ const renderPipeline = root.createRenderPipeline({
targets: { format: presentationFormat },
});

let lastTimeStamp = performance.now();
let lastTimestamp: number | null = null;
let frameCount = 0;
const taaResolver = new TAAResolver(root, width, height);

Expand All @@ -507,8 +507,8 @@ let animationFrameHandle: number;
function render(timestamp: number) {
frameCount++;
camera.jitter();
const deltaTime = Math.min((timestamp - lastTimeStamp) * 0.001, 0.1);
lastTimeStamp = timestamp;
const deltaTime = Math.min(lastTimestamp !== null ? (timestamp - lastTimestamp) * 0.001 : 0, 0.1);
lastTimestamp = timestamp;

randomUniform.write(d.vec2f((Math.random() - 0.5) * 2, (Math.random() - 0.5) * 2));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,8 @@ const fragmentMain = tgpu.fragmentFn({
const PCF_SAMPLES = shadowParams.$.pcfSamples;
const diskRadius = shadowParams.$.diskRadius;

let visibilityAcc = 0.0;
for (let i = 0; i < PCF_SAMPLES; i++) {
let visibilityAcc = d.f32(0);
for (let i = d.u32(0); i < PCF_SAMPLES; i++) {
const o = samplesUniform.$[i].xy.mul(diskRadius);

const sampleDir = dir.add(right.mul(o.x)).add(realUp.mul(o.y));
Expand Down Expand Up @@ -352,11 +352,12 @@ const lightIndicatorBindGroup = root.createBindGroup(lightIndicatorLayout, {

let showDepthPreview = false;
let showDistanceView = false;
let lastTime = performance.now();
let lastTime: number | null = null;
let time = 0;
let animationFrameId: number;

function render(timestamp: number) {
const dt = (timestamp - lastTime) / 1000;
const dt = lastTime !== null ? (timestamp - lastTime) / 1000 : 0;
lastTime = timestamp;
time += dt;

Expand All @@ -376,7 +377,7 @@ function render(timestamp: number) {

if (showDepthPreview) {
pipelinePreview.withColorAttachment({ view: context }).draw(3);
requestAnimationFrame(render);
animationFrameId = requestAnimationFrame(render);
return;
}

Expand Down Expand Up @@ -415,9 +416,9 @@ function render(timestamp: number) {
.with(vertexLayout, BoxGeometry.vertexBuffer)
.drawIndexed(BoxGeometry.indexCount);

requestAnimationFrame(render);
animationFrameId = requestAnimationFrame(render);
}
requestAnimationFrame(render);
animationFrameId = requestAnimationFrame(render);

const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
Expand Down Expand Up @@ -644,6 +645,7 @@ export const controls = defineControls({
});

export function onCleanup() {
cancelAnimationFrame(animationFrameId);
BoxGeometry.clearBuffers();
window.removeEventListener('mouseup', mouseUpEventListener);
window.removeEventListener('mousemove', mouseMoveEventListener);
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 5 additions & 13 deletions apps/typegpu-docs/src/examples/rendering/two-boxes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,24 +277,16 @@ function drawObject(
.draw(vertexCount);
}

let disposed = false;

function render() {
if (disposed) {
return;
}
let animationFrameId: number;

function frame() {
drawObject(cubeBuffer, bindGroup, 36, 'clear');
drawObject(secondCubeBuffer, secondBindGroup, 36, 'load');
drawObject(planeBuffer, planeBindGroup, 6, 'load');
animationFrameId = requestAnimationFrame(frame);
}

function frame() {
requestAnimationFrame(frame);
render();
}

frame();
animationFrameId = requestAnimationFrame(frame);

// #region Example controls and cleanup

Expand Down Expand Up @@ -474,7 +466,7 @@ const resizeObserver = new ResizeObserver(() => {
resizeObserver.observe(canvas);

export function onCleanup() {
disposed = true;
cancelAnimationFrame(animationFrameId);
window.removeEventListener('mouseup', mouseUpEventListener);
window.removeEventListener('mousemove', mouseMoveEventListener);
window.removeEventListener('touchend', touchEndEventListener);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ function createBlurPass(root: TgpuRoot, direction: 'horizontal' | 'vertical') {
let totalWeight = d.f32(0);

for (let i = -BLUR_RADIUS; i <= BLUR_RADIUS; i++) {
const offset = offsetDir * i * texelSize;
const offset = offsetDir * d.f32(i) * texelSize;
const weight = std.exp(-d.f32(i * i) / (2 * BLUR_RADIUS));
result +=
std.textureSampleLevel(
Expand Down
Loading
Loading