Skip to content

Commit

Permalink
add dpr test
Browse files Browse the repository at this point in the history
  • Loading branch information
greggman committed Jan 9, 2025
1 parent 707fee5 commit 61bd698
Showing 1 changed file with 166 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>WebGPU Resize Canvas - Pixel Perfect</title>
<style>
@import url(https://webgpufundamentals.org/webgpu/resources/webgpu-lesson.css);
html, body {
margin: 0; /* remove the default margin */
height: 100%; /* make the html,body fill the page */
}
canvas {
display: block; /* make the canvas act like a block */
width: 100%; /* make the canvas fill its container */
height: 100%;
}
#info {
position: absolute;
left: 0;
top: 0;
padding: 0.5em;
margin: 0;
background-color: rgba(0, 0, 0, 0.7);
color: white;
}
</style>
</head>
<body>
<canvas></canvas>
<pre id="info"></pre>
</body>
<script>
// WebGPU Resize Canvas - Pixel Perfect
// from https://webgpufundamentals.org/webgpu/webgpu-resize-pixel-perfect.html

const info = document.querySelector('#info');

async function main() {
const adapter = await navigator.gpu?.requestAdapter();
const device = await adapter?.requestDevice();
if (!device) {
fail('need a browser that supports WebGPU');
return;
}

// Get a WebGPU context from the canvas and configure it
const canvas = document.querySelector('canvas');
const context = canvas.getContext('webgpu');
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format: presentationFormat,
});

const module = device.createShaderModule({
label: 'hardcoded checkerboard triangle shaders',
code: `
struct OurVertexShaderOutput {
@builtin(position) position: vec4f,
};
@vertex fn vs(
@builtin(vertex_index) vertexIndex : u32
) -> OurVertexShaderOutput {
let pos = array(
vec2f(-1.0, 3.0),
vec2f( 3.0, -1.0),
vec2f(-1.0, -1.0),
);
var vsOutput: OurVertexShaderOutput;
vsOutput.position = vec4f(pos[vertexIndex], 0.0, 1.0);
return vsOutput;
}
@fragment fn fs(fsInput: OurVertexShaderOutput) -> @location(0) vec4f {
let hv = vec2f(floor(fsInput.position.xy % 2));
return vec4f(1, 0, 1, 1) * hv.x +
vec4f(0, 1, 0, 1) * hv.y;
}
`,
});

const pipeline = device.createRenderPipeline({
label: 'hardcoded checkerboard triangle pipeline',
layout: 'auto',
vertex: {
module,
},
fragment: {
module,
targets: [{ format: presentationFormat }],
},
});

const renderPassDescriptor = {
label: 'our basic canvas renderPass',
colorAttachments: [
{
// view: <- to be filled out when we render
clearValue: [0.3, 0.3, 0.3, 1],
loadOp: 'clear',
storeOp: 'store',
},
],
};

let renderCount = 0;
const elemSizes = new WeakMap();
function render() {
const { width, height } = elemSizes.get(canvas);
canvas.width = Math.max(1, Math.min(Math.round(width * visualViewport.scale), device.limits.maxTextureDimension2D));
canvas.height = Math.max(1, Math.min(Math.round(height * visualViewport.scale), device.limits.maxTextureDimension2D));

info.textContent = `\
devicePixelRatio: ${devicePixelRatio}
canvas size: ${canvas.width}x${canvas.height}
visualViewport.scale: ${visualViewport.scale}
`;

// Get the current texture from the canvas context and
// set it as the texture to render to.
renderPassDescriptor.colorAttachments[0].view =
context.getCurrentTexture().createView();

const encoder = device.createCommandEncoder({ label: 'our encoder' });
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(pipeline);
pass.draw(3); // call our vertex shader 3 times
pass.end();

const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}

const observer = new ResizeObserver(entries => {
for (const entry of entries) {
const width = (entry.devicePixelContentBoxSize?.[0].inlineSize ||
entry.contentBoxSize[0].inlineSize * devicePixelRatio);
const height = (entry.devicePixelContentBoxSize?.[0].blockSize ||
entry.contentBoxSize[0].blockSize * devicePixelRatio);
elemSizes.set(entry.target, { width, height });
// re-render
render();
}
});

visualViewport.addEventListener('resize', render);

try {
observer.observe(canvas, { box: 'device-pixel-content-box' });
} catch {
observer.observe(canvas, { box: 'content-box' });
}
}

function fail(msg) {
// eslint-disable-next-line no-alert
alert(msg);
}

main();

</script>
</html>

0 comments on commit 61bd698

Please sign in to comment.