CPU와 GPU가 함께 쓰는 헬퍼

CPU와 GPU가 함께 쓰는 헬퍼

프래그먼트 진입점이 GPU에서 그리고 호스트가 CPU에서 부르는 지형 함수 height입니다. 호스트는 fs(canvas, { view })로 지형을 그린 뒤, 커서 아래의 높이를 얻으려고 height([u, v])를 부릅니다. 결과는 평범한 숫자이고, 같은 코드를 f32 정밀도로 계산한 값입니다. 캔버스는 읽지 않는다(언어 문서 §64).

실행 tier WebGPUWebGL2CPU tier

이 목록은 컴파일러가 확인합니다. tier(호출이 실행되는 백엔드)는 호스트의 실행 전체가 그 tier 하나만으로 기준값을 낼 때만 목록에 오릅니다. 컴파일러의 저니 게이트가 호스트마다 WebGPU와 WebGL2에서 실행하고, 단위 테스트가 CPU tier에서 실행합니다.

"use typeshade";
/* @example
{
"title": "Host: one helper on the CPU and the GPU",
"blurb": "A terrain `height` function that the fragment entry draws on the GPU and the host calls on the CPU. The host draws the terrain with `fs(canvas, { view })`, then calls `height([u, v])` for the height under the cursor: a plain number, from the same code at `f32` precision, with no read of the canvas (surface §64).",
"renderable": false,
"reason": "no entry point"
}
*/
class View {
size: vec2;
}
declare const view: uniform<View>;
// An ordinary exported function: the fragment entry calls it on the GPU, and a host that imports
// the module calls it on the CPU.
export function height(p: vec2): f32 {
return 0.5 + 0.25 * sin(6.2831853 * p.x) * cos(6.2831853 * p.y);
}
@fragment
export function fs(@builtin("position") p: vec4): vec4 {
const h = height(p.xy / view.size);
return vec4(h, h, h, 1.);
}
// Call a shader's helper on the CPU, and draw with the same function on the GPU (surface §64).
//
// `height` is an ordinary function of the module. The draw runs it for each pixel on the GPU;
// the host calls it on the CPU, at `f32` precision, for the one value it needs.
import { fs, height } from './host-helper.shade.ts';
/** Draw the terrain into `canvas`, and return the height under the pixel `cursor`. */
export async function run(
canvas: HTMLCanvasElement | OffscreenCanvas,
cursor: readonly [number, number],
): Promise<number> {
const { width, height: rows } = canvas;
await fs(canvas, { view: { size: [width, rows] } });
// The draw computed this pixel at its centre, so the host asks for the same point.
return height([(cursor[0] + 0.5) / width, (cursor[1] + 0.5) / rows]);
}

두 파일 모두 커밋 91c2fe31의 컴파일러에 있는 그대로이며, 예제 디렉터리에서 읽어 왔습니다.

GitHub의 모듈GitHub의 호스트 파일

이 페이지 편집 문제 보고