Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

8.5 KB
Raw Blame
import { Matrix4 } from "three";
import { TelosHost, materialFromAppearance } from "../src/index.js";
import type {
  TelosMesh,
  TelosField,
  TelosScene,
  TelosShaderArtifact,
  TelosLine,
} from "../src/index.js";

declare global {
  interface Window {
    telosQualification: unknown;
    telosWitness: TelosHost;
  }
}
const check = (value: unknown, message: string) => {
  if (!value) throw new Error(message);
};
const canvas = document.querySelector("canvas")!;
const status = document.querySelector("pre")!;
const errors: string[] = [];
try {
  const started = performance.now();
  const host = await TelosHost.create(canvas, (message) =>
    errors.push(message),
  );
  window.telosWitness = host;
  const initMs = performance.now() - started;
  host.resize(256, 256, 1);
  host.camera.position.set(0, 0, 5);
  host.camera.target.set(0, 0, 0);
  host.camera.near = 0.1;
  host.camera.far = 100;
  host.camera.span = 4;
  host.camera.update();
  const artifact = (await (
    await fetch("/artifacts/local/three-telos/cir/cylinder.json")
  ).json()) as TelosShaderArtifact;
  check(
    artifact.wgsl.startsWith("// Generated by vd-wgsl/1"),
    "not direct WGSL",
  );
  const plane = {
    id: "shared-plane",
    positions: [-1.3, -1.3, 0, 1.3, -1.3, 0, -1.3, 1.3, 0, 1.3, 1.3, 0],
    normals: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
    indices: [0, 1, 2, 2, 1, 3],
  };
  const mesh = (z: number, id = "mesh"): TelosMesh => ({
    definition: plane,
    transform: new Matrix4().makeTranslation(0, 0, z).elements,
    identity: { occurrenceId: id, bodyId: "mesh-body" },
    material: materialFromAppearance({ baseColor: [0.05, 0.8, 0.12] }),
  });
  const field: TelosField = {
    artifact,
    identity: { occurrenceId: "CIR-cylinder", bodyId: "authored-cylinder" },
    bounds: { minimum: [-0.8, -0.8, -1], maximum: [0.8, 0.8, 1] },
    material: materialFromAppearance({ baseColor: [0.85, 0.12, 0.06] }),
  };
  const results: Record<string, unknown> = {
    initMs,
    shaderId: artifact.shaderId,
    directCompiler: true,
  };
  const initialStart = performance.now();
  host.setScene({ meshes: [mesh(-2)], lines: [], fields: [field] });
  host.render();
  await host.owner.device.queue.onSubmittedWorkDone();
  results.firstFrame = {
    ...host.metrics,
    submissionCompletedMs: performance.now() - initialStart,
  };
  const render = async (scene: TelosScene) => {
    host.setScene(scene);
    host.render();
    const pixels = await host.readPixels();
    await host.owner.device.queue.onSubmittedWorkDone();
    check(!errors.length, errors.join("\n"));
    return pixels;
  };
  const center = (pixels: Uint8Array) =>
    Array.from(
      pixels.subarray((128 * 256 + 128) * 4, (128 * 256 + 128) * 4 + 4),
    );
  const same = (a: number[], b: number[]) =>
    a.every((n, i) => Math.abs(n - b[i]) <= 2);
  for (const mode of ["perspective", "orthographic"] as const) {
    host.camera.mode = mode;
    host.camera.update();
    const cir = center(
      await render({ meshes: [], lines: [], fields: [field] }),
    );
    const front = center(
      await render({ meshes: [mesh(2)], lines: [], fields: [] }),
    );
    const mixedBack = center(
      await render({ meshes: [mesh(-2)], lines: [], fields: [field] }),
    );
    const mixedFront = center(
      await render({ meshes: [mesh(2)], lines: [], fields: [field] }),
    );
    check(!same(cir, front), "empty or indistinguishable CIR");
    check(
      same(cir, mixedBack),
      mode +
        ": field must occlude mesh " +
        JSON.stringify({ cir, mixedBack, front, mixedFront }),
    );
    check(same(front, mixedFront), mode + ": mesh must occlude field");
    const meshOverlap = center(
      await render({
        meshes: [mesh(2), { ...mesh(-2), material: field.material }],
        lines: [],
        fields: [],
      }),
    );
    check(same(front, meshOverlap), "mesh depth failed");
    results[mode] = { cir, front, mixedBack, mixedFront, meshOverlap };
  }
  const line: TelosLine = {
    id: "edge",
    points: [-1, 0, 0, 1, 0, 0],
    widthPixels: 4,
    color: [1, 1, 1, 1],
    identity: { occurrenceId: "line", edgeId: "BRep-edge" },
  };
  const lineWidths = [];
  for (const dpr of [1, 2])
    for (const span of [3, 10]) {
      host.camera.span = span;
      host.resize(256, 256, dpr);
      const pixels = await render({
        meshes: [],
        fields: [],
        lines: [
          {
            ...line,
            transform: new Matrix4().makeTranslation(0, 0, 0.5).elements,
          },
        ],
      });
      const x = host.frame.width / 2;
      let width = 0;
      for (let y = 0; y < host.frame.height; y++) {
        const offset = (y * host.frame.width + x) * 4;
        if (
          pixels[offset] > 200 &&
          pixels[offset + 1] > 200 &&
          pixels[offset + 2] > 200
        )
          width++;
      }
      check(Math.abs(width / dpr - 4) <= 1, "line CSS width drift");
      lineWidths.push({ dpr, span, devicePixels: width });
    }
  results.lineWidths = lineWidths;
  host.resize(256, 256, 1);
  host.camera.span = 4;
  const surface = center(
    await render({ meshes: [mesh(2)], fields: [], lines: [] }),
  );
  const hidden = center(
    await render({ meshes: [mesh(2)], fields: [], lines: [line] }),
  );
  check(same(surface, hidden), "hidden edge leakage");
  const selected = center(
    await render({
      meshes: [],
      fields: [],
      lines: [{ ...line, selected: true }],
    }),
  );
  check(!same(surface, selected), "selected edge style");
  const sharedScene: TelosScene = {
    meshes: [
      { ...mesh(0, "left"), selected: true },
      {
        ...mesh(0, "right"),
        transform: new Matrix4().makeTranslation(2, 0, 0).elements,
      },
    ],
    fields: [
      field,
      {
        ...field,
        identity: { occurrenceId: "second-cylinder" },
        selected: true,
        transform: new Matrix4().makeTranslation(-2, 0, 0).elements,
      },
    ],
    lines: [line],
  };
  await render(sharedScene);
  check(host.geometry.size === 1, "duplicate definition buffers");
  check(host.owner.resources.modules.size === 3, "duplicate shader modules");
  results.reuse = {
    definitions: host.geometry.size,
    modules: host.owner.resources.modules.size,
    pipelines: host.owner.resources.pipelines.size,
  };
  const depthGeneration = host.frame.generation;
  host.resize(320, 180, 2);
  host.render();
  await host.readPixels();
  check(host.frame.generation > depthGeneration, "depth resize failed");
  for (const span of [0.01, 10000]) {
    host.camera.span = span;
    host.grid = true;
    host.render();
    await host.readPixels();
    check(!errors.length, "grid/camera stress validation");
  }
  host.grid = false;
  host.resize(256, 256, 1);
  host.camera.span = 4;
  host.camera.position.set(4, 3, 6);
  host.camera.update();
  host.render();
  await host.readPixels();
  const times = [];
  for (let i = 0; i < 20; i++) {
    const start = performance.now();
    host.render();
    await host.owner.device.queue.onSubmittedWorkDone();
    times.push(performance.now() - start);
  }
  results.timings = {
    ...host.metrics,
    steadySubmissionMeanMs: times.reduce((a, b) => a + b) / times.length,
  };
  results.gpu = {
    vendor: host.owner.adapter.info.vendor,
    architecture: host.owner.adapter.info.architecture,
    description: host.owner.adapter.info.description,
  };
  const modes: Record<string, unknown> = {};
  for (const mode of ["None", "SpatialOnly", "TAA", "TAAUtility"] as const) {
    host.setAA(mode);
    host.render();
    await host.readPixels();
    modes[mode] = {
      active: host.aaMode,
      samples: host.owner.sampleCount,
      depthGeneration: host.frame.generation,
    };
    check(
      host.owner.sampleCount === (mode === "SpatialOnly" ? 4 : 1),
      "AA attachment sample count mismatch",
    );
  }
  results.aaTransitions = modes;
  const resources = host.owner.resources;
  host.dispose();
  check(
    resources.buffers.size === 0 && resources.textures.size === 0,
    "resources retained after disposal",
  );
  const recreated = await TelosHost.create(canvas, (message) =>
    errors.push(message),
  );
  recreated.resize(256, 256);
  recreated.setScene(sharedScene);
  recreated.fit();
  recreated.render();
  await recreated.readPixels();
  check(!errors.length, errors.join("\n"));
  window.telosWitness = recreated;
  window.telosQualification = { status: "PASS", results, errors };
  status.textContent = JSON.stringify(window.telosQualification, null, 2);
} catch (error) {
  window.telosQualification = { status: "FAIL", error: String(error), errors };
  status.textContent = JSON.stringify(window.telosQualification, null, 2);
}