O nosso rasterizador, agora por trás da API do WebGL2, no webgl2-cpu.js. Quem desenha ainda é a CPU; o programa só manda os dados (buffers, texturas, uniforms) e escolhe os shaders, que aqui são funções JavaScript.
Primeiro, o cubo com textura: um vertex shader que leva cada vértice para a tela e um fragment shader que só lê a cor da textura.
// O cubo com textura do capítulo de texturas, agora pelo WebGL2 na CPU (o webgl2-cpu.js, na outra aba).
// O cubo, as instâncias da cena e o laço de desenho são os mesmos dos outros capítulos;
// o que muda é o render: em vez de preencher os triângulos, ele chama o WebGL.
// Sem luz: o vertex shader leva cada vértice para a tela e o fragment shader só lê a cor da textura.
import { createContext, texture } from "./webgl2-cpu.js";
class Matrix4 {
// novo: a matriz pode nascer das suas linhas (é assim que o shader recebe um uniform mat4)
constructor(
body = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
]
) {
this.body = body;
}
multV(vector) {
let matrix = this.body;
let vec = [vector.x, vector.y, vector.z, vector.w];
if (!vector.w) vec[3] = 1;
let result = [];
for (let i = 0; i < matrix.length; i++) {
let pos = 0;
for (let j = 0; j < matrix[i].length; j++) {
pos += matrix[i][j] * vec[j];
}
result[i] = pos;
}
return new Vector4f(result[0], result[1], result[2], result[3]);
}
multM(matrix) {
let prevMatrix = this.body;
let result = new Matrix4();
for (let i = 0; i < prevMatrix.length; i++) {
for (let j = 0; j < prevMatrix.length; j++) {
for (let k = 0; k < prevMatrix.length; k++) {
result.body[i][j] += prevMatrix[i][k] * matrix.body[k][j];
}
}
}
this.body = result.body;
return this;
}
Translate(translation) {
const { x, y, z } = translation;
this.body = [
[1, 0, 0, x],
[0, 1, 0, y],
[0, 0, 1, z],
[0, 0, 0, 1],
];
return this;
}
Scale(scale) {
const { x, y, z } = scale;
this.body = [
[x, 0, 0, 0],
[0, y, 0, 0],
[0, 0, z, 0],
[0, 0, 0, 1],
];
return this;
}
RotateY(rotationVector) {
const { y: angle } = rotationVector;
this.body = [
[Math.cos(angle), 0, Math.sin(angle), 0],
[0, 1, 0, 0],
[-Math.sin(angle), 0, Math.cos(angle), 0],
[0, 0, 0, 1],
];
return this;
}
// novo: a projeção do WebGL. É a nossa Projection, com duas mudanças:
// - x e y saem divididos pela metade do plano de projeção, então o que aparece na tela fica entre -1 e 1
// - z sai entre -1 (no near) e 1 (no far) depois da divisão por w, para o teste de profundidade
// w continua sendo o z do ponto: a GPU divide x, y e z por ele
Perspective(planeDistance, planeWidth, planeHeight, near, far) {
this.body = [
[(2 * planeDistance) / planeWidth, 0, 0, 0],
[0, (2 * planeDistance) / planeHeight, 0, 0],
[0, 0, (far + near) / (far - near), (-2 * far * near) / (far - near)],
[0, 0, 1, 0],
];
return this;
}
}
class Vector {
constructor(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
}
class Vector3f extends Vector {}
class Vector4f extends Vector {}
// novo: no shader, um vec3 é uma lista de três números
const vec3 = ([x, y, z]) => new Vector3f(x, y, z);
// o cubo dos outros capítulos; cada triângulo diz de que parte da textura em cruz ele sai
const cube = {
vertices: [
{ x: -1, y: 1, z: -1 }, // a 0
{ x: 1, y: 1, z: -1 }, // b 1
{ x: 1, y: -1, z: -1 }, // c 2
{ x: -1, y: -1, z: -1 }, // d 3
{ x: -1, y: 1, z: 1 }, // e 4
{ x: 1, y: 1, z: 1 }, // f 5
{ x: 1, y: -1, z: 1 }, // g 6
{ x: -1, y: -1, z: 1 }, // h 7
],
meshes: [
{
// abd: frente
vertices: [0, 1, 3],
textureCoords: [
[0.25, 0.333],
[0.5, 0.333],
[0.25, 0.666],
],
},
{
// bcd
vertices: [1, 2, 3],
textureCoords: [
[0.5, 0.333],
[0.5, 0.666],
[0.25, 0.666],
],
},
{
// bgc: direita
vertices: [1, 6, 2],
textureCoords: [
[0.5, 0.333],
[0.75, 0.666],
[0.5, 0.666],
],
},
{
// bfg
vertices: [1, 5, 6],
textureCoords: [
[0.5, 0.333],
[0.75, 0.333],
[0.75, 0.666],
],
},
{
// eah: esquerda
vertices: [4, 0, 7],
textureCoords: [
[0, 0.333],
[0.25, 0.333],
[0, 0.666],
],
},
{
// adh
vertices: [0, 3, 7],
textureCoords: [
[0.25, 0.333],
[0.25, 0.666],
[0, 0.666],
],
},
{
// dch: baixo
vertices: [3, 2, 7],
textureCoords: [
[0.25, 0.666],
[0.5, 0.666],
[0.25, 1],
],
},
{
// hcg
vertices: [7, 2, 6],
textureCoords: [
[0.25, 1],
[0.5, 0.666],
[0.5, 1],
],
},
{
// aeb: cima
vertices: [0, 4, 1],
textureCoords: [
[0.25, 0.333],
[0.25, 0],
[0.5, 0.333],
],
},
{
// efb
vertices: [4, 5, 1],
textureCoords: [
[0.25, 0],
[0.5, 0],
[0.5, 0.333],
],
},
{
// feh: trás
vertices: [5, 4, 7],
textureCoords: [
[0.75, 0.333],
[1, 0.333],
[1, 0.666],
],
},
{
// fhg
vertices: [5, 7, 6],
textureCoords: [
[0.75, 0.333],
[1, 0.666],
[0.75, 0.666],
],
},
],
};
const instance = {
model: cube,
transform: {
position: new Vector3f(0, -1.3, 7), // um pouco abaixo da câmera, para vermos a face de cima
scale: new Vector3f(1, 1, 1),
rotation: new Vector3f(0, 1, 0),
},
};
let sceneInstances = [instance];
// ---------------------------------------------------------------------------------------------
// os shaders
const vertexShader = ({ aPosition, aTexCoord }, u) => {
const position = new Matrix4(u.uModel).multV(vec3(aPosition)); // o vértice na cena
const clip = new Matrix4(u.uProjection).multV(position);
return {
gl_Position: [clip.x, clip.y, clip.z, clip.w],
vTexCoord: aTexCoord,
};
};
const fragmentShader = ({ vTexCoord }, u) => texture(u.uTexture, vTexCoord);
// ---------------------------------------------------------------------------------------------
// daqui para baixo, só chamadas do WebGL
const canvas = document.getElementById("canvas");
const gl = createContext(canvas); // na GPU de verdade: canvas.getContext("webgl2")
const compileShader = (type, source) => {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
return shader;
};
const program = gl.createProgram();
gl.attachShader(program, compileShader(gl.VERTEX_SHADER, vertexShader));
gl.attachShader(program, compileShader(gl.FRAGMENT_SHADER, fragmentShader));
gl.linkProgram(program);
gl.useProgram(program);
const PLANE_DISTANCE = 1;
const PLANE_WIDTH = canvas.width / canvas.height;
const PLANE_HEIGHT = 1;
const NEAR = 0.3;
const FAR = 100;
const projection = new Matrix4().Perspective(PLANE_DISTANCE, PLANE_WIDTH, PLANE_HEIGHT, NEAR, FAR);
gl.uniformMatrix4fv(gl.getUniformLocation(program, "uProjection"), true, projection.body.flat()); // true: linha por linha
gl.uniform1i(gl.getUniformLocation(program, "uTexture"), 0); // o sampler lê a unidade de textura 0
gl.clearColor(1, 1, 1, 1);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
gl.frontFace(gl.CW); // nos nossos modelos, a frente do triângulo tem os vértices em sentido horário na tela
// os triângulos do modelo viram listas de números, uma por atributo, com três vértices por triângulo,
// e o vertex array diz de qual buffer sai cada atributo
const uploadModel = (instance) => {
const positions = [];
const texCoords = [];
for (const mesh of instance.model.meshes) {
for (let i = 0; i < 3; i++) {
const vertex = instance.model.vertices[mesh.vertices[i]];
positions.push(vertex.x, vertex.y, vertex.z);
texCoords.push(...mesh.textureCoords[i]);
}
}
instance.vertexArray = gl.createVertexArray();
gl.bindVertexArray(instance.vertexArray);
const attribute = (name, values, size) => {
const location = gl.getAttribLocation(program, name);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(values), gl.STATIC_DRAW);
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, size, gl.FLOAT, false, 0, 0);
};
attribute("aPosition", positions, 3);
attribute("aTexCoord", texCoords, 2);
};
// o render de sempre: cada instância com a sua matriz (escala, rotação e posição)
const render = () => {
sceneInstances.forEach((instance) => {
const { position, scale, rotation } = instance.transform;
const scaling = new Matrix4().Scale(scale);
const rotating = new Matrix4().RotateY(rotation);
const translating = new Matrix4().Translate(position);
const model = translating.multM(rotating.multM(scaling));
gl.uniformMatrix4fv(gl.getUniformLocation(program, "uModel"), true, model.body.flat());
gl.bindVertexArray(instance.vertexArray);
gl.drawArrays(gl.TRIANGLES, 0, instance.model.meshes.length * 3);
});
};
let i = 1;
const draw = () => {
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
render();
i += 0.01;
instance.transform.rotation = new Vector3f(0, i, 0);
requestAnimationFrame(draw);
};
const image = new Image();
image.onload = () => {
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); // sem mipmaps
sceneInstances.forEach(uploadModel);
draw();
};
image.src = "/images/rasterizer/texturing/texture-target.png";
// WebGL2 na CPU: um pedaço da API do WebGL2, mas quem desenha é o nosso rasterizador.
// O programa não desenha nada: ele manda dados (buffers, texturas, uniforms) e escolhe os shaders,
// que aqui são funções JavaScript no lugar do texto em GLSL. O resto do caminho é fixo:
//
// atributos → vertex shader → descarte → divisão por w → viewport → culling →
// rasterização (interpolando as varyings) → teste de profundidade → fragment shader → pixel
//
// Para usar a GPU de verdade, troca-se createContext(canvas) por canvas.getContext("webgl2")
// e as funções dos shaders por GLSL.
// as mesmas constantes (e os mesmos números) do WebGL2
const GL = {
DEPTH_BUFFER_BIT: 0x0100,
COLOR_BUFFER_BIT: 0x4000,
TRIANGLES: 0x0004,
CW: 0x0900,
CCW: 0x0901,
CULL_FACE: 0x0b44,
DEPTH_TEST: 0x0b71,
TEXTURE_2D: 0x0de1,
TEXTURE0: 0x84c0,
TEXTURE_MIN_FILTER: 0x2801,
LINEAR: 0x2601,
RGBA: 0x1908,
UNSIGNED_BYTE: 0x1401,
FLOAT: 0x1406,
ARRAY_BUFFER: 0x8892,
STATIC_DRAW: 0x88e4,
FRAGMENT_SHADER: 0x8b30,
VERTEX_SHADER: 0x8b31,
// nomes do estado, para o getParameter
CURRENT_PROGRAM: 0x8b8d,
VERTEX_ARRAY_BINDING: 0x85b5,
ARRAY_BUFFER_BINDING: 0x8894,
ACTIVE_TEXTURE: 0x84e0,
TEXTURE_BINDING_2D: 0x8069,
COLOR_CLEAR_VALUE: 0x0c22,
FRONT_FACE: 0x0b46,
};
// ---------------------------------------------------------------------------------------------
// o nosso rasterizador, igual ao dos capítulos anteriores
const interpolate = (i0, i1, d0, d1) => {
if (i0 === i1) {
return [d0];
}
let values = [];
let a = (d1 - d0) / (i1 - i0);
let d = d0;
for (let i = i0; i <= i1; i++) {
values.push(d);
d += a;
}
return values;
};
const isBiggerEdgeAtLeftSide = (x02, x12) => {
const midIndex = (x12.length / 2) | 0;
return x02[midIndex] < x12[midIndex];
};
const buildInterpolatedEdgeValues = (i0, i1, i2, d0, d1, d2) => {
const i12 = interpolate(i1, i2, d1, d2);
const i01 = interpolate(i0, i1, d0, d1);
const i02 = interpolate(i0, i2, d0, d2);
i01.pop();
const smaller = [...i01, ...i12];
return {
smallEdge: smaller,
bigEdge: i02,
};
};
// ---------------------------------------------------------------------------------------------
// texturas: cada unidade (TEXTURE0, TEXTURE1...) guarda a textura ligada a ela.
// ponytail: uma GPU por página; as unidades ficam aqui para o texture() dos shaders enxergar
const units = [];
const wrap = (i, size) => ((i % size) + size) % size; // REPEAT: a coordenada dá a volta
// o texture() do GLSL: o getTexel da Sting (filtro bilinear), devolvendo [r, g, b, a] de 0 a 1.
// No shader, um sampler2D é só o número da unidade
export const texture = (unit, [u, v]) => {
const image = units[unit];
if (!image?.data) return [0, 0, 0, 1]; // como no WebGL: textura vazia é preta
const { width: iw, height: ih, data } = image;
let tx = u * iw;
let ty = v * ih;
const fx = tx - Math.floor(tx);
const fy = ty - Math.floor(ty);
tx = Math.floor(tx);
ty = Math.floor(ty);
const texel = (x, y) => (wrap(y, ih) * iw + wrap(x, iw)) * 4;
const [TL, TR, BL, BR] = [texel(tx, ty), texel(tx + 1, ty), texel(tx, ty + 1), texel(tx + 1, ty + 1)];
const color = [];
for (let i = 0; i < 4; i++) {
const CT = fx * data[TR + i] + (1 - fx) * data[TL + i];
const CB = fx * data[BR + i] + (1 - fx) * data[BL + i];
color.push((fy * CB + (1 - fy) * CT) / 255);
}
return color;
};
// ---------------------------------------------------------------------------------------------
// não existe no WebGL: é por aqui que o passo a passo olha a "GPU" trabalhando, como uma ferramenta
// de depuração. onCall roda depois de cada chamada do gl; onDraw roda dentro do drawArrays,
// depois do vertex shader e depois de cada triângulo
export const inspector = { onCall: null, onDraw: null };
// ---------------------------------------------------------------------------------------------
// o contexto: o objeto "gl"
export const createContext = (canvas) => {
const context = canvas.getContext("2d");
const { width, height } = canvas;
const canvasBuffer = context.createImageData(width, height); // começa transparente, como no WebGL
const zBuffer = Array(width * height).fill(1); // o depth buffer: 0 é o near, 1 é o far
units.length = 0; // um contexto novo começa sem texturas
const blit = () => {
context.putImageData(canvasBuffer, 0, 0);
};
blit();
// o índice de um pixel, com a origem no centro do canvas como no nosso putPixel; -1 se cair fora
const pixelIndex = (x, y) => {
const canvasX = (width / 2 + x) | 0;
const canvasY = (height / 2 - y) | 0;
if (canvasX < 0 || canvasX >= width || canvasY < 0 || canvasY >= height) return -1;
return canvasX + canvasY * width;
};
// o estado do WebGL: o que está ligado agora
let program = null;
const defaultVertexArray = { attributes: [] }; // o WebGL2 já começa com um vertex array
let vertexArray = defaultVertexArray;
let arrayBuffer = null;
let activeUnit = 0;
let clearColor = [0, 0, 0, 0];
let frontFace = GL.CCW;
const enabled = new Set();
// o nosso fillTriangle (o do Phong), para qualquer lista de valores: cada vértice traz a
// profundidade, 1/w e cada componente de cada varying dividido por w (como u/z e v/z nas texturas)
const fillTriangle = (vertices, layout) => {
const [p0, p1, p2] = vertices.sort((a, b) => a.y - b.y);
const { bigEdge: x02, smallEdge: x12 } = buildInterpolatedEdgeValues(p0.y, p1.y, p2.y, p0.x, p1.x, p2.x);
const edges = p0.values.map((_, k) =>
buildInterpolatedEdgeValues(p0.y, p1.y, p2.y, p0.values[k], p1.values[k], p2.values[k])
);
// ordena os lados interpolados para iterar da esquerda para a direita
const bigAtLeft = isBiggerEdgeAtLeftSide(x02, x12);
const [xLeft, xRight] = bigAtLeft ? [x02, x12] : [x12, x02];
const valuesLeft = edges.map((edge) => (bigAtLeft ? edge.bigEdge : edge.smallEdge));
const valuesRight = edges.map((edge) => (bigAtLeft ? edge.smallEdge : edge.bigEdge));
let fragments = 0; // pixels pintados
let hidden = 0; // pixels que perderam no teste de profundidade
for (let y = p0.y; y <= p2.y; y++) {
const row = y - p0.y;
const [xFloor, xCeiling] = [xLeft[row] | 0, xRight[row] | 0];
const scans = valuesLeft.map((left, k) => interpolate(xFloor, xCeiling, left[row], valuesRight[k][row]));
for (let x = xFloor; x <= xCeiling; x++) {
const index = pixelIndex(x, y);
if (index < 0) continue;
const i = x - xFloor;
const depth = scans[0][i];
// o teste de profundidade vem antes do fragment shader: a GPU também adianta ele quando
// o shader não mexe na profundidade, e assim não calculamos a luz de um pixel escondido
if (enabled.has(GL.DEPTH_TEST) && !(depth < zBuffer[index])) {
hidden++;
continue;
}
// de v/w de volta para v: divide por 1/w
const oneOverW = scans[1][i];
const varyings = {};
let k = 2;
for (const [name, size] of layout) {
const components = scans.slice(k, k + (size || 1)).map((scan) => scan[i] / oneOverW);
varyings[name] = size ? components : components[0];
k += size || 1;
}
const [r, g, b] = program.fragmentShader(varyings, program.uniforms);
canvasBuffer.data.set([r * 255, g * 255, b * 255, 255], index * 4);
if (enabled.has(GL.DEPTH_TEST)) zBuffer[index] = depth;
fragments++;
}
}
return { fragments, hidden };
};
// devolve o que aconteceu com o triângulo (para o inspector)
const drawTriangle = (triangle) => {
// ponytail: sem recorte de verdade ainda. Como na Sting, um vértice antes do near (ou atrás da
// câmera) descarta o triângulo inteiro; o recorte contra os planos fica para o capítulo de clipping
if (triangle.some(({ gl_Position: [, , z, w] }) => z < -w)) return { result: "near" };
// culling: o mesmo produto vetorial do nosso culling, mas com os pontos já na tela.
// Pela ordem dos vértices na tela (horário ou anti-horário) sabemos para que lado o triângulo olha
const ndc = triangle.map(({ gl_Position: [x, y, , w] }) => [x / w, y / w]);
const [a, b, c] = ndc;
const area = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
const isFront = frontFace === GL.CCW ? area > 0 : area < 0;
if (enabled.has(GL.CULL_FACE) && !isFront) return { result: "culled", ndc };
// divide por w e leva de -1..1 para os pixels do canvas (o viewport). A profundidade vai de -1..1 para 0..1
const vertices = triangle.map(({ gl_Position: [x, y, z, w], ...varyings }) => ({
x: Math.floor((x / w) * (width / 2)),
y: Math.floor((y / w) * (height / 2)),
values: [
(z / w + 1) / 2,
1 / w,
...Object.values(varyings).flatMap((value) =>
(typeof value === "number" ? [value] : Array.from(value)).map((component) => component / w)
),
],
}));
// como na Sting: um triângulo todo fora da tela não precisa ser preenchido
if (
vertices.every((p) => p.x < -width / 2) ||
vertices.every((p) => p.x > width / 2) ||
vertices.every((p) => p.y < -height / 2) ||
vertices.every((p) => p.y > height / 2)
) return { result: "offscreen", ndc };
// o nome e o tamanho de cada varying (0 para um número), para montar de volta no fragment shader
const { gl_Position, ...varyings } = triangle[0];
const layout = Object.entries(varyings).map(([name, value]) => [name, typeof value === "number" ? 0 : value.length]);
return { result: "drawn", ndc, ...fillTriangle(vertices, layout) };
};
const gl = {
...GL,
// shaders e programas: no lugar do texto em GLSL, uma função
createShader: (type) => ({ type }),
shaderSource: (shader, source) => {
shader.source = source;
},
compileShader: () => {}, // nada para compilar: a função já está pronta
createProgram: () => ({ attributes: [], uniforms: {} }),
attachShader: (program, shader) => {
program[shader.type === GL.VERTEX_SHADER ? "vertexShader" : "fragmentShader"] = shader.source;
},
linkProgram: () => {},
useProgram: (newProgram) => {
program = newProgram;
},
// atributos: um número (location) para cada nome
getAttribLocation: (program, name) => {
if (!program.attributes.includes(name)) program.attributes.push(name);
return program.attributes.indexOf(name);
},
// uniforms: um valor por nome, o mesmo para todos os vértices e pixels de um desenho
getUniformLocation: (program, name) => ({ program, name }),
uniform1i: ({ program, name }, value) => {
program.uniforms[name] = value;
},
uniform1f: ({ program, name }, value) => {
program.uniforms[name] = value;
},
uniform3fv: ({ program, name }, values) => {
program.uniforms[name] = Array.from(values);
},
// o WebGL recebe a matriz coluna por coluna; transpose = true diz que ela vem linha por linha.
// O shader recebe as quatro linhas, como o body da nossa Matrix4
uniformMatrix4fv: ({ program, name }, transpose, values) => {
program.uniforms[name] = [0, 1, 2, 3].map((i) =>
[0, 1, 2, 3].map((j) => (transpose ? values[i * 4 + j] : values[j * 4 + i]))
);
},
// buffers: listas de números que ficam na "GPU"
createBuffer: () => ({}),
bindBuffer: (target, buffer) => {
arrayBuffer = buffer;
},
bufferData: (target, data) => {
arrayBuffer.data = data;
},
// vertex array: de qual buffer (e como) cada atributo é lido
createVertexArray: () => ({ attributes: [] }),
bindVertexArray: (newVertexArray) => {
vertexArray = newVertexArray ?? defaultVertexArray;
},
enableVertexAttribArray: (location) => {
(vertexArray.attributes[location] ??= {}).enabled = true;
},
// stride e offset em bytes, como no WebGL (um FLOAT tem 4 bytes)
vertexAttribPointer: (location, size, type, normalized, stride, offset) => {
Object.assign((vertexArray.attributes[location] ??= {}), {
buffer: arrayBuffer,
size,
stride: stride / 4 || size,
offset: offset / 4,
});
},
// texturas
createTexture: () => ({}),
activeTexture: (unit) => {
activeUnit = unit - GL.TEXTURE0;
},
bindTexture: (target, texture) => {
units[activeUnit] = texture;
},
// como o Texture.loadImage: desenha a imagem num canvas para ler os pixels
texImage2D: (target, level, internalFormat, format, type, image) => {
const imageCanvas = document.createElement("canvas");
imageCanvas.width = image.width;
imageCanvas.height = image.height;
const imageContext = imageCanvas.getContext("2d");
imageContext.drawImage(image, 0, 0);
Object.assign(units[activeUnit], {
width: image.width,
height: image.height,
data: imageContext.getImageData(0, 0, image.width, image.height).data,
});
},
texParameteri: () => {}, // ponytail: o filtro é sempre LINEAR e as bordas sempre REPEAT
// estado
enable: (capability) => enabled.add(capability),
disable: (capability) => enabled.delete(capability),
frontFace: (mode) => {
frontFace = mode;
},
clearColor: (r, g, b, a) => {
clearColor = [r, g, b, a];
},
clear: (mask) => {
if (mask & GL.COLOR_BUFFER_BIT) {
const color = clearColor.map((c) => c * 255);
for (let i = 0; i < width * height * 4; i += 4) canvasBuffer.data.set(color, i);
}
if (mask & GL.DEPTH_BUFFER_BIT) zBuffer.fill(1);
blit();
},
// desenhar: roda o vertex shader em cada vértice e preenche um triângulo a cada três.
// A GPU de verdade mostra o quadro quando o JavaScript termina; aqui mostramos a cada desenho
drawArrays: (mode, first, count) => {
const vertices = [];
for (let i = first; i < first + count; i++) {
const attributes = {};
vertexArray.attributes.forEach((attribute, location) => {
if (!attribute.enabled) return;
const start = attribute.offset + i * attribute.stride;
attributes[program.attributes[location]] = attribute.buffer.data.subarray(start, start + attribute.size);
});
vertices.push(program.vertexShader(attributes, program.uniforms));
}
const triangles = [];
inspector.onDraw?.({ vertices, triangles, image: canvasBuffer });
for (let i = 0; i + 2 < vertices.length; i += 3) {
triangles.push(drawTriangle([vertices[i], vertices[i + 1], vertices[i + 2]]));
inspector.onDraw?.({ vertices, triangles, image: canvasBuffer });
}
blit();
},
// perguntar o estado: o WebGL é uma máquina de estados, e o getParameter diz o que está ligado agora
getParameter: (name) =>
({
[GL.CURRENT_PROGRAM]: program,
[GL.VERTEX_ARRAY_BINDING]: vertexArray === defaultVertexArray ? null : vertexArray,
[GL.ARRAY_BUFFER_BINDING]: arrayBuffer,
[GL.ACTIVE_TEXTURE]: GL.TEXTURE0 + activeUnit,
[GL.TEXTURE_BINDING_2D]: units[activeUnit] ?? null,
[GL.COLOR_CLEAR_VALUE]: clearColor,
[GL.FRONT_FACE]: frontFace,
})[name],
isEnabled: (capability) => enabled.has(capability),
};
// com o inspector ligado, cada chamada do gl avisa o passo a passo
if (inspector.onCall) {
for (const [name, method] of Object.entries(gl)) {
if (typeof method !== "function") continue;
gl[name] = (...args) => {
const result = method(...args);
inspector.onCall(name, args, result, gl);
return result;
};
}
inspector.onCall("createContext", [canvas], gl, gl);
}
return gl;
};
O WebGL é uma máquina de estados: quase toda chamada liga alguma coisa (um programa, um buffer, uma textura) ou usa o que está ligado. Como a nossa “GPU” roda na CPU, dá para gravar o primeiro quadro do mesmo cubo.js e andar por ele passo a passo: a cada chamada, o estado dela, o canvas e as linhas marcadas no cubo.js e no webgl2-cpu.js. Dentro do drawArrays, o passo a passo para depois do vertex shader e depois de cada triângulo.
// O cubo com textura do capítulo de texturas, agora pelo WebGL2 na CPU (o webgl2-cpu.js, na outra aba).
// O cubo, as instâncias da cena e o laço de desenho são os mesmos dos outros capítulos;
// o que muda é o render: em vez de preencher os triângulos, ele chama o WebGL.
// Sem luz: o vertex shader leva cada vértice para a tela e o fragment shader só lê a cor da textura.
import { createContext, texture } from "./webgl2-cpu.js";
class Matrix4 {
// novo: a matriz pode nascer das suas linhas (é assim que o shader recebe um uniform mat4)
constructor(
body = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
]
) {
this.body = body;
}
multV(vector) {
let matrix = this.body;
let vec = [vector.x, vector.y, vector.z, vector.w];
if (!vector.w) vec[3] = 1;
let result = [];
for (let i = 0; i < matrix.length; i++) {
let pos = 0;
for (let j = 0; j < matrix[i].length; j++) {
pos += matrix[i][j] * vec[j];
}
result[i] = pos;
}
return new Vector4f(result[0], result[1], result[2], result[3]);
}
multM(matrix) {
let prevMatrix = this.body;
let result = new Matrix4();
for (let i = 0; i < prevMatrix.length; i++) {
for (let j = 0; j < prevMatrix.length; j++) {
for (let k = 0; k < prevMatrix.length; k++) {
result.body[i][j] += prevMatrix[i][k] * matrix.body[k][j];
}
}
}
this.body = result.body;
return this;
}
Translate(translation) {
const { x, y, z } = translation;
this.body = [
[1, 0, 0, x],
[0, 1, 0, y],
[0, 0, 1, z],
[0, 0, 0, 1],
];
return this;
}
Scale(scale) {
const { x, y, z } = scale;
this.body = [
[x, 0, 0, 0],
[0, y, 0, 0],
[0, 0, z, 0],
[0, 0, 0, 1],
];
return this;
}
RotateY(rotationVector) {
const { y: angle } = rotationVector;
this.body = [
[Math.cos(angle), 0, Math.sin(angle), 0],
[0, 1, 0, 0],
[-Math.sin(angle), 0, Math.cos(angle), 0],
[0, 0, 0, 1],
];
return this;
}
// novo: a projeção do WebGL. É a nossa Projection, com duas mudanças:
// - x e y saem divididos pela metade do plano de projeção, então o que aparece na tela fica entre -1 e 1
// - z sai entre -1 (no near) e 1 (no far) depois da divisão por w, para o teste de profundidade
// w continua sendo o z do ponto: a GPU divide x, y e z por ele
Perspective(planeDistance, planeWidth, planeHeight, near, far) {
this.body = [
[(2 * planeDistance) / planeWidth, 0, 0, 0],
[0, (2 * planeDistance) / planeHeight, 0, 0],
[0, 0, (far + near) / (far - near), (-2 * far * near) / (far - near)],
[0, 0, 1, 0],
];
return this;
}
}
class Vector {
constructor(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
}
class Vector3f extends Vector {}
class Vector4f extends Vector {}
// novo: no shader, um vec3 é uma lista de três números
const vec3 = ([x, y, z]) => new Vector3f(x, y, z);
// o cubo dos outros capítulos; cada triângulo diz de que parte da textura em cruz ele sai
const cube = {
vertices: [
{ x: -1, y: 1, z: -1 }, // a 0
{ x: 1, y: 1, z: -1 }, // b 1
{ x: 1, y: -1, z: -1 }, // c 2
{ x: -1, y: -1, z: -1 }, // d 3
{ x: -1, y: 1, z: 1 }, // e 4
{ x: 1, y: 1, z: 1 }, // f 5
{ x: 1, y: -1, z: 1 }, // g 6
{ x: -1, y: -1, z: 1 }, // h 7
],
meshes: [
{
// abd: frente
vertices: [0, 1, 3],
textureCoords: [
[0.25, 0.333],
[0.5, 0.333],
[0.25, 0.666],
],
},
{
// bcd
vertices: [1, 2, 3],
textureCoords: [
[0.5, 0.333],
[0.5, 0.666],
[0.25, 0.666],
],
},
{
// bgc: direita
vertices: [1, 6, 2],
textureCoords: [
[0.5, 0.333],
[0.75, 0.666],
[0.5, 0.666],
],
},
{
// bfg
vertices: [1, 5, 6],
textureCoords: [
[0.5, 0.333],
[0.75, 0.333],
[0.75, 0.666],
],
},
{
// eah: esquerda
vertices: [4, 0, 7],
textureCoords: [
[0, 0.333],
[0.25, 0.333],
[0, 0.666],
],
},
{
// adh
vertices: [0, 3, 7],
textureCoords: [
[0.25, 0.333],
[0.25, 0.666],
[0, 0.666],
],
},
{
// dch: baixo
vertices: [3, 2, 7],
textureCoords: [
[0.25, 0.666],
[0.5, 0.666],
[0.25, 1],
],
},
{
// hcg
vertices: [7, 2, 6],
textureCoords: [
[0.25, 1],
[0.5, 0.666],
[0.5, 1],
],
},
{
// aeb: cima
vertices: [0, 4, 1],
textureCoords: [
[0.25, 0.333],
[0.25, 0],
[0.5, 0.333],
],
},
{
// efb
vertices: [4, 5, 1],
textureCoords: [
[0.25, 0],
[0.5, 0],
[0.5, 0.333],
],
},
{
// feh: trás
vertices: [5, 4, 7],
textureCoords: [
[0.75, 0.333],
[1, 0.333],
[1, 0.666],
],
},
{
// fhg
vertices: [5, 7, 6],
textureCoords: [
[0.75, 0.333],
[1, 0.666],
[0.75, 0.666],
],
},
],
};
const instance = {
model: cube,
transform: {
position: new Vector3f(0, -1.3, 7), // um pouco abaixo da câmera, para vermos a face de cima
scale: new Vector3f(1, 1, 1),
rotation: new Vector3f(0, 1, 0),
},
};
let sceneInstances = [instance];
// ---------------------------------------------------------------------------------------------
// os shaders
const vertexShader = ({ aPosition, aTexCoord }, u) => {
const position = new Matrix4(u.uModel).multV(vec3(aPosition)); // o vértice na cena
const clip = new Matrix4(u.uProjection).multV(position);
return {
gl_Position: [clip.x, clip.y, clip.z, clip.w],
vTexCoord: aTexCoord,
};
};
const fragmentShader = ({ vTexCoord }, u) => texture(u.uTexture, vTexCoord);
// ---------------------------------------------------------------------------------------------
// daqui para baixo, só chamadas do WebGL
const canvas = document.getElementById("canvas");
const gl = createContext(canvas); // na GPU de verdade: canvas.getContext("webgl2")
const compileShader = (type, source) => {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
return shader;
};
const program = gl.createProgram();
gl.attachShader(program, compileShader(gl.VERTEX_SHADER, vertexShader));
gl.attachShader(program, compileShader(gl.FRAGMENT_SHADER, fragmentShader));
gl.linkProgram(program);
gl.useProgram(program);
const PLANE_DISTANCE = 1;
const PLANE_WIDTH = canvas.width / canvas.height;
const PLANE_HEIGHT = 1;
const NEAR = 0.3;
const FAR = 100;
const projection = new Matrix4().Perspective(PLANE_DISTANCE, PLANE_WIDTH, PLANE_HEIGHT, NEAR, FAR);
gl.uniformMatrix4fv(gl.getUniformLocation(program, "uProjection"), true, projection.body.flat()); // true: linha por linha
gl.uniform1i(gl.getUniformLocation(program, "uTexture"), 0); // o sampler lê a unidade de textura 0
gl.clearColor(1, 1, 1, 1);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
gl.frontFace(gl.CW); // nos nossos modelos, a frente do triângulo tem os vértices em sentido horário na tela
// os triângulos do modelo viram listas de números, uma por atributo, com três vértices por triângulo,
// e o vertex array diz de qual buffer sai cada atributo
const uploadModel = (instance) => {
const positions = [];
const texCoords = [];
for (const mesh of instance.model.meshes) {
for (let i = 0; i < 3; i++) {
const vertex = instance.model.vertices[mesh.vertices[i]];
positions.push(vertex.x, vertex.y, vertex.z);
texCoords.push(...mesh.textureCoords[i]);
}
}
instance.vertexArray = gl.createVertexArray();
gl.bindVertexArray(instance.vertexArray);
const attribute = (name, values, size) => {
const location = gl.getAttribLocation(program, name);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(values), gl.STATIC_DRAW);
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, size, gl.FLOAT, false, 0, 0);
};
attribute("aPosition", positions, 3);
attribute("aTexCoord", texCoords, 2);
};
// o render de sempre: cada instância com a sua matriz (escala, rotação e posição)
const render = () => {
sceneInstances.forEach((instance) => {
const { position, scale, rotation } = instance.transform;
const scaling = new Matrix4().Scale(scale);
const rotating = new Matrix4().RotateY(rotation);
const translating = new Matrix4().Translate(position);
const model = translating.multM(rotating.multM(scaling));
gl.uniformMatrix4fv(gl.getUniformLocation(program, "uModel"), true, model.body.flat());
gl.bindVertexArray(instance.vertexArray);
gl.drawArrays(gl.TRIANGLES, 0, instance.model.meshes.length * 3);
});
};
let i = 1;
const draw = () => {
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
render();
i += 0.01;
instance.transform.rotation = new Vector3f(0, i, 0);
requestAnimationFrame(draw);
};
const image = new Image();
image.onload = () => {
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); // sem mipmaps
sceneInstances.forEach(uploadModel);
draw();
};
image.src = "/images/rasterizer/texturing/texture-target.png";
// WebGL2 na CPU: um pedaço da API do WebGL2, mas quem desenha é o nosso rasterizador.
// O programa não desenha nada: ele manda dados (buffers, texturas, uniforms) e escolhe os shaders,
// que aqui são funções JavaScript no lugar do texto em GLSL. O resto do caminho é fixo:
//
// atributos → vertex shader → descarte → divisão por w → viewport → culling →
// rasterização (interpolando as varyings) → teste de profundidade → fragment shader → pixel
//
// Para usar a GPU de verdade, troca-se createContext(canvas) por canvas.getContext("webgl2")
// e as funções dos shaders por GLSL.
// as mesmas constantes (e os mesmos números) do WebGL2
const GL = {
DEPTH_BUFFER_BIT: 0x0100,
COLOR_BUFFER_BIT: 0x4000,
TRIANGLES: 0x0004,
CW: 0x0900,
CCW: 0x0901,
CULL_FACE: 0x0b44,
DEPTH_TEST: 0x0b71,
TEXTURE_2D: 0x0de1,
TEXTURE0: 0x84c0,
TEXTURE_MIN_FILTER: 0x2801,
LINEAR: 0x2601,
RGBA: 0x1908,
UNSIGNED_BYTE: 0x1401,
FLOAT: 0x1406,
ARRAY_BUFFER: 0x8892,
STATIC_DRAW: 0x88e4,
FRAGMENT_SHADER: 0x8b30,
VERTEX_SHADER: 0x8b31,
// nomes do estado, para o getParameter
CURRENT_PROGRAM: 0x8b8d,
VERTEX_ARRAY_BINDING: 0x85b5,
ARRAY_BUFFER_BINDING: 0x8894,
ACTIVE_TEXTURE: 0x84e0,
TEXTURE_BINDING_2D: 0x8069,
COLOR_CLEAR_VALUE: 0x0c22,
FRONT_FACE: 0x0b46,
};
// ---------------------------------------------------------------------------------------------
// o nosso rasterizador, igual ao dos capítulos anteriores
const interpolate = (i0, i1, d0, d1) => {
if (i0 === i1) {
return [d0];
}
let values = [];
let a = (d1 - d0) / (i1 - i0);
let d = d0;
for (let i = i0; i <= i1; i++) {
values.push(d);
d += a;
}
return values;
};
const isBiggerEdgeAtLeftSide = (x02, x12) => {
const midIndex = (x12.length / 2) | 0;
return x02[midIndex] < x12[midIndex];
};
const buildInterpolatedEdgeValues = (i0, i1, i2, d0, d1, d2) => {
const i12 = interpolate(i1, i2, d1, d2);
const i01 = interpolate(i0, i1, d0, d1);
const i02 = interpolate(i0, i2, d0, d2);
i01.pop();
const smaller = [...i01, ...i12];
return {
smallEdge: smaller,
bigEdge: i02,
};
};
// ---------------------------------------------------------------------------------------------
// texturas: cada unidade (TEXTURE0, TEXTURE1...) guarda a textura ligada a ela.
// ponytail: uma GPU por página; as unidades ficam aqui para o texture() dos shaders enxergar
const units = [];
const wrap = (i, size) => ((i % size) + size) % size; // REPEAT: a coordenada dá a volta
// o texture() do GLSL: o getTexel da Sting (filtro bilinear), devolvendo [r, g, b, a] de 0 a 1.
// No shader, um sampler2D é só o número da unidade
export const texture = (unit, [u, v]) => {
const image = units[unit];
if (!image?.data) return [0, 0, 0, 1]; // como no WebGL: textura vazia é preta
const { width: iw, height: ih, data } = image;
let tx = u * iw;
let ty = v * ih;
const fx = tx - Math.floor(tx);
const fy = ty - Math.floor(ty);
tx = Math.floor(tx);
ty = Math.floor(ty);
const texel = (x, y) => (wrap(y, ih) * iw + wrap(x, iw)) * 4;
const [TL, TR, BL, BR] = [texel(tx, ty), texel(tx + 1, ty), texel(tx, ty + 1), texel(tx + 1, ty + 1)];
const color = [];
for (let i = 0; i < 4; i++) {
const CT = fx * data[TR + i] + (1 - fx) * data[TL + i];
const CB = fx * data[BR + i] + (1 - fx) * data[BL + i];
color.push((fy * CB + (1 - fy) * CT) / 255);
}
return color;
};
// ---------------------------------------------------------------------------------------------
// não existe no WebGL: é por aqui que o passo a passo olha a "GPU" trabalhando, como uma ferramenta
// de depuração. onCall roda depois de cada chamada do gl; onDraw roda dentro do drawArrays,
// depois do vertex shader e depois de cada triângulo
export const inspector = { onCall: null, onDraw: null };
// ---------------------------------------------------------------------------------------------
// o contexto: o objeto "gl"
export const createContext = (canvas) => {
const context = canvas.getContext("2d");
const { width, height } = canvas;
const canvasBuffer = context.createImageData(width, height); // começa transparente, como no WebGL
const zBuffer = Array(width * height).fill(1); // o depth buffer: 0 é o near, 1 é o far
units.length = 0; // um contexto novo começa sem texturas
const blit = () => {
context.putImageData(canvasBuffer, 0, 0);
};
blit();
// o índice de um pixel, com a origem no centro do canvas como no nosso putPixel; -1 se cair fora
const pixelIndex = (x, y) => {
const canvasX = (width / 2 + x) | 0;
const canvasY = (height / 2 - y) | 0;
if (canvasX < 0 || canvasX >= width || canvasY < 0 || canvasY >= height) return -1;
return canvasX + canvasY * width;
};
// o estado do WebGL: o que está ligado agora
let program = null;
const defaultVertexArray = { attributes: [] }; // o WebGL2 já começa com um vertex array
let vertexArray = defaultVertexArray;
let arrayBuffer = null;
let activeUnit = 0;
let clearColor = [0, 0, 0, 0];
let frontFace = GL.CCW;
const enabled = new Set();
// o nosso fillTriangle (o do Phong), para qualquer lista de valores: cada vértice traz a
// profundidade, 1/w e cada componente de cada varying dividido por w (como u/z e v/z nas texturas)
const fillTriangle = (vertices, layout) => {
const [p0, p1, p2] = vertices.sort((a, b) => a.y - b.y);
const { bigEdge: x02, smallEdge: x12 } = buildInterpolatedEdgeValues(p0.y, p1.y, p2.y, p0.x, p1.x, p2.x);
const edges = p0.values.map((_, k) =>
buildInterpolatedEdgeValues(p0.y, p1.y, p2.y, p0.values[k], p1.values[k], p2.values[k])
);
// ordena os lados interpolados para iterar da esquerda para a direita
const bigAtLeft = isBiggerEdgeAtLeftSide(x02, x12);
const [xLeft, xRight] = bigAtLeft ? [x02, x12] : [x12, x02];
const valuesLeft = edges.map((edge) => (bigAtLeft ? edge.bigEdge : edge.smallEdge));
const valuesRight = edges.map((edge) => (bigAtLeft ? edge.smallEdge : edge.bigEdge));
let fragments = 0; // pixels pintados
let hidden = 0; // pixels que perderam no teste de profundidade
for (let y = p0.y; y <= p2.y; y++) {
const row = y - p0.y;
const [xFloor, xCeiling] = [xLeft[row] | 0, xRight[row] | 0];
const scans = valuesLeft.map((left, k) => interpolate(xFloor, xCeiling, left[row], valuesRight[k][row]));
for (let x = xFloor; x <= xCeiling; x++) {
const index = pixelIndex(x, y);
if (index < 0) continue;
const i = x - xFloor;
const depth = scans[0][i];
// o teste de profundidade vem antes do fragment shader: a GPU também adianta ele quando
// o shader não mexe na profundidade, e assim não calculamos a luz de um pixel escondido
if (enabled.has(GL.DEPTH_TEST) && !(depth < zBuffer[index])) {
hidden++;
continue;
}
// de v/w de volta para v: divide por 1/w
const oneOverW = scans[1][i];
const varyings = {};
let k = 2;
for (const [name, size] of layout) {
const components = scans.slice(k, k + (size || 1)).map((scan) => scan[i] / oneOverW);
varyings[name] = size ? components : components[0];
k += size || 1;
}
const [r, g, b] = program.fragmentShader(varyings, program.uniforms);
canvasBuffer.data.set([r * 255, g * 255, b * 255, 255], index * 4);
if (enabled.has(GL.DEPTH_TEST)) zBuffer[index] = depth;
fragments++;
}
}
return { fragments, hidden };
};
// devolve o que aconteceu com o triângulo (para o inspector)
const drawTriangle = (triangle) => {
// ponytail: sem recorte de verdade ainda. Como na Sting, um vértice antes do near (ou atrás da
// câmera) descarta o triângulo inteiro; o recorte contra os planos fica para o capítulo de clipping
if (triangle.some(({ gl_Position: [, , z, w] }) => z < -w)) return { result: "near" };
// culling: o mesmo produto vetorial do nosso culling, mas com os pontos já na tela.
// Pela ordem dos vértices na tela (horário ou anti-horário) sabemos para que lado o triângulo olha
const ndc = triangle.map(({ gl_Position: [x, y, , w] }) => [x / w, y / w]);
const [a, b, c] = ndc;
const area = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
const isFront = frontFace === GL.CCW ? area > 0 : area < 0;
if (enabled.has(GL.CULL_FACE) && !isFront) return { result: "culled", ndc };
// divide por w e leva de -1..1 para os pixels do canvas (o viewport). A profundidade vai de -1..1 para 0..1
const vertices = triangle.map(({ gl_Position: [x, y, z, w], ...varyings }) => ({
x: Math.floor((x / w) * (width / 2)),
y: Math.floor((y / w) * (height / 2)),
values: [
(z / w + 1) / 2,
1 / w,
...Object.values(varyings).flatMap((value) =>
(typeof value === "number" ? [value] : Array.from(value)).map((component) => component / w)
),
],
}));
// como na Sting: um triângulo todo fora da tela não precisa ser preenchido
if (
vertices.every((p) => p.x < -width / 2) ||
vertices.every((p) => p.x > width / 2) ||
vertices.every((p) => p.y < -height / 2) ||
vertices.every((p) => p.y > height / 2)
) return { result: "offscreen", ndc };
// o nome e o tamanho de cada varying (0 para um número), para montar de volta no fragment shader
const { gl_Position, ...varyings } = triangle[0];
const layout = Object.entries(varyings).map(([name, value]) => [name, typeof value === "number" ? 0 : value.length]);
return { result: "drawn", ndc, ...fillTriangle(vertices, layout) };
};
const gl = {
...GL,
// shaders e programas: no lugar do texto em GLSL, uma função
createShader: (type) => ({ type }),
shaderSource: (shader, source) => {
shader.source = source;
},
compileShader: () => {}, // nada para compilar: a função já está pronta
createProgram: () => ({ attributes: [], uniforms: {} }),
attachShader: (program, shader) => {
program[shader.type === GL.VERTEX_SHADER ? "vertexShader" : "fragmentShader"] = shader.source;
},
linkProgram: () => {},
useProgram: (newProgram) => {
program = newProgram;
},
// atributos: um número (location) para cada nome
getAttribLocation: (program, name) => {
if (!program.attributes.includes(name)) program.attributes.push(name);
return program.attributes.indexOf(name);
},
// uniforms: um valor por nome, o mesmo para todos os vértices e pixels de um desenho
getUniformLocation: (program, name) => ({ program, name }),
uniform1i: ({ program, name }, value) => {
program.uniforms[name] = value;
},
uniform1f: ({ program, name }, value) => {
program.uniforms[name] = value;
},
uniform3fv: ({ program, name }, values) => {
program.uniforms[name] = Array.from(values);
},
// o WebGL recebe a matriz coluna por coluna; transpose = true diz que ela vem linha por linha.
// O shader recebe as quatro linhas, como o body da nossa Matrix4
uniformMatrix4fv: ({ program, name }, transpose, values) => {
program.uniforms[name] = [0, 1, 2, 3].map((i) =>
[0, 1, 2, 3].map((j) => (transpose ? values[i * 4 + j] : values[j * 4 + i]))
);
},
// buffers: listas de números que ficam na "GPU"
createBuffer: () => ({}),
bindBuffer: (target, buffer) => {
arrayBuffer = buffer;
},
bufferData: (target, data) => {
arrayBuffer.data = data;
},
// vertex array: de qual buffer (e como) cada atributo é lido
createVertexArray: () => ({ attributes: [] }),
bindVertexArray: (newVertexArray) => {
vertexArray = newVertexArray ?? defaultVertexArray;
},
enableVertexAttribArray: (location) => {
(vertexArray.attributes[location] ??= {}).enabled = true;
},
// stride e offset em bytes, como no WebGL (um FLOAT tem 4 bytes)
vertexAttribPointer: (location, size, type, normalized, stride, offset) => {
Object.assign((vertexArray.attributes[location] ??= {}), {
buffer: arrayBuffer,
size,
stride: stride / 4 || size,
offset: offset / 4,
});
},
// texturas
createTexture: () => ({}),
activeTexture: (unit) => {
activeUnit = unit - GL.TEXTURE0;
},
bindTexture: (target, texture) => {
units[activeUnit] = texture;
},
// como o Texture.loadImage: desenha a imagem num canvas para ler os pixels
texImage2D: (target, level, internalFormat, format, type, image) => {
const imageCanvas = document.createElement("canvas");
imageCanvas.width = image.width;
imageCanvas.height = image.height;
const imageContext = imageCanvas.getContext("2d");
imageContext.drawImage(image, 0, 0);
Object.assign(units[activeUnit], {
width: image.width,
height: image.height,
data: imageContext.getImageData(0, 0, image.width, image.height).data,
});
},
texParameteri: () => {}, // ponytail: o filtro é sempre LINEAR e as bordas sempre REPEAT
// estado
enable: (capability) => enabled.add(capability),
disable: (capability) => enabled.delete(capability),
frontFace: (mode) => {
frontFace = mode;
},
clearColor: (r, g, b, a) => {
clearColor = [r, g, b, a];
},
clear: (mask) => {
if (mask & GL.COLOR_BUFFER_BIT) {
const color = clearColor.map((c) => c * 255);
for (let i = 0; i < width * height * 4; i += 4) canvasBuffer.data.set(color, i);
}
if (mask & GL.DEPTH_BUFFER_BIT) zBuffer.fill(1);
blit();
},
// desenhar: roda o vertex shader em cada vértice e preenche um triângulo a cada três.
// A GPU de verdade mostra o quadro quando o JavaScript termina; aqui mostramos a cada desenho
drawArrays: (mode, first, count) => {
const vertices = [];
for (let i = first; i < first + count; i++) {
const attributes = {};
vertexArray.attributes.forEach((attribute, location) => {
if (!attribute.enabled) return;
const start = attribute.offset + i * attribute.stride;
attributes[program.attributes[location]] = attribute.buffer.data.subarray(start, start + attribute.size);
});
vertices.push(program.vertexShader(attributes, program.uniforms));
}
const triangles = [];
inspector.onDraw?.({ vertices, triangles, image: canvasBuffer });
for (let i = 0; i + 2 < vertices.length; i += 3) {
triangles.push(drawTriangle([vertices[i], vertices[i + 1], vertices[i + 2]]));
inspector.onDraw?.({ vertices, triangles, image: canvasBuffer });
}
blit();
},
// perguntar o estado: o WebGL é uma máquina de estados, e o getParameter diz o que está ligado agora
getParameter: (name) =>
({
[GL.CURRENT_PROGRAM]: program,
[GL.VERTEX_ARRAY_BINDING]: vertexArray === defaultVertexArray ? null : vertexArray,
[GL.ARRAY_BUFFER_BINDING]: arrayBuffer,
[GL.ACTIVE_TEXTURE]: GL.TEXTURE0 + activeUnit,
[GL.TEXTURE_BINDING_2D]: units[activeUnit] ?? null,
[GL.COLOR_CLEAR_VALUE]: clearColor,
[GL.FRONT_FACE]: frontFace,
})[name],
isEnabled: (capability) => enabled.has(capability),
};
// com o inspector ligado, cada chamada do gl avisa o passo a passo
if (inspector.onCall) {
for (const [name, method] of Object.entries(gl)) {
if (typeof method !== "function") continue;
gl[name] = (...args) => {
const result = method(...args);
inspector.onCall(name, args, result, gl);
return result;
};
}
inspector.onCall("createContext", [canvas], gl, gl);
}
return gl;
};
// O passo a passo do cubo.js. Não faz parte do WebGL: é só a interface do sketch.
// Ele grava o primeiro quadro do cubo.js: cada chamada ao gl (pelo inspector do webgl2-cpu.js) e, dentro do
// drawArrays, o vertex shader e cada triângulo, com o estado do WebGL e o canvas depois de cada passo.
// Os botões andam por essa gravação e marcam, nos códigos abaixo, a linha do cubo.js que fez a chamada
// e o pedaço do webgl2-cpu.js que ela executou.
// Quem liga os ganchos no inspector é o passo-a-passo.html (daqui não dá para importar o webgl2-cpu.js).
const GPU_FILE = "webgl2-cpu.js";
const $ = (id) => document.getElementById(id);
// só o primeiro quadro: o laço de animação do cubo.js para aqui
window.requestAnimationFrame = () => 0;
// ---------------------------------------------------------------------------------------------
// formatação
const number = (value) => String(+value.toFixed(2));
const vector = (values) => `(${Array.from(values, number).join(", ")})`;
const show = (value) =>
typeof value === "number" ? number(value)
: Array.isArray(value[0]) ? value.map(vector).join("\n") // uma matriz, linha por linha
: vector(value);
const escape = (text) => String(text).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
const unique = (lines) => [...new Set(lines)].sort((a, b) => a - b);
const range = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
// uma tabela de chave e valor; as linhas que mudaram desde o passo anterior ficam marcadas
const table = (title, rows, previous) => {
const before = previous && new Map(previous);
const body = rows
.map(([key, value]) => {
const changed = before && before.get(key) !== value;
return `<tr class="${changed ? "changed" : ""}"><th>${escape(key)}</th><td>${escape(value)}</td></tr>`;
})
.join("");
return `<h4>${title}</h4><table>${body}</table>`;
};
// ---------------------------------------------------------------------------------------------
// onde no código: linhas do cubo.js (pela pilha de chamadas) e trechos do webgl2-cpu.js (pelo texto)
// a linha do programa que fez a chamada: a primeira da pilha que não é da "GPU" nem do passo a passo.
// O Chrome conta as linhas do <script> do cubo.js a partir do script; o Firefox, a partir do começo da página.
// Vale a das duas que tem a chamada (name) escrita nela.
const callSite = (name) => {
for (const [, file, line] of new Error().stack.matchAll(/([\w.-]+\.m?js):(\d+):\d+/g)) {
if (file === GPU_FILE || file === "stepper.js") continue;
const source = files[file] ?? "";
const page = window.frameElement?.srcdoc ?? "";
const scriptStart = page.includes(source) ? page.slice(0, page.indexOf(source)).split("\n").length - 1 : 0;
const lines = source.split("\n");
const found = [Number(line), line - scriptStart].find((candidate) => lines[candidate - 1]?.includes(name));
return { file, line: found };
}
return null;
};
const gpuLines = (files[GPU_FILE] ?? "").split("\n");
const findLine = (text, after = 0) => gpuLines.findIndex((line, i) => i >= after && line.includes(text)) + 1;
// um bloco que começa na linha start: até fecharem as chaves que ele abriu
const blockFrom = (start) => {
if (!start) return [];
let depth = 0;
let opened = false;
for (let i = start - 1; i < gpuLines.length; i++) {
for (const char of gpuLines[i]) {
if (char === "{") (depth++, (opened = true));
else if (char === "}") depth--;
}
if (opened && depth <= 0) return range(start, i + 1);
}
return [start];
};
const between = (from, to) => {
const start = findLine(from);
const end = findLine(to, start);
return start && end ? range(start, end) : [];
};
const methodLines = (name) => blockFrom(gpuLines.findIndex((line) => line.trimStart().startsWith(`${name}: `)) + 1);
const GPU = {
createContext: between("export const createContext", "const enabled = new Set()"),
vertexShader: blockFrom(findLine("for (let i = first;")),
near: between("const drawTriangle", 'result: "near"'),
culled: between("const drawTriangle", 'result: "culled"'),
offscreen: between("const drawTriangle", 'result: "offscreen"'),
drawn: blockFrom(findLine("const fillTriangle")),
};
// as linhas de uma função (um shader) dentro do texto do programa
const functionLines = (source, fn) => {
const at = source.indexOf(String(fn));
if (at < 0) return [];
const start = source.slice(0, at).split("\n").length;
return range(start, start + String(fn).split("\n").length - 1);
};
// ---------------------------------------------------------------------------------------------
// o que cada chamada quer dizer
const TEXTS = {
createContext: () => [
"O contexto",
"O getContext(\"webgl2\") devolve o objeto gl, a porta para a GPU; aqui, o createContext do nosso rasterizador. O WebGL é uma máquina de estados: quase toda chamada liga alguma coisa (um programa, um buffer, uma textura) ou usa o que está ligado. Por enquanto nada está ligado, e o canvas está transparente.",
],
attachShader: ([, shader], gl) => [
shader.type === gl.VERTEX_SHADER ? "O vertex shader" : "O fragment shader",
"O shader é criado, recebe o código (aqui uma função JavaScript, no lugar do texto em GLSL) e é compilado. O attachShader prende ele ao programa.",
],
linkProgram: () => ["O programa fica pronto", "O linkProgram junta o vertex shader e o fragment shader num programa só."],
useProgram: () => [
"O programa em uso",
"O useProgram liga o programa: os próximos uniforms e desenhos usam ele. É o CURRENT_PROGRAM no estado.",
],
uniformMatrix4fv: ([location]) => [
`O uniform ${location.name}`,
"Um valor igual para todos os vértices e pixels de um desenho, guardado no programa em uso. A matriz vai linha por linha (transpose = true).",
],
uniform1i: ([location, value]) => [
`O uniform ${location.name}`,
`O sampler recebe o número da unidade de textura que ele vai ler: a TEXTURE${value}.`,
],
clearColor: () => ["A cor de limpar", "A cor que o clear vai usar. Só muda o estado: o canvas continua igual."],
enable: ([capability], gl) =>
capability === gl.DEPTH_TEST
? ["O teste de profundidade", "Com o DEPTH_TEST ligado, um pixel só é pintado se estiver mais perto do que o que já está no depth buffer."]
: ["O culling", "Com o CULL_FACE ligado, os triângulos de costas para a câmera são descartados antes de virar pixels."],
frontFace: () => [
"Qual lado é a frente",
"Nos nossos modelos, a frente de um triângulo é quando os vértices giram no sentido horário (CW) na tela.",
],
activeTexture: () => ["A unidade de textura", "As próximas chamadas de textura mexem na unidade TEXTURE0."],
bindTexture: () => ["Uma textura", "A textura criada é ligada na unidade ativa. É o TEXTURE_BINDING_2D no estado."],
texImage2D: () => [
"A imagem vai para a textura",
"O texImage2D copia os pixels da imagem para a textura ligada. Ele não recebe a textura: usa a que está ligada.",
],
texParameteri: () => [
"O filtro da textura",
"Sem mipmaps, o filtro precisa ser LINEAR (no nosso rasterizador ele sempre é).",
],
bindVertexArray: () => [
"O vertex array",
"O vertex array guarda de onde sai cada atributo dos vértices. Enquanto ele está ligado, as chamadas de atributo mexem nele; na hora de desenhar, ligar ele traz todos os atributos de volta de uma vez.",
],
bindBuffer: () => ["Um buffer", "O buffer criado é ligado em ARRAY_BUFFER."],
bufferData: ([, data]) => [
"Os números vão para o buffer",
`O bufferData copia ${data.length} números para o buffer ligado em ARRAY_BUFFER. Ele não recebe o buffer: usa o que está ligado.`,
],
enableVertexAttribArray: ([location]) => [
"Liga um atributo",
`O atributo da location ${location} passa a ser lido do vertex array a cada vértice.`,
],
vertexAttribPointer: ([location, size]) => [
"De onde sai o atributo",
`O vertexAttribPointer grava no vertex array que o atributo da location ${location} sai do buffer ligado em ARRAY_BUFFER agora, de ${size} em ${size} números (um vértice). Depois disso, trocar o ARRAY_BUFFER não muda mais esse atributo.`,
],
clear: () => [
"Limpa a tela",
"O clear pinta o canvas com a COLOR_CLEAR_VALUE e enche o depth buffer de 1, o mais longe possível.",
],
};
// chamadas que só criam ou perguntam alguma coisa: juntam-se à próxima chamada que muda o estado
const QUIET = new Set([
"createProgram",
"createShader",
"shaderSource",
"compileShader",
"createBuffer",
"createVertexArray",
"createTexture",
"getAttribLocation",
"getUniformLocation",
]);
// ---------------------------------------------------------------------------------------------
// a gravação
const frames = [];
let pending = []; // as chamadas desde o último passo
let gl;
let programFile;
let recording = true;
let quiet = false; // o próprio passo a passo perguntando o estado
// nomes para os objetos do WebGL, na ordem em que são criados
const names = new Map();
const counters = {};
const KINDS = { createProgram: "program", createBuffer: "buffer", createVertexArray: "vertexArray", createTexture: "texture" };
const label = (object) => (object == null ? "null" : names.get(object) ?? "?");
// o estado do WebGL, perguntado pelo getParameter (e olhando dentro dos objetos da nossa "GPU")
const snapshot = () => {
quiet = true;
const on = (capability) => (gl.isEnabled(capability) ? "ligado" : "desligado");
const program = gl.getParameter(gl.CURRENT_PROGRAM);
const vertexArray = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
const buffer = gl.getParameter(gl.ARRAY_BUFFER_BINDING);
const texture = gl.getParameter(gl.TEXTURE_BINDING_2D);
const rows = [
["CURRENT_PROGRAM", label(program)],
["VERTEX_ARRAY_BINDING", label(vertexArray)],
...(vertexArray?.attributes ?? []).flatMap((attribute, location) => [
[
` location ${location}`,
`${program?.attributes[location]} ← ${label(attribute.buffer)}${attribute.size ? `, ${attribute.size} por vértice` : ""}`,
],
]),
["ARRAY_BUFFER_BINDING", buffer ? `${label(buffer)} (${buffer.data?.length ?? 0} números)` : "null"],
["ACTIVE_TEXTURE", `TEXTURE${gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0}`],
["TEXTURE_BINDING_2D", texture ? `${label(texture)} (${texture.data ? `${texture.width} × ${texture.height}` : "vazia"})` : "null"],
["DEPTH_TEST", on(gl.DEPTH_TEST)],
["CULL_FACE", on(gl.CULL_FACE)],
["FRONT_FACE", gl.getParameter(gl.FRONT_FACE) === gl.CW ? "CW (horário)" : "CCW (anti-horário)"],
["COLOR_CLEAR_VALUE", vector(gl.getParameter(gl.COLOR_CLEAR_VALUE))],
];
const uniforms = Object.entries(program?.uniforms ?? {}).map(([name, value]) => [name, show(value)]);
quiet = false;
return { rows, uniforms, program };
};
const canvasImage = () => {
const canvas = $("canvas");
return canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height);
};
export const onCall = (name, args, result, context) => {
if (quiet || !recording) return;
gl = context;
const site = callSite(name);
programFile ??= site?.file;
if (KINDS[name] || name === "createShader") {
const kind = name === "createShader" ? (args[0] === gl.VERTEX_SHADER ? "vertexShader" : "fragmentShader") : KINDS[name];
counters[kind] = (counters[kind] ?? 0) + 1;
names.set(result, `${kind} ${counters[kind]}`);
}
pending.push({ name, args, line: site?.line });
if (name === "drawArrays") return finish(); // os passos do desenho já foram gravados pelo onDraw
if (QUIET.has(name)) return;
const [title, text] = TEXTS[name]?.(args, gl) ?? [name, ""];
frames.push({
title,
text,
lines: pending.map((call) => call.line).filter(Boolean),
gpu: pending.flatMap((call) => (call.name === "createContext" ? GPU.createContext : methodLines(call.name))),
state: snapshot(),
image: canvasImage(),
});
pending = [];
};
export const onDraw = ({ vertices, triangles, image }) => {
if (!recording) return;
const site = callSite("drawArrays");
const state = snapshot();
const source = files[programFile] ?? "";
const triangle = triangles[triangles.length - 1];
const shader =
!triangle ? state.program.vertexShader
: triangle.result === "drawn" ? state.program.fragmentShader
: null;
frames.push({
lines: [...pending.map((call) => call.line), site?.line].filter(Boolean),
shaderLines: shader ? functionLines(source, shader) : [],
gpu: triangle ? GPU[triangle.result] : GPU.vertexShader,
state,
image: new ImageData(new Uint8ClampedArray(image.data), image.width, image.height),
draw: { vertices, triangles: triangles.slice() },
});
pending = [];
};
// ---------------------------------------------------------------------------------------------
// a interface
let triangleCount = 0;
// dentro do drawArrays: o que saiu do vertex shader e o que aconteceu com os triângulos até aqui
const drawPanel = ({ vertices, triangles }) => {
const drawn = triangles.filter((triangle) => triangle.result === "drawn");
const fragments = drawn.reduce((sum, triangle) => sum + triangle.fragments, 0);
const hidden = drawn.reduce((sum, triangle) => sum + triangle.hidden, 0);
const { gl_Position, ...varyings } = vertices[0];
const rows = vertices
.map(({ gl_Position, ...varyings }, index) => {
const isCurrent = Math.floor(index / 3) === triangles.length - 1;
const cells = [index, vector(gl_Position), ...Object.values(varyings).map(show)];
return `<tr class="${isCurrent ? "current" : ""}">${cells.map((cell) => `<td>${cell}</td>`).join("")}</tr>`;
})
.join("");
const header = ["#", "gl_Position", ...Object.keys(varyings)].map((name) => `<th>${name}</th>`).join("");
return `<h4>dentro do drawArrays</h4>
<p class="summary">vertex shader: ${vertices.length} vértices<br>
triângulos: ${triangles.length} de ${triangleCount} · ${drawn.length} desenhados · ${triangles.length - drawn.length} descartados<br>
pixels: ${fragments} pintados · ${hidden} recusados pelo teste de profundidade</p>
<table class="vertices"><tr>${header}</tr>${rows}</table>`;
};
// o título e o texto de um passo do desenho
const describeDraw = ({ vertices, triangles }) => {
if (!triangles.length) {
return [
"Desenha: o vertex shader",
`O drawArrays começa rodando o vertex shader uma vez para cada vértice: ${vertices.length} vezes, cada uma lendo os seus atributos pelo vertex array e os uniforms do programa. O gl_Position de cada vértice, dividido por w, diz onde ele cai na tela (os pontos). Numa GPU essas execuções acontecem ao mesmo tempo; aqui, uma depois da outra.`,
];
}
const triangle = triangles[triangles.length - 1];
const texts = {
drawn: `Na tela, os vértices 1 → 2 → 3 giram no sentido horário: é a frente. A GPU acha os pixels dentro do triângulo, interpola o vTexCoord entre os três vértices e roda o fragment shader em cada pixel que passa no teste de profundidade: ${triangle.fragments} pixels pintados${triangle.hidden ? `, ${triangle.hidden} recusados (a borda que ele divide com um triângulo já desenhado)` : ""}.`,
culled: "Na tela, os vértices 1 → 2 → 3 giram no sentido anti-horário: o triângulo está de costas para a câmera. Com o CULL_FACE ligado, ele é descartado antes de virar pixels, e o fragment shader nem roda.",
offscreen: "O triângulo fica todo fora da tela, então não vira nenhum pixel.",
near: "Um dos vértices fica antes do plano near (ou atrás da câmera), então o triângulo é descartado.",
};
const isLast = triangles.length === triangleCount;
return [
`Desenha: triângulo ${triangles.length} de ${triangleCount}`,
texts[triangle.result] + (isLast ? " Era o último: o desenho está pronto." : ""),
];
};
// por cima do canvas: os vértices depois do vertex shader, ou o triângulo da vez
const drawOverlay = (draw) => {
const overlay = $("overlay").getContext("2d");
const { width, height } = overlay.canvas;
overlay.clearRect(0, 0, width, height);
if (!draw) return;
const toScreen = ([x, y]) => [((x + 1) / 2) * width, ((1 - y) / 2) * height];
const dot = ([x, y], color) => {
overlay.fillStyle = color;
overlay.beginPath();
overlay.arc(x, y, 2.5, 0, 2 * Math.PI);
overlay.fill();
};
if (!draw.triangles.length) {
for (const { gl_Position: [x, y, , w] } of draw.vertices) if (w > 0) dot(toScreen([x / w, y / w]), "#d6336c");
return;
}
const triangle = draw.triangles[draw.triangles.length - 1];
if (!triangle.ndc) return;
const points = triangle.ndc.map(toScreen);
const color = triangle.result === "drawn" ? "#1f9d55" : "#d63031";
overlay.beginPath();
points.forEach(([x, y], index) => (index ? overlay.lineTo(x, y) : overlay.moveTo(x, y)));
overlay.closePath();
overlay.setLineDash(triangle.result === "drawn" ? [] : [4, 3]);
overlay.strokeStyle = color;
overlay.lineWidth = 1.5;
overlay.stroke();
overlay.setLineDash([]);
// os números mostram a ordem dos vértices na tela, que decide o culling
const center = points.reduce(([cx, cy], [x, y]) => [cx + x / 3, cy + y / 3], [0, 0]);
overlay.font = "bold 10px sans-serif";
overlay.textAlign = "center";
overlay.textBaseline = "middle";
points.forEach(([x, y], index) => {
dot([x, y], color);
const length = Math.hypot(x - center[0], y - center[1]) || 1;
overlay.fillText(String(index + 1), x + ((x - center[0]) / length) * 9, y + ((y - center[1]) / length) * 9);
});
};
let current = 0;
const go = (index) => {
current = Math.max(0, Math.min(frames.length - 1, index));
const frame = frames[current];
const previous = frames[current - 1];
const [title, text] = frame.draw ? describeDraw(frame.draw) : [frame.title, frame.text];
const sourceLines = (files[programFile] ?? "").split("\n");
$("title").textContent = `passo ${current + 1}: ${title}`;
$("snippet").textContent = unique(frame.lines).map((line) => sourceLines[line - 1].trim()).join("\n");
$("text").textContent = text;
$("counter").textContent = `${current + 1} / ${frames.length}`;
$("scrub").value = current;
$("back").disabled = current === 0;
$("next").disabled = current === frames.length - 1;
$("details").innerHTML = frame.draw
? drawPanel(frame.draw)
: frame.state.uniforms.length
? table("Uniforms do programa", frame.state.uniforms, previous?.state.uniforms)
: "";
$("state").innerHTML = table("Estado do WebGL", frame.state.rows, previous?.state.rows);
$("screen").getContext("2d").putImageData(frame.image, 0, 0);
drawOverlay(frame.draw);
window.highlightCode?.({
[programFile]: unique([...frame.lines, ...(frame.shaderLines ?? [])]),
[GPU_FILE]: unique(frame.gpu),
});
};
// o primeiro drawArrays terminou: a gravação acabou, e o passo a passo começa
const finish = () => {
recording = false;
triangleCount = frames[frames.length - 1].draw?.triangles.length ?? 0;
$("scrub").max = frames.length - 1;
$("back").onclick = () => go(current - 1);
$("next").onclick = () => go(current + 1);
$("scrub").oninput = (event) => go(Number(event.target.value));
addEventListener("keydown", (event) => {
if (event.key === "ArrowRight") go(current + 1);
else if (event.key === "ArrowLeft") go(current - 1);
else return;
event.preventDefault();
});
go(0);
};
<!-- o canvas em que o cubo.js desenha fica escondido; o passo a passo mostra o que foi gravado dele -->
<canvas id="canvas" width="240" height="240" hidden></canvas>
<div class="stepper">
<section class="step">
<div class="nav">
<button id="back" title="Voltar (←)" disabled>◀</button>
<input id="scrub" type="range" min="0" max="0" value="0" aria-label="Passo">
<button id="next" title="Avançar (→)" disabled>▶</button>
<span id="counter"></span>
</div>
<h3 id="title">carregando…</h3>
<pre id="snippet"></pre>
<p id="text"></p>
<div id="details"></div>
</section>
<section class="gpu">
<div class="screen">
<canvas id="screen" width="240" height="240"></canvas>
<canvas id="overlay" width="240" height="240"></canvas>
</div>
<div id="state"></div>
</section>
</div>
<!-- roda antes do cubo.js: liga o passo a passo nos ganchos do inspector antes do createContext -->
<script type="module">
import { inspector } from "./webgl2-cpu.js";
import { onCall, onDraw } from "./stepper.js";
Object.assign(inspector, { onCall, onDraw });
</script>
* {
box-sizing: border-box;
}
body {
font: 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: #2b2b2b;
background: #fff;
}
.stepper {
display: flex;
height: 100%;
}
/* o passo: navegação, a chamada e a explicação */
.step {
flex: 1 1 56%;
min-width: 0;
overflow: auto;
padding: 10px 12px;
border-right: 1px solid #e6e6e6;
}
.nav {
display: flex;
align-items: center;
gap: 8px;
}
.nav button {
font: inherit;
font-size: 12px;
padding: 2px 12px;
border: 1px solid #d4d4d4;
border-radius: 6px;
background: #fafafa;
cursor: pointer;
}
.nav button:disabled {
opacity: 0.4;
cursor: default;
}
#scrub {
flex: 1;
min-width: 0;
accent-color: #b5322b;
}
#counter {
font-size: 12px;
color: #888;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
h3 {
margin: 10px 0 6px;
font-size: 14px;
}
#snippet {
margin: 0 0 8px;
padding: 6px 8px;
border-left: 3px solid #e0a800;
background: #fff5d1;
font: 11.5px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: pre-wrap;
}
#snippet:empty {
display: none;
}
#text {
margin: 0;
color: #444;
font-size: 12.5px;
}
/* a tela e o estado */
.gpu {
flex: 0 0 44%;
min-width: 0;
display: flex;
flex-direction: column;
}
.screen {
position: relative;
flex: none;
width: min(100% - 20px, 200px);
aspect-ratio: 1;
margin: 10px auto 2px;
/* o xadrez aparece onde o canvas está transparente */
background: repeating-conic-gradient(#eee 0 25%, #fff 0 50%) 0 0 / 16px 16px;
border: 1px solid #e6e6e6;
}
.screen canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
image-rendering: pixelated;
}
#state {
flex: 1;
overflow: auto;
padding: 0 10px 10px;
}
h4 {
margin: 10px 0 4px;
font-size: 12px;
}
.summary {
margin: 0 0 6px;
font-size: 11.5px;
color: #555;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 2px 4px;
border-bottom: 1px solid #f0f0f0;
text-align: left;
vertical-align: top;
font: 10.5px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
}
th {
color: #555;
white-space: pre;
}
td {
white-space: pre-wrap;
}
tr.changed {
background: #fff5d1;
}
tr.current {
background: #e5f2fd;
}