Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

11.2 KB
Raw Blame
// Hardware ray tracing (wgpu ray query). A TLAS instance a model instance or a procedural object: shadow casters
// mask 1, the rest mask 2 (glass among them; an instance's glass among its other sections is stepped through by its
// row). Every query forces opacity and a cutout's hit is confirmed by `alpha_pass`, but for a ray that goes by the
// cutouts' maps (cutout.rs): the sections that have maps are not flagged opaque, and that ray is handed their
// triangles one by one. instance_custom_data holds the instance's record.
@if(hwrt) @group(0) @binding(19) var acc: acceleration_structure;

@if(hwrt) fn trace(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mode: u32) -> Hit {
    // Ray tracing off (pathtrace.wgsl `rays_off`): past the camera ray, every ray misses.
    if (rays_off) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u); }
    let mask = select(0xffu, 1u, mode == TRACE_SHADOW);
    let any = mode != TRACE_CLOSEST;
    // (A scene without cutouts: one query. A feature bit: the kernel has this or what follows, not both. Glass among an
    // instance's other sections is stepped through as a cutout is: `passes`.)
    if (!has(F_MASKED) && !has(F_IGLASS)) { return trace_opaque(o, d, tmax_in, mask, any, false); }
    // Whether a cutout stops this ray as any triangle does: A_CUTOUT_PATHS (pathtrace.wgsl `cutouts_opaque`).
    @if(!cutout_lite) let solid = cutouts_opaque();
    @if(cutout_lite) let solid = cutouts_opaque() || any;
    // A ray by the cutouts' maps (TRACE_ANY_OPAQUE: A_CUTOUT_EMITTERS, `emitter_tr`): one query, which hands it each
    // triangle of a cutout that has maps to ask the map of (`trace_opaque`); whatever else it meets stops it. No
    // texture is read and no second query starts where a map says a hole. (The candidate loop this is lost hits
    // on Metal when every ray's cutouts went through it and their hits were confirmed by `alpha_pass`, see below;
    // for these rays, on the sections with maps alone, two offline renders of Bistro agree in all but 2 of 921,600
    // pixels and with the same rays stepped in order in all but 0.2 %, their mean within 1e-5.)
    @if(!cutout_lite) if (mode == TRACE_ANY_OPAQUE && !solid && has(F_MASKED)) {
        map_hole = false;
        let h = trace_opaque(o, d, tmax_in, mask, true, true);
        if (h.tri == 0xffffffffu && map_hole) { shadow_hole = true; }
        return h;
    }
    // Alpha-cutout triangles: every query forces opacity, and a cutout hit that fails its alpha test is stepped
    // through. The ray query's own candidate loop (non-opaque traversal) lost hits on Metal: ~0.1 % of rays near
    // cutout foliage missed even the opaque ground behind it or found it unlit (black pixels on the ground; the
    // software BVH had none, and confirming every candidate did not help), differently from run to run (two offline
    // renders of Kabukichō differed in 75 % of their pixels). Fewer whole-scene steps (the opaque instances once, then
    // the cutout instances alone; or one candidate loop on them) came out within ±0.4 ms on Bistro: the leaves' alpha
    // tests and the traversal past them cost it, however the queries are arranged. Culling the cutout geometry by its
    // non-opaque flag (RAY_FLAG_CULL_NO_OPAQUE) was slow on Metal (Bistro's trace +1.7 ms); every geometry is flagged
    // opaque.
    //
    // In order, each query starting past the last cutout hit its alpha let through. Shadow rays take up to 64 of them
    // and count as blocked past that: with 16, as closest hits take, the rest counted as unblocked (light through dense
    // foliage: Bistro's offline render up to 2.3 % bright in a region against the software BVH).
    // A_CUTOUT_DEEP: a closest hit takes CUTOUT_DEEP, and the cutout its last one meets stands whole, where 16 then
    // end in nothing. Each query starts the traversal again, and a view through a tree's crown is many: of Bistro's frame
    // at its street view the queries past the eighth were 1.1 ms of 20.3 (an M4, half resolution; guides 3.35 ->
    // 2.70 ms, camera hits 1.33 -> 0.87), for 0.26 % of the picture's pixels off by more than 8 of 255, all in the
    // crowns, and ΔE against the offline render 3.11 -> 3.13. (What stands in for the queries is not in reach here:
    // the cutouts' maps in the query's candidate loop, as opacity micromaps answer, were slower on Metal than the
    // queries, guides 5.84 ms; in front of the alpha test they saved nothing: the cost is the queries, not the
    // texture.)
    @if(!cutout_lite2) let deep = approx(A_CUTOUT_DEEP) && !any;
    @if(!cutout_lite2) let steps = select(select(16u, CUTOUT_DEEP, deep), 64u, any);
    @if(cutout_lite2) let deep = false;
    @if(cutout_lite2) let steps = 4u;
    // One ray query in the source for every kind of ray. `trace` is inlined where it is called, and each query written
    // in it costs every ray, taken or not: with a query of its own for opaque cutouts and one for a shadow ray's first
    // hit beside the ordered ones, Zero Day's trace was 9.40 ms for 8.39 and Bistro's 8.56 for 8.05. A shadow ray's
    // first query takes any hit; if that is a cutout its alpha lets through, the ordered ones start from the ray's
    // origin.
    var first = any;
    var t0 = 0.0;
    var hole = false;
    for (var k = 0u; k < steps + u32(any); k++) {
        let h = trace_opaque(o + d * t0, d, tmax_in - t0, mask, first, false);
        if (h.tri == 0xffffffffu) {
            // (A shadow ray comes here in order only past a cutout that let it through, `shadow_hole`, or past glass.)
            if (any && !first && hole) { shadow_hole = true; }
            return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);
        }
        let t = t0 + h.t;
        // A shadow ray passes the glass among an instance's sections (its row says so; an instance that is all glass is
        // out of its way by its mask).
        let passes = has(F_IGLASS) && mask == 1u && hit_row != NO_ROW && (hit_row & ROW_GLASS) != 0u;
        if (!passes) {
            if (!has(F_MASKED) || solid || is_proc(h) || !cutout_hit(h) || (deep && k + 1u >= steps) || alpha_pass(h.tri, h.inst, h.part, h.u, h.v, t)) { return Hit(t, h.tri, h.u, h.v, h.inst, h.part); }
            hole = true;
        }
        if (first) { first = false; } else { t0 = t + 1e-4 * max(1.0, t); }
    }
    if (any) { return Hit(t0, 0u, 0.0, 0.0, NO_INST, 0u); }
    return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);
}

