Шахова підлогова сітка — це опорна площина землі, яку ви бачите під 3D-моделями в CAD-переглядачах (FreeCAD, Fusion 360, в’юпорт Blender). Вона слугує двом цілям: дає глядачеві відчуття масштабу і забезпечує просторову опору, щоб можна було сказати, де модель розташована у світовому просторі. Сітка зазвичай має шаховий візерунок для швидкого візуального підрахунку комірок, лінійну розмітку через регулярні інтервали, позначки на краях рамки і числові підписи масштабу, щоб зчитувати координати.
Цей пост показує мінімальну реалізацію WebGPU без залежностей, що
рендерить шахову підлогову сітку з масштабною розміткою, числовими
підписами й орбітальною камерою. Повний вихідник внизу; живе демо
нижче завантажує той самий скрипт з /scripts/floor-grid-webgpu.js.
Перетягуйте для орбіти, скрольте для зуму. Сітка 200×300 одиниць із комірками по 10 одиниць (20×30 поділів). Потрібен браузер із підтримкою WebGPU (Chrome / Edge 113+).
Як це працює
Сітка рендериться в три проходи в межах одного render pass:
- Шаховий квад — єдиний плоский квад (два трикутники), що покриває область сітки на z = 0. Шаховий візерунок обчислюється процедурно у фрагментному шейдері зі світлової позиції, а не з текстури. Це означає: без алокації текстури, без UV-мапування, і візерунок незалежний від роздільності (немає пікселізації при наближенні).
- Лінії сітки — line-list із кольорами на вершину. Звичайні лінії сітки світло-сірі, два осьові краї темніші, а позначки на рамці — середнього відтінку.
- Підписи масштабу — числові підписи позначок, відрендерені як 3D-текстуровані квади, компланарні з сіткою (z = 0), з атласом гліфів, згенерованим при ініціалізації на 2D-canvas. Підписи — справжній 3D-текст: вони масштабуються й обертаються з камерою, а не є оверлеєм у екранному просторі. Підписи осі X повернуті на -90°, щоб іти вздовж напрямку Y; підписи осі Y вирівняні праворуч ліворуч від сітки. Проріджування підписів показує кожну 2-гу позначку, щоб уникнути захаращення.
Усі проходи використовують premultiplied alpha blending, тож напівпрозорі елементи коректно композитуються з фоном canvas.
Ключові техніки:
- Процедурна шахівниця у фрагментному шейдері. Вершинний
шейдер пропускає світову XY-позицію до фрагментного шейдера як
varying. Фрагментний шейдер обчислює, до якої комірки належить
фрагмент, через
floor(worldPos / cellSize)і чергує два відтінки сірого на основі(cellX + cellY) % 2. Розмір комірки (GRID_SIZE / GRID_DIVISIONS) випікається у вихідник WGSL під час створення шейдера через інтерполяцію шаблонного літерала JavaScript — додатковий uniform не потрібен. - Переплетена геометрія ліній. Лінії сітки, осьові краї й
позначки упаковані в єдиний вершинний буфер line-list із
переплетеною розкладкою
[x, y, z, r, g, b](24 байти на вершину). Колір на вершину дає кожному типу ліній власний відтінок без окремих draw-викликів. - Атлас гліфів для підписів масштабу. Бітмап-атлас для символів
0123456789.-генерується на 2D-canvas при ініціалізації і завантажується як текстура WebGPU. Кожен гліф вимірюється окремо, тож атлас використовує комірки змінної ширини (без вигляду моноширинності). Фрагментний шейдер підписів семплує атлас і використовує червоний канал як alpha (білий текст на прозорому тлі), тонований uniform-кольором. - Орбітальна камера. Позиція камери обчислюється зі сферичних
координат (yaw, pitch, відстань) і подається в матрицю
lookAt. Перетягування керує yaw/pitch; коліщатко миші — радіусом орбіти. Pitch обмежений трохи вище 0 і трохи нижче 90°, тож камера ніколи не заходить під землю і не дивиться прямо вниз. - Запис глибини вимкнено. Усі pipelines використовують
depthWriteEnabled: false, тож сітка не закриває геометрію, намальовану після неї. У повному 3D-переглядачі сітка малюється першою, потім модель зверху. - Premultiplied alpha blending. Canvas використовує
alphaMode: 'premultiplied', тож усі фрагментні шейдери виводять(color * alpha, alpha), а blend-стан використовуєsrcFactor: 'one'(не'src-alpha'). Це коректне налаштування blending для premultiplied alpha — straight-alpha blending тут удвічі затемнив би альфа-канал, роблячи напівпрозорі об’єкти майже невидимими.
Використання на власній сторінці
Покладіть /scripts/floor-grid-webgpu.js у вашу папку static і додайте canvas із класом
nav-grid-canvas — скрипт автоініціалізує кожен відповідний canvas
на сторінці:
<canvas class="nav-grid-canvas"
style="width:960px;height:720px;"></canvas>
<script src="/scripts/floor-grid-webgpu.js" defer></script>Задайте розмір canvas через CSS (width/height); скрипт обробляє
масштабування devicePixelRatio і зміну розміру depth-текстури
внутрішньо. Щоб змінити розмір сітки чи кількість поділів,
відредагуйте константи GRID_SIZE_X, GRID_SIZE_Y,
GRID_DIVISIONS_X і GRID_DIVISIONS_Y на початку скрипта — розмір
комірки шахівниці виводиться автоматично по осі. Для квадратних
комірок обидва розміри комірок мають бути рівними
(GRID_SIZE_X / GRID_DIVISIONS_X === GRID_SIZE_Y / GRID_DIVISIONS_Y).
Повний код
// SPDX-FileCopyrightText: 2026 Uli Köhler <gitlab@techoverflow.net>
// SPDX-License-Identifier: CC0-1.0
//
// Minimal WebGPU checkerboard floor grid with scale labels.
// Renders a ground-reference grid in the XY plane with:
// - A procedural checkerboard pattern (computed in the fragment shader)
// - Grid lines at regular intervals
// - Darker axis lines along the two edges through the origin
// - Tick marks on the border edges for scale reading
// - Numeric scale labels rendered as 3D textured quads (glyph atlas)
// The camera orbits the origin; drag to rotate, mouse wheel to zoom.
// Auto-initializes every <canvas class="nav-grid-canvas"> on the page.
//
// Why an IIFE? We wrap everything in an immediately-invoked function
// expression so that none of the helpers, constants, or the WGSL source
// leak into the global scope. The script is intended to be included
// verbatim with <script src=... defer>, possibly alongside other scripts
// on the same page, so isolation matters.
(function () {
'use strict';
// ─────────────────────────────────────────────────────────────────────
// Grid configuration
// ─────────────────────────────────────────────────────────────────────
// The grid lies in the XY plane (z = 0) and is centered at the origin.
// It spans [-GRID_SIZE_X/2, +GRID_SIZE_X/2] on X and
// [-GRID_SIZE_Y/2, +GRID_SIZE_Y/2] on Y.
//
// GRID_DIVISIONS_X / GRID_DIVISIONS_Y control how many cells per axis.
// Each cell is GRID_SIZE_X / GRID_DIVISIONS_X units wide on X and
// GRID_SIZE_Y / GRID_DIVISIONS_Y on Y. For a checkerboard with square
// cells, both cell sizes must be equal — here 200/20 = 300/30 = 10.
//
// For a real CAD viewer you would typically make these configurable
// and re-center the grid on the bounding box of the loaded geometry
// (see WebGCodeViewer's GridRenderer.setCenter). Here we keep it
// simple with fixed values that look good in the demo canvas.
const GRID_SIZE_X = 200; // total X extent in world units (e.g. mm)
const GRID_SIZE_Y = 300; // total Y extent in world units (e.g. mm)
const GRID_DIVISIONS_X = 20; // cells along X → cell size = 10.0 units
const GRID_DIVISIONS_Y = 30; // cells along Y → cell size = 10.0 units
const TICK_LENGTH = 0.3; // tick mark length as fraction of cell size
// Colors for the grid elements. All are dark grays so the grid reads
// as a subtle reference overlay, not a foreground object.
const GRID_COLOR = [0.25, 0.25, 0.27]; // regular grid lines
const AXIS_COLOR = [0.15, 0.15, 0.17]; // darker — the two edge axes
const TICK_COLOR = [0.20, 0.20, 0.22]; // tick marks on the border
const LABEL_COLOR = [0.25, 0.25, 0.27]; // numeric labels (matches grid)
// ─────────────────────────────────────────────────────────────────────
// Label configuration
// ─────────────────────────────────────────────────────────────────────
// Labels are rendered as textured quads coplanar with the grid (z=0),
// using a glyph atlas generated at init time from a 2D canvas. This
// is true 3D text — it scales and rotates with the camera, not a
// screen-space overlay.
const GLYPHS = '0123456789.-'; // characters supported by the atlas
const GLYPH_PX_H = 32; // pixel height of each glyph cell
const GLYPH_PAD = 2; // px padding around each glyph (anti-bleed)
const CHAR_HEIGHT = 7.5; // world-space character height (mm)
const LABEL_MARGIN = 2; // gap from grid edge to label (mm)
const TICK_STRIDE = 2; // show every Nth tick label to avoid clutter
// ─────────────────────────────────────────────────────────────────────
// Minimal mat4 helpers (column-major, WebGPU NDC z in [0,1])
// ─────────────────────────────────────────────────────────────────────
// WebGPU / WGSL stores matrices column-major, i.e. element [col*4+row].
// We mirror that layout here so we can upload the Float32Array directly
// to a uniform buffer without any transpose step.
// We only implement the handful of matrices we need: identity, multiply,
// perspective, and lookAt. No dependency on gl-matrix or similar — the
// goal is a single self-contained file.
function mat4Identity() {
const m = new Float32Array(16);
m[0] = m[5] = m[10] = m[15] = 1;
return m;
}
// Returns a * b in the sense that (a * b) * v applies b first, then a.
// This is the convention used everywhere in this file: the
// view-projection is built as proj * view, so a point is transformed
// view→clip.
function mat4Multiply(a, b) {
const r = new Float32Array(16);
for (let col = 0; col < 4; col++) {
for (let row = 0; row < 4; row++) {
let s = 0;
for (let k = 0; k < 4; k++) s += a[k * 4 + row] * b[col * 4 + k];
r[col * 4 + row] = s;
}
}
return r;
}
// Right-handed perspective projection matrix.
// The camera looks down -Z, so visible points have z < 0.
// This is the WebGPU convention: clip space z is in [0, 1] (not [-1, 1]
// as in OpenGL), which is why m[10] = far/(near-far) and m[14] has the
// extra near*far term. Getting this wrong is the #1 source of "my
// geometry disappeared" bugs when porting WebGL code to WebGPU.
function mat4Perspective(fovy, aspect, near, far) {
const f = 1 / Math.tan(fovy / 2);
const m = new Float32Array(16);
m[0] = f / aspect;
m[5] = f;
m[10] = far / (near - far);
m[11] = -1;
m[14] = (far * near) / (near - far);
return m;
}
// Right-handed lookAt matrix: places the camera at 'eye' looking toward
// 'target' with 'up' as the screen-up direction. Returns a view matrix
// (world→view). eye, target, up are plain {x,y,z} objects.
//
// The math:
// forward = normalize(eye - target) (points from target to eye)
// right = normalize(cross(up, forward))
// trueUp = cross(forward, right) (re-orthogonalized up)
// The matrix rows are [right | trueUp | forward], and the translation
// column is -dot(axis, eye) for each axis, which moves the world so the
// camera sits at the origin.
function mat4LookAt(eye, target, up) {
const zx = eye.x - target.x, zy = eye.y - target.y, zz = eye.z - target.z;
let zl = Math.hypot(zx, zy, zz);
const fx = zx / zl, fy = zy / zl, fz = zz / zl;
// right = normalize(cross(up, forward))
let rx = up.y * fz - up.z * fy;
let ry = up.z * fx - up.x * fz;
let rz = up.x * fy - up.y * fx;
let rl = Math.hypot(rx, ry, rz);
// Degenerate case: up is parallel to forward. Fall back to (1,0,0)
// so we don't produce NaNs.
if (rl < 1e-6) { rx = 1; ry = 0; rz = 0; rl = 1; }
rx /= rl; ry /= rl; rz /= rl;
// trueUp = cross(forward, right) — already unit length.
const ux = fy * rz - fz * ry;
const uy = fz * rx - fx * rz;
const uz = fx * ry - fy * rx;
const m = mat4Identity();
m[0] = rx; m[1] = ux; m[2] = fx;
m[4] = ry; m[5] = uy; m[6] = fy;
m[8] = rz; m[9] = uz; m[10] = fz;
m[12] = -(rx * eye.x + ry * eye.y + rz * eye.z);
m[13] = -(ux * eye.x + uy * eye.y + uz * eye.z);
m[14] = -(fx * eye.x + fy * eye.y + fz * eye.z);
return m;
}
// ─────────────────────────────────────────────────────────────────────
// Geometry: grid lines + checkerboard quad
// ─────────────────────────────────────────────────────────────────────
// The grid is drawn in three passes:
// 1. Checkerboard — a single quad (2 triangles) covering the grid
// area. The checkerboard pattern is computed procedurally in the
// fragment shader from the world-space position, so we don't need
// a texture or per-cell geometry.
// 2. Grid lines — a line-list with per-vertex colors. Regular grid
// lines are gray, the two axis edges are darker, and tick marks
// on the border are a medium shade.
// 3. Labels — textured quads for numeric tick labels, rendered using
// a glyph atlas (see buildGlyphAtlas / buildLabelVertices).
//
// The vertex layout for grid lines is interleaved:
// [x, y, z, r, g, b] per vertex = 24 bytes (arrayStride: 24)
// The checkerboard quad has position only:
// [x, y, z] per vertex = 12 bytes (arrayStride: 12)
// The label quads have position + UV:
// [x, y, z, u, v] per vertex = 20 bytes (arrayStride: 20)
// Build the grid line geometry: regular lines, axis edges, tick marks.
// Returns a Float32Array of interleaved [x,y,z, r,g,b] vertices.
function buildGridLines() {
const sizeX = GRID_SIZE_X;
const sizeY = GRID_SIZE_Y;
const stepX = GRID_SIZE_X / GRID_DIVISIONS_X;
const stepY = GRID_SIZE_Y / GRID_DIVISIONS_Y;
const tickLenX = stepX * TICK_LENGTH;
const tickLenY = stepY * TICK_LENGTH;
// Grid spans from -size/2 to +size/2 on each axis (centered at origin).
const x0 = -sizeX / 2;
const y0 = -sizeY / 2;
const lines = [];
// Helper: push a line segment with a single color for both endpoints.
function addLine(x1, y1, z1, x2, y2, z2, color) {
lines.push(x1, y1, z1, color[0], color[1], color[2]);
lines.push(x2, y2, z2, color[0], color[1], color[2]);
}
// ── Regular grid lines ──
// Vertical lines (constant X) spaced stepX apart, spanning the full
// Y extent. Horizontal lines (constant Y) spaced stepY apart,
// spanning the full X extent.
for (let i = 0; i <= GRID_DIVISIONS_X; i++) {
const p = x0 + i * stepX;
addLine(p, y0, 0, p, y0 + sizeY, 0, GRID_COLOR); // vertical
}
for (let i = 0; i <= GRID_DIVISIONS_Y; i++) {
const q = y0 + i * stepY;
addLine(x0, q, 0, x0 + sizeX, q, 0, GRID_COLOR); // horizontal
}
// ── Axis lines along the two edges through the origin ──
// These are drawn slightly darker so the X=0 and Y=0 lines stand out
// as reference axes. In this centered layout the bottom-left corner
// is at (-sizeX/2, -sizeY/2), so the "axes" are the left and bottom
// border edges.
addLine(x0, y0, 0, x0 + sizeX, y0, 0, AXIS_COLOR); // bottom edge (X)
addLine(x0, y0, 0, x0, y0 + sizeY, 0, AXIS_COLOR); // left edge (Y)
// ── Tick marks on the border edges ──
// Ticks are short inward-pointing marks on the bottom and left
// edges, one per grid line intersection. They make it easy to read
// off coordinates at a glance, like ruler tick marks.
//
// X-axis ticks: along the bottom edge (Y = y0), extend inward (+Y).
for (let i = 0; i <= GRID_DIVISIONS_X; i++) {
const p = x0 + i * stepX;
addLine(p, y0, 0, p, y0 + tickLenY, 0, TICK_COLOR);
}
// Y-axis ticks: along the left edge (X = x0), extend inward (+X).
for (let i = 0; i <= GRID_DIVISIONS_Y; i++) {
const p = y0 + i * stepY;
addLine(x0, p, 0, x0 + tickLenX, p, 0, TICK_COLOR);
}
return new Float32Array(lines);
}
// Build the checkerboard quad: two triangles covering the entire grid
// area. The actual checkerboard pattern is generated in the fragment
// shader from world-space coordinates, so the geometry is just a flat
// quad at z = 0.
function buildCheckerQuad() {
const sx = GRID_SIZE_X;
const sy = GRID_SIZE_Y;
const x0 = -sx / 2;
const y0 = -sy / 2;
// Two triangles forming a quad:
// (x0,y0) → (x0+sx, y0) → (x0+sx, y0+sy) [first triangle]
// (x0,y0) → (x0+sx, y0+sy) → (x0, y0+sy) [second triangle]
return new Float32Array([
x0, y0, 0,
x0 + sx, y0, 0,
x0 + sx, y0 + sy, 0,
x0, y0, 0,
x0 + sx, y0 + sy, 0,
x0, y0 + sy, 0,
]);
}
// ─────────────────────────────────────────────────────────────────────
// Glyph atlas generation
// ─────────────────────────────────────────────────────────────────────
// We generate a bitmap atlas for the characters '0123456789.-' on a
// 2D canvas at init time, then upload it as a WebGPU texture. Each
// glyph is measured individually so the atlas uses variable-width
// cells (no fixed-width look). The world-space width of each glyph
// is proportional to its pixel width, preserving the font's natural
// aspect ratio.
//
// The atlas is a single horizontal strip. Each glyph's UV coordinates
// and world-space width are stored in the glyphMap for later quad
// generation.
// Build the glyph atlas on a 2D canvas and return the canvas plus a
// map from character → {u0, v0, u1, v1, worldW}.
function buildGlyphAtlas() {
const fontPx = Math.floor(GLYPH_PX_H * 0.8);
// Serif / math-friendly font stack for a CAD-like look.
const fontStack = '"Cambria Math", "STIX Two Math", "Latin Modern Math", "Times New Roman", Georgia, serif';
// First pass: measure every glyph to determine cell widths.
const measureCanvas = document.createElement('canvas');
const mctx = measureCanvas.getContext('2d');
mctx.font = fontPx + 'px ' + fontStack;
mctx.textAlign = 'center';
mctx.textBaseline = 'middle';
const cellWidths = [];
let totalW = 0;
for (let i = 0; i < GLYPHS.length; i++) {
const w = Math.ceil(mctx.measureText(GLYPHS[i]).width) + 2 * GLYPH_PAD;
cellWidths.push(w);
totalW += w;
}
const atlasW = totalW;
const atlasH = GLYPH_PX_H;
// Second pass: draw the atlas (white text on transparent background).
const atlasCanvas = document.createElement('canvas');
atlasCanvas.width = atlasW;
atlasCanvas.height = atlasH;
const ctx = atlasCanvas.getContext('2d');
ctx.clearRect(0, 0, atlasW, atlasH);
ctx.fillStyle = 'white';
ctx.font = fontPx + 'px ' + fontStack;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const glyphMap = new Map();
let xOff = 0;
for (let i = 0; i < GLYPHS.length; i++) {
const cw = cellWidths[i];
ctx.fillText(GLYPHS[i], xOff + cw / 2, atlasH / 2);
// Record UVs + world-space width (proportional to pixel width).
glyphMap.set(GLYPHS[i], {
u0: xOff / atlasW,
v0: 0,
u1: (xOff + cw) / atlasW,
v1: 1,
worldW: CHAR_HEIGHT * cw / GLYPH_PX_H,
});
xOff += cw;
}
return { atlasCanvas, atlasW, atlasH, glyphMap };
}
// Format a tick value for display as a label string.
// Trims unnecessary decimal places while keeping at least one digit.
function formatTickValue(v) {
if (Math.abs(v) < 1e-9) return '0';
if (Math.abs(v) >= 100) return v.toFixed(0);
if (Math.abs(v) >= 10) return v.toFixed(1);
return v.toFixed(1);
}
// Build label quad vertices for all visible tick labels.
//
// Labels are placed OUTSIDE the grid:
// X-axis labels: below the bottom edge (Y < y0), rotated -90° about Z
// so the text runs along the Y axis (perpendicular to the X axis).
// Y-axis labels: left of the left edge (X < x0), right-aligned.
//
// Label thinning: only every TICK_STRIDE-th tick gets a label, plus the
// last tick is always included. This avoids clutter when the grid has
// many divisions.
//
// Returns a Float32Array of [x,y,z, u,v] vertices (20 bytes per vertex).
function buildLabelVertices(glyphMap) {
const stepX = GRID_SIZE_X / GRID_DIVISIONS_X;
const stepY = GRID_SIZE_Y / GRID_DIVISIONS_Y;
const x0 = -GRID_SIZE_X / 2;
const y0 = -GRID_SIZE_Y / 2;
// Generate tick positions and values for both axes.
const xTicks = [];
for (let i = 0; i <= GRID_DIVISIONS_X; i++) {
const p = x0 + i * stepX;
xTicks.push({ position: [p, y0, 0], value: p, axis: 0 });
}
const yTicks = [];
for (let i = 0; i <= GRID_DIVISIONS_Y; i++) {
const p = y0 + i * stepY;
yTicks.push({ position: [x0, p, 0], value: p, axis: 1 });
}
// Thin: show every TICK_STRIDE-th tick, always include the last.
const thin = (arr) => arr.filter((_, i) =>
i % TICK_STRIDE === 0 || i === arr.length - 1);
const thinned = [...thin(xTicks), ...thin(yTicks)];
const vertices = [];
for (const tick of thinned) {
const label = formatTickValue(tick.value);
// Look up glyph info (UVs + variable world width) from the atlas.
function glyphFor(ch) {
return glyphMap.get(ch) || null;
}
// Total label width = sum of per-glyph advance widths.
let labelWidth = 0;
for (const ch of label) {
const g = glyphFor(ch);
labelWidth += g ? g.worldW : CHAR_HEIGHT * 0.5;
}
if (tick.axis === 0) {
// X-axis: rotate the label -90° about Z so the text runs along
// Y (normal to the X axis being labeled), while remaining
// coplanar with the grid plane (z=0). The label is centered on
// the tick in X and placed just below the grid edge (Y < y0).
//
// After -90° rotation about Z: (x,y) → (y, -x), so a glyph
// that was at horizontal offset cx becomes at vertical offset
// -cx relative to the pivot.
const pivotX = tick.value;
const pivotY = y0 - LABEL_MARGIN - labelWidth / 2;
let advance = 0;
for (const ch of label) {
const g = glyphFor(ch);
const w = g ? g.worldW : CHAR_HEIGHT * 0.5;
// Unrotated center X relative to label center.
const cx = advance + w / 2 - labelWidth / 2;
// After -90° about Z: center maps to (0, -cx) relative to pivot.
const yCenter = pivotY - cx;
// Post-rotation half-extents: X = CHAR_HEIGHT/2, Y = w/2.
const hx = CHAR_HEIGHT / 2;
const hy = w / 2;
const u0 = g ? g.u0 : 0, u1 = g ? g.u1 : 0;
const v0 = g ? g.v0 : 0, v1 = g ? g.v1 : 1;
vertices.push(
// Triangle 1: BL, BR, TR
pivotX - hx, yCenter + hy, 0, u0, v1,
pivotX - hx, yCenter - hy, 0, u1, v1,
pivotX + hx, yCenter - hy, 0, u1, v0,
// Triangle 2: BL, TR, TL
pivotX - hx, yCenter + hy, 0, u0, v1,
pivotX + hx, yCenter - hy, 0, u1, v0,
pivotX + hx, yCenter + hy, 0, u0, v0,
);
advance += w;
}
} else {
// Y-axis: right-align the label to the left of the grid edge
// (X < x0). No rotation — text reads left-to-right.
const originX = x0 - LABEL_MARGIN - labelWidth;
const originY = tick.value - CHAR_HEIGHT / 2;
let cursorX = originX;
for (const ch of label) {
const g = glyphFor(ch);
const w = g ? g.worldW : CHAR_HEIGHT * 0.5;
const xa = cursorX;
const xb = cursorX + w;
const ya = originY;
const yb = originY + CHAR_HEIGHT;
const u0 = g ? g.u0 : 0, u1 = g ? g.u1 : 0;
const v0 = g ? g.v0 : 0, v1 = g ? g.v1 : 1;
// Two triangles: (xa,ya) (xb,ya) (xb,yb) (xa,yb)
// UV: top-left=(u0,v0), top-right=(u1,v0),
// bottom-right=(u1,v1), bottom-left=(u0,v1)
vertices.push(
// Triangle 1: bottom-left, bottom-right, top-right
xa, ya, 0, u0, v1,
xb, ya, 0, u1, v1,
xb, yb, 0, u1, v0,
// Triangle 2: bottom-left, top-right, top-left
xa, ya, 0, u0, v1,
xb, yb, 0, u1, v0,
xa, yb, 0, u0, v0,
);
cursorX += w;
}
}
}
return new Float32Array(vertices);
}
// ─────────────────────────────────────────────────────────────────────
// WGSL shader
// ─────────────────────────────────────────────────────────────────────
// One shader module, three pipelines (checkerboard + grid lines + labels).
//
// The grid-line pipeline transforms positions by the view-projection
// matrix and passes the per-vertex color through; the fragment shader
// outputs it with premultiplied alpha.
//
// The checkerboard pipeline passes the world-space XY position to the
// fragment shader as a varying. The fragment shader computes which
// checkerboard cell the fragment falls in using floor(worldPos /
// cellSize) and alternates between two shades of gray based on
// (cx + cy) % 2.
//
// The label pipeline samples a glyph atlas texture and uses the red
// channel as alpha (white text on transparent background). The text
// color comes from a uniform.
//
// All three pipelines use premultiplied alpha blending: the fragment
// shaders output (color * alpha, alpha) and the blend state uses
// srcFactor: 'one' (not 'src-alpha'). This is the correct setup for
// alphaMode: 'premultiplied' on the canvas — without it, the
// checkerboard and labels would be nearly invisible because the alpha
// channel would be double-darkened.
//
// The ${...} template literals below are interpolated by JavaScript at
// shader creation time, baking the grid size and division count
// directly into the WGSL source. This avoids extra uniforms.
const SHADER = /* wgsl */ `
struct Uniforms {
viewProj: mat4x4<f32>,
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
// ── Grid-line pipeline ──
struct LineVertexInput {
@location(0) position: vec3<f32>,
@location(1) color: vec3<f32>,
};
struct LineVertexOutput {
@builtin(position) clipPosition: vec4<f32>,
@location(0) color: vec3<f32>,
};
@vertex
fn vs_line(input: LineVertexInput) -> LineVertexOutput {
var out: LineVertexOutput;
out.clipPosition = uniforms.viewProj * vec4<f32>(input.position, 1.0);
out.color = input.color;
return out;
}
@fragment
fn fs_line(input: LineVertexOutput) -> @location(0) vec4<f32> {
// Premultiplied alpha: output (color * alpha, alpha) so the blend
// state (srcFactor: 'one') composites correctly.
let alpha = 0.7;
return vec4<f32>(input.color * alpha, alpha);
}
// ── Checkerboard pipeline ──
// The vertex shader passes world-space XY to the fragment shader so it
// can compute the checkerboard cell coordinates.
struct CheckerVertexOutput {
@builtin(position) clipPosition: vec4<f32>,
@location(0) worldPos: vec2<f32>,
};
@vertex
fn vs_checker(@location(0) position: vec3<f32>) -> CheckerVertexOutput {
var out: CheckerVertexOutput;
out.clipPosition = uniforms.viewProj * vec4<f32>(position, 1.0);
// Pass the world-space XY position through as a varying. The
// fragment shader uses this to determine which checker cell the
// fragment belongs to.
out.worldPos = position.xy;
return out;
}
@fragment
fn fs_checker(input: CheckerVertexOutput) -> @location(0) vec4<f32> {
// Cell size in world units = GRID_SIZE / GRID_DIVISIONS per axis.
// These constants are baked in at shader-creation time. For square
// checker cells both must be equal (here 200/20 = 300/30 = 10).
let cellSizeX = ${GRID_SIZE_X.toFixed(1)} / ${GRID_DIVISIONS_X}.0;
let cellSizeY = ${GRID_SIZE_Y.toFixed(1)} / ${GRID_DIVISIONS_Y}.0;
// Integer cell coordinates: which cell does this fragment fall in?
let cx = floor(input.worldPos.x / cellSizeX);
let cy = floor(input.worldPos.y / cellSizeY);
// (cx + cy) % 2 alternates between 0 and 1 for adjacent cells,
// producing the classic checkerboard pattern.
let checker = (cx + cy) % 2.0;
// Two shades of gray for the checkerboard squares. The values are
// chosen to be subtle — the grid is a background reference, not the
// foreground object. Alpha = 0.35 makes it semi-transparent so the
// canvas background shows through.
let lightSquare = vec3<f32>(0.62, 0.63, 0.67);
let darkSquare = vec3<f32>(0.52, 0.53, 0.57);
let color = select(darkSquare, lightSquare, checker > 0.5);
// Premultiplied alpha output.
let alpha = 0.35;
return vec4<f32>(color * alpha, alpha);
}
// ── Label pipeline ──
// Uses a separate uniform struct with viewProj + text color.
struct LabelUniforms {
viewProj: mat4x4<f32>,
color: vec3<f32>,
_pad: f32,
};
@group(0) @binding(0) var<uniform> labelUniforms: LabelUniforms;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@group(0) @binding(2) var atlasSampler: sampler;
struct LabelVertexInput {
@location(0) position: vec3<f32>,
@location(1) uv: vec2<f32>,
};
struct LabelVertexOutput {
@builtin(position) clipPosition: vec4<f32>,
@location(0) uv: vec2<f32>,
};
@vertex
fn vs_label(input: LabelVertexInput) -> LabelVertexOutput {
var out: LabelVertexOutput;
out.clipPosition = labelUniforms.viewProj * vec4<f32>(input.position, 1.0);
out.uv = input.uv;
return out;
}
@fragment
fn fs_label(input: LabelVertexOutput) -> @location(0) vec4<f32> {
// Sample the glyph atlas. The atlas is white text on transparent
// background, so the red channel encodes the glyph coverage (alpha).
let sampled = textureSample(atlas, atlasSampler, input.uv);
let alpha = sampled.r * 0.7;
// Premultiplied alpha: color * alpha.
return vec4<f32>(labelUniforms.color * alpha, alpha);
}
`;
// ─────────────────────────────────────────────────────────────────────
// Per-canvas initialization
// ─────────────────────────────────────────────────────────────────────
// Called once for each <canvas class="nav-grid-canvas"> on the page.
// Sets up the WebGPU device, pipelines, geometry buffers, glyph atlas,
// interaction, and starts the render loop. All GPU resources are
// captured in the closure so the render loop can access them without
// global state.
async function initCanvas(canvas) {
// --- WebGPU bootstrap ---
// navigator.gpu is the entry point. If it's missing, the browser
// does not support WebGPU at all (e.g. Firefox without flags, or
// an older browser). We replace the canvas with a text node so the
// page doesn't show a broken empty rectangle.
if (!navigator.gpu) {
canvas.replaceWith(document.createTextNode('WebGPU is not supported in this browser.'));
return;
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
canvas.replaceWith(document.createTextNode('No WebGPU adapter available.'));
return;
}
const device = await adapter.requestDevice();
// Configure the canvas's WebGPU context. alphaMode: 'premultiplied'
// lets the canvas blend with the page background — important here
// because the checkerboard and labels are semi-transparent and we
// want the canvas background (white) to show through. All fragment
// shaders output premultiplied alpha to match this mode.
const ctx = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();
ctx.configure({ device, format, alphaMode: 'premultiplied' });
// Compile the WGSL shader into a shader module.
const shader = device.createShaderModule({ code: SHADER });
// --- Blend state (premultiplied alpha) ---
// With premultiplied alpha, the fragment shader outputs
// (color * alpha, alpha) and the blend state uses srcFactor: 'one'
// (not 'src-alpha'). This is the correct blend setup for
// alphaMode: 'premultiplied' on the canvas. Using straight-alpha
// blending here would double-darken the alpha channel, making
// semi-transparent objects nearly invisible.
const blendState = {
color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },
alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha', operation: 'add' },
};
// --- Pipelines ---
// Three render pipelines sharing the same shader module:
// checkerPipeline — renders the checkerboard quad (triangles)
// linePipeline — renders grid lines, axes, ticks (lines)
// labelPipeline — renders numeric tick labels (textured triangles)
//
// The checker and line pipelines use layout: 'auto' and share a
// single uniform buffer (viewProj only, 64 bytes). The label
// pipeline has its own bind group layout because it needs the
// atlas texture and sampler in addition to a uniform buffer
// (viewProj + color, 80 bytes).
//
// All pipelines use depthWriteEnabled: false so the grid doesn't
// occlude other geometry that might be drawn after it. In a full
// 3D viewer the grid is drawn first, then the toolpath / model on
// top. depthCompare: 'less' still tests against the depth buffer
// so geometry drawn before the grid can occlude it.
// Checkerboard pipeline: renders a single quad, pattern in fragment shader.
const checkerPipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: shader, entryPoint: 'vs_checker',
// Position only: 3 floats per vertex = 12 bytes.
buffers: [{
arrayStride: 12,
attributes: [{ shaderLocation: 0, offset: 0, format: 'float32x3' }],
}],
},
fragment: {
module: shader, entryPoint: 'fs_checker',
targets: [{ format, blend: blendState }],
},
primitive: { topology: 'triangle-list', cullMode: 'none' },
depthStencil: { format: 'depth24plus', depthCompare: 'less', depthWriteEnabled: false },
});
// Grid-line pipeline: renders line-list with per-vertex colors.
const linePipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: shader, entryPoint: 'vs_line',
// Interleaved layout: position (float32x3) + color (float32x3)
// = 24 bytes per vertex.
buffers: [{
arrayStride: 24,
attributes: [
{ shaderLocation: 0, offset: 0, format: 'float32x3' },
{ shaderLocation: 1, offset: 12, format: 'float32x3' },
],
}],
},
fragment: {
module: shader, entryPoint: 'fs_line',
targets: [{ format, blend: blendState }],
},
primitive: { topology: 'line-list' },
depthStencil: { format: 'depth24plus', depthCompare: 'less', depthWriteEnabled: false },
});
// --- Glyph atlas ---
// Generate the bitmap atlas on a 2D canvas and upload as a WebGPU
// texture. The atlas is a single horizontal strip of white glyphs
// on transparent background. The label fragment shader samples it
// and uses the red channel as alpha.
const { atlasCanvas, atlasW, atlasH, glyphMap } = buildGlyphAtlas();
const atlasTexture = device.createTexture({
size: [atlasW, atlasH],
format: 'rgba8unorm',
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
});
device.queue.copyExternalImageToTexture(
{ source: atlasCanvas },
{ texture: atlasTexture },
[atlasW, atlasH],
);
const atlasSampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
});
// Label pipeline: renders textured quads using the glyph atlas.
// Has its own bind group layout because it needs texture + sampler
// bindings in addition to the uniform buffer.
const labelPipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: shader, entryPoint: 'vs_label',
// Position (float32x3) + UV (float32x2) = 20 bytes per vertex.
buffers: [{
arrayStride: 20,
attributes: [
{ shaderLocation: 0, offset: 0, format: 'float32x3' },
{ shaderLocation: 1, offset: 12, format: 'float32x2' },
],
}],
},
fragment: {
module: shader, entryPoint: 'fs_label',
targets: [{ format, blend: blendState }],
},
primitive: { topology: 'triangle-list' },
depthStencil: { format: 'depth24plus', depthCompare: 'less', depthWriteEnabled: false },
});
// --- Upload geometry to GPU buffers ---
// All geometry is static — uploaded once, never modified.
// Checkerboard quad: 6 vertices × 3 floats × 4 bytes = 72 bytes.
const checkerVerts = buildCheckerQuad();
const checkerVbuf = device.createBuffer({
size: checkerVerts.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(checkerVbuf, 0, checkerVerts);
// Grid lines: interleaved [x,y,z, r,g,b] per vertex.
const lineVerts = buildGridLines();
const lineVbuf = device.createBuffer({
size: lineVerts.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(lineVbuf, 0, lineVerts);
// Label quads: interleaved [x,y,z, u,v] per vertex.
const labelVerts = buildLabelVertices(glyphMap);
const labelVbuf = device.createBuffer({
size: labelVerts.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(labelVbuf, 0, labelVerts);
// --- Uniform buffers ---
// Checker + line pipelines share a 64-byte uniform buffer
// (viewProj only). The label pipeline has its own 80-byte uniform
// buffer (viewProj + color + pad).
const ubuf = device.createBuffer({
size: 64,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const checkerBindGroup = device.createBindGroup({
layout: checkerPipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: ubuf } }],
});
const lineBindGroup = device.createBindGroup({
layout: linePipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: ubuf } }],
});
// Label uniform buffer: 64 bytes (viewProj) + 12 bytes (color) + 4 bytes (pad) = 80 bytes.
const labelUbuf = device.createBuffer({
size: 80,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const labelBindGroup = device.createBindGroup({
layout: labelPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: labelUbuf } },
{ binding: 1, resource: atlasTexture.createView() },
{ binding: 2, resource: atlasSampler },
],
});
// --- Depth texture ---
// Recreated whenever the canvas size changes. Required because all
// pipelines declare a depthStencil state (even with depthWriteEnabled:
// false, WebGPU still needs a depth attachment if the pipeline
// specifies one).
let depthTex = null;
function ensureDepth(w, h) {
if (depthTex && depthTex.width === w && depthTex.height === h) return;
if (depthTex) depthTex.destroy();
depthTex = device.createTexture({
size: [w, h, 1], format: 'depth24plus', usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
}
// --- Interaction: orbit camera ---
// The camera orbits the origin using spherical coordinates:
// yaw — horizontal angle (drag left/right)
// pitch — vertical angle (drag up/down), clamped to (0, π/2)
// dist — distance from origin (mouse wheel)
//
// We convert (yaw, pitch, dist) to a Cartesian eye position and feed
// it to mat4LookAt. Up is always +Z (CAD convention: Z is up).
//
// setPointerCapture ensures we keep receiving pointermove events
// even if the pointer leaves the canvas while dragging.
let yaw = Math.PI / 4, pitch = Math.PI / 3.5, dist = 400;
let dragging = false, lastX = 0, lastY = 0;
canvas.style.cursor = 'grab';
canvas.style.touchAction = 'none'; // prevent scrolling on touch devices
canvas.addEventListener('pointerdown', (e) => {
dragging = true; lastX = e.clientX; lastY = e.clientY;
canvas.setPointerCapture(e.pointerId);
canvas.style.cursor = 'grabbing';
});
canvas.addEventListener('pointerup', () => {
dragging = false; canvas.style.cursor = 'grab';
});
canvas.addEventListener('pointermove', (e) => {
if (!dragging) return;
const dx = e.clientX - lastX, dy = e.clientY - lastY;
lastX = e.clientX; lastY = e.clientY;
// 0.01 rad per pixel — a full screen-width drag ≈ 6.3 rad ≈ 360°.
yaw -= dx * 0.01;
pitch += dy * 0.01;
// Clamp pitch to (0.05, π/2 - 0.05) so the camera never goes
// below the grid plane and never looks straight down (which would
// make the grid degenerate to a square).
pitch = Math.max(0.05, Math.min(Math.PI / 2 - 0.05, pitch));
});
// Mouse wheel zoom: adjust the orbit radius. The factor 1.1 per
// wheel notch gives a smooth zoom feel. We clamp dist to [50, 2000]
// so the user can't zoom in past the grid or out past the far plane.
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const factor = e.deltaY > 0 ? 1.1 : 1 / 1.1;
dist = Math.max(50, Math.min(2000, dist * factor));
}, { passive: false });
// --- Render loop ---
// Runs once per animation frame via requestAnimationFrame. Each
// frame:
// 1. Resize canvas + depth texture if the CSS size changed.
// 2. Compute the orbit camera position and view-projection matrix.
// 3. Upload the view-projection to the uniform buffers.
// 4. Record a render pass: draw checkerboard, grid lines, labels.
// 5. Submit and schedule the next frame.
function frame() {
// Handle HiDPI: render at devicePixelResolution but cap at 2× to
// avoid excessive fill rate on high-DPI phones.
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const cw = Math.max(1, Math.floor(canvas.clientWidth * dpr));
const ch = Math.max(1, Math.floor(canvas.clientHeight * dpr));
if (canvas.width !== cw || canvas.height !== ch) {
canvas.width = cw; canvas.height = ch;
}
ensureDepth(cw, ch);
// Convert spherical orbit coordinates to a Cartesian eye position.
// x = dist * cos(pitch) * cos(yaw)
// y = dist * cos(pitch) * sin(yaw)
// z = dist * sin(pitch)
// With up = +Z, this places the camera above the XY plane looking
// down at the grid at an angle. The default yaw=45°, pitch≈51°
// gives a standard CAD isometric-ish view.
const eye = {
x: dist * Math.cos(pitch) * Math.cos(yaw),
y: dist * Math.cos(pitch) * Math.sin(yaw),
z: dist * Math.sin(pitch),
};
// Build the view-projection matrix:
// viewProj = proj * view
// where:
// proj = perspective(45°, aspect, 0.1, 10000)
// view = lookAt(eye, origin, +Z)
//
// The far plane (10000) is generous so the grid is never clipped
// even when zoomed out to dist = 2000.
const aspect = cw / ch;
const proj = mat4Perspective(Math.PI / 4, aspect, 0.1, 10000);
const view = mat4LookAt(eye, { x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 1 });
const viewProj = mat4Multiply(proj, view);
// Upload viewProj to the checker/line uniform buffer (64 bytes).
device.queue.writeBuffer(ubuf, 0, viewProj);
// Upload viewProj + label color to the label uniform buffer (80 bytes).
// Layout: [viewProj (16 floats)] [color (3 floats)] [pad (1 float)]
const labelUniform = new Float32Array(20);
labelUniform.set(viewProj, 0);
labelUniform[16] = LABEL_COLOR[0];
labelUniform[17] = LABEL_COLOR[1];
labelUniform[18] = LABEL_COLOR[2];
labelUniform[19] = 0; // pad
device.queue.writeBuffer(labelUbuf, 0, labelUniform);
// Record the render pass. Clear to transparent (alpha = 0) so
// the canvas's CSS background shows through. The depth buffer is
// cleared to 1.0 (farthest).
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [{
view: ctx.getCurrentTexture().createView(),
clearValue: { r: 0, g: 0, b: 0, a: 0 },
loadOp: 'clear', storeOp: 'store',
}],
depthStencilAttachment: {
view: depthTex.createView(),
depthClearValue: 1.0, depthLoadOp: 'clear', depthStoreOp: 'store',
},
});
// Pass 1: draw the checkerboard quad (6 vertices = 2 triangles).
// Drawn first so the grid lines and labels render on top of it.
pass.setPipeline(checkerPipeline);
pass.setBindGroup(0, checkerBindGroup);
pass.setVertexBuffer(0, checkerVbuf);
pass.draw(6);
// Pass 2: draw all grid lines, axis edges, and tick marks.
// lineVerts is interleaved [x,y,z, r,g,b], so vertex count =
// array length / 6.
pass.setPipeline(linePipeline);
pass.setBindGroup(0, lineBindGroup);
pass.setVertexBuffer(0, lineVbuf);
pass.draw(lineVerts.length / 6);
// Pass 3: draw the numeric tick labels (textured quads).
// labelVerts is interleaved [x,y,z, u,v], so vertex count =
// array length / 5.
pass.setPipeline(labelPipeline);
pass.setBindGroup(0, labelBindGroup);
pass.setVertexBuffer(0, labelVbuf);
pass.draw(labelVerts.length / 5);
pass.end();
device.queue.submit([encoder.finish()]);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
// ─────────────────────────────────────────────────────────────────────
// Auto-initialization
// ─────────────────────────────────────────────────────────────────────
// Find every <canvas class="nav-grid-canvas"> on the page and
// initialize it. If the document is still loading (script ran from
// <head> or with defer), wait for DOMContentLoaded so the canvases
// exist. If the document is already ready (script injected late),
// initialize immediately.
function initAll() {
document.querySelectorAll('canvas.nav-grid-canvas').forEach(initCanvas);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initAll);
} else {
initAll();
}
})();Скрипт і вбудований лістинг вище ідентичні й обидва випущені
під CC0-1.0. Реалізація — порт без залежностей GridRenderer і
GridLabelRenderer з проєкту WebGCodeViewer. Оригінал також
підтримує динамічне рецентрування на bounding box; це опущено тут
для ясності. Ключові техніки (процедурна шахівниця у фрагментному
шейдері, геометрія сітки line-list, підписи масштабу з атласу
гліфів, premultiplied alpha-blended оверлей із вимкненим записом
глибини) ті самі.