// The closest (or with `any`, the first found) hit, every triangle opaque; or, `by_maps`, the triangles of the
// cutouts that have maps (their geometries are not flagged opaque: gpu.rs) each asked of its map where the ray meets
// it and passed where the map says a hole (`map_hole`): a section without maps is flagged opaque and stops the ray,
// as every cutout stopped such a ray before there were maps.
@if(hwrt) var<private> map_hole: bool;
@if(hwrt) fn trace_opaque(o: vec3<f32>, d: vec3<f32>, tmax_in: f32, mask: u32, any: bool, by_maps: bool) -> Hit {
    hit_row = NO_ROW;
    @if(strict) if (ray_bad(o, d, tmax_in)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u); }
    var rq: ray_query;
    let flags = select(RAY_FLAG_FORCE_OPAQUE, RAY_FLAG_NONE, by_maps) | select(RAY_FLAG_NONE, RAY_FLAG_TERMINATE_ON_FIRST_HIT, any);
    rayQueryInitialize(&rq, acc, RayDesc(flags, mask, 0.0, tmax_in, o, d));
    var pg = GOut(-1.0, vec3<f32>(0.0, 1.0, 0.0), 0u, vec2<f32>(0.0));
    var pprim = 0u;
    if (!has(F_PROC) && !(has(F_MASKED) && by_maps)) {
        rayQueryProceed(&rq);
    } else {
        // Procedural boxes come up as candidates although the query forces opacity (that applies to triangles; checked
        // on Metal: one AABB candidate loop is deterministic run to run, unlike cutout-triangle candidates). Each one's
        // geometry function answers up to the closest hit so far; the last hit generated is the committed one unless a
        // triangle committed after it.
        while (rayQueryProceed(&rq)) {
            let c = rayQueryGetCandidateIntersection(&rq);
            if (c.kind == RAY_QUERY_INTERSECTION_TRIANGLE) {
                // (A cutout's, of a ray by the maps: no other triangle and no other ray comes here.)
                if (cutout_mapped(instance_at(c.instance_custom_data).info.w, c.geometry_index, c.primitive_index, c.barycentrics.x, c.barycentrics.y) != 0) {
                    rayQueryConfirmIntersection(&rq);
                } else {
                    map_hole = true;
                }
                continue;
            }
            if (c.kind != RAY_QUERY_INTERSECTION_AABB) { continue; }
            let cur = rayQueryGetCommittedIntersection(&rq);
            let tmax = select(tmax_in, cur.t, cur.kind != RAY_QUERY_INTERSECTION_NONE);
            let g = proc_box(c.instance_custom_data, c.primitive_index, c.world_to_object * vec4<f32>(o, 1.0), c.world_to_object * vec4<f32>(d, 0.0), 0.0, tmax);
            // (naga: the hit distance as its own value, not `g.t`, which it scopes wrongly for the ray-query statement.)
            let gt = g.t;
            if (gt >= 0.0) {
                pg = g;
                pprim = c.primitive_index;
                rayQueryGenerateIntersection(&rq, gt);
            }
        }
    }
    let it = rayQueryGetCommittedIntersection(&rq);
    if (it.kind == RAY_QUERY_INTERSECTION_NONE) {
        return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);
    }
    if (has(F_PROC) && it.kind == RAY_QUERY_INTERSECTION_GENERATED) { return proc_hit(it.t, pg, pprim, it.instance_custom_data); }
    // (A triangle is an instance's: a scene without instances has none.)
    if (!has(F_INST)) { return Hit(tmax_in, 0xffffffffu, 0.0, 0.0, NO_INST, 0u); }
    // Its instance's record is the custom data; ti is its mesh's triangle, in model space, and the geometry it was
    // hit in its section.
    let ti = hit_tri(it.instance_custom_data, it.geometry_index, it.primitive_index);
    return Hit(it.t, ti, it.barycentrics.x, it.barycentrics.y, it.instance_custom_data, it.geometry_index);
}

// The first word of the row of the hit `trace_opaque` last found (its material and class bits), NO_ROW where its
// instance has no rows: the trace's tests of a hit read no attribute and no material then.
@if(hwrt) var<private> hit_row: u32;
@if(hwrt) const NO_ROW: u32 = 0xffffffffu;
// Whether that hit is an alpha-cutout's: its row says.
@if(hwrt) fn cutout_hit(h: Hit) -> bool { return hit_row != NO_ROW && (hit_row & ROW_CUTOUT) != 0u; }

// The triangle of a hit of the instance at record `inst`. The geometry is a section of its mesh, and its row has
// where the section's triangles start (the first section starts where the mesh does); the row's class is read where
// the trace tests a hit by it.
@if(hwrt) fn hit_tri(inst: u32, geometry: u32, prim: u32) -> u32 {
    let rec = instance_at(inst);
    if (has(F_MASKED) || has(F_IGLASS)) { hit_row = row_word(rec.info.w, geometry, 0u); }
    var first = rec.info.x;
    if (geometry != 0u) { first = row_word(rec.info.w, geometry, 1u); }
    return first + prim;
}

// gpu.rs `KernelSwitches::strict`: a ray a ray query must not be given (not finite, or a length that is negative or NaN).
@if(hwrt && strict) fn ray_bad(o: vec3<f32>, d: vec3<f32>, tmax: f32) -> bool {
    let tb = bitcast<u32>(tmax);
    return non_finite(o) || non_finite(d) || (tb & 0x80000000u) != 0u || (tb & 0x7fffffffu) > 0x7f800000u;
}