<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ramith D. Rodrigo on Medium]]></title>
        <description><![CDATA[Stories by Ramith D. Rodrigo on Medium]]></description>
        <link>https://medium.com/@ramithrodrigo?source=rss-5003525022b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Ramith D. Rodrigo on Medium</title>
            <link>https://medium.com/@ramithrodrigo?source=rss-5003525022b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:26:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramithrodrigo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Improving the performance of the Ray Tracer using WebGPU Compute]]></title>
            <link>https://medium.com/@ramithrodrigo/improving-the-performance-of-the-ray-tracer-using-webgpu-compute-4b6de7881ae5?source=rss-5003525022b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b6de7881ae5</guid>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[webgpu]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <dc:creator><![CDATA[Ramith D. Rodrigo]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 08:46:45 GMT</pubDate>
            <atom:updated>2026-06-16T08:46:45.006Z</atom:updated>
            <content:encoded><![CDATA[<p>As I have some interest in graphics and rendering, I wanted to try out implementing a ray tracer and found a great resource, which is <a href="https://raytracing.github.io/books/RayTracingInOneWeekend.html"><strong><em>Ray Tracing in One Weekend</em></strong></a>. It explains the theory behind ray tracing and how to implement it in C++. The one-to-one implementation can be found <a href="https://github.com/Ramith-D-Rodrigo/RayTracer"><strong><em>here</em></strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*l6gAiQvZvm0YLST6YjxY1Q.png" /><figcaption>The output I got from following the resource. Pretty Cool right?</figcaption></figure><p>After completing it, the resource pointed out the next steps of the series. However, before going on the next book, I wanted to try out improving its performance using GPU.</p><p>If you have tried out the implementation of this series, you may realize that it is a CPU implementation which tries to determine the color of each pixel sequentially. But GPU is all about paralellism.</p><h3><strong>Result</strong></h3><p>To get you engaged, here are the screenshots and the frame times for rendering the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyXMLQtuRg-v3BqaabxDnw.png" /><figcaption>CPU Rendered Frame (Frame Time of 595268 ms)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UL08DLwl1nfw9e1wC5ecTA.png" /><figcaption>GPU Rendered Frame (Frame Time of 1592.69 ms)</figcaption></figure><p>Notice the difference in frame time. 595268ms vs 1592.69ms. That is about 374x speed up!</p><p>Although you can see the positions and the colors of the spheres in each frame are different, which may raise a concern on the comparison. This happens because the positions and colors are randomized. But at an average, you can definitely achieve the said performance boost.</p><p>Even still, it is worth noting that the frame time of 1592.69ms doesn’t even come close to the interactive real-time rendering, as it requires the frame time to be around 33.33ms. I believe the next part of the Ray Tracing series book aims to improve the performance with the use of bounding volumes. However, that part isn’t within the scope of this article.</p><h3><strong>Motivation</strong></h3><p>Frankly, there are many videos, demos, and resources that discuss GPU ray tracing, GPU compute shaders, etc. Over the few months, my WebGPU knowledge has become rusty, and I thought this would be a good opportunity to refresh my knowledge, and also learn more about GPU programming, and GPU compute shaders. Following that, I wanted to share how I translated this CPU implementation to GPU friendly implementation, and how I improved its performance. Maybe in the future, I can revisit this article to refresh my knowledge again if needed. Hence, please keep in mind that there can be better approaches to solve this problem. I am always open to suggestions and improvements.</p><p>Also, WebGPU can be used in the browser, so anyone can try out my implementation on their own device (as long as it supports WebGPU and has a compatible GPU). To do the comparison, I added a CPU mode for the ray tracer using TypeScript Canvas2D (with the help of AI because I didn’t want to spend time reimplementing it).</p><p>You can find the full source code on <a href="https://github.com/Ramith-D-Rodrigo/RayTracer-web"><strong><em>GitHub</em></strong></a>.</p><h3><strong>Prerequisites</strong></h3><p>As I am purely focusing on the translation process, I will not be explaining the rendering/ray tracing logic in detail. I recommend you to read <a href="https://raytracing.github.io/books/RayTracingInOneWeekend.html"><strong><em>Ray Tracing in One Weekend</em></strong></a> to understand the logic. Also, you should be familiar with TypeScript, and WebGPU concepts. The best resources that I personally used to study WebGPU are <a href="https://webgpufundamentals.org/"><strong><em>WebGPU Fundamentals</em></strong></a>, and <a href="https://eliemichel.github.io/LearnWebGPU/"><strong><em>Learn WebGPU</em></strong></a><strong><em>.</em></strong></p><p>I recommend you to clone my source code and/or have it open in the side while reading this article to gain a better understanding.</p><h3>Structure</h3><p>There are 3 important components in this implementation:</p><ol><li>Compute Shader Code</li><li>Scene Serialization</li><li>Singleton Class that encapsulates all the WebGPU logic</li></ol><p>Let me start with the compute shader code.</p><h3>Compute Shader Code</h3><p>The CPU implementation’s rendering logic is stored in my Camera class. This is what I used to translate to the GPU compute shader.</p><p>WebGPU supports compute shaders which can be used to perform arbitrary parallel computations on the GPU. Since the operation is handled by the GPU, we need to pass the data correctly. As such I have defined 4 structs in WGSL which are:</p><ul><li>CameraParams</li><li>Sphere</li><li>Ray</li><li>HitRecord</li></ul><h4>CameraParams</h4><p>The definition of the struct CameraParams is as follows:</p><pre>struct CameraParams {<br>  cameraOrigin: vec3&lt;f32&gt;,<br>  padding1: f32,<br>  pixel00Loc: vec3&lt;f32&gt;,<br>  padding2: f32,<br>  deltaU: vec3&lt;f32&gt;,<br>  padding3: f32,<br>  deltaV: vec3&lt;f32&gt;,<br>  padding4: f32,<br>  defocusDiskU: vec3&lt;f32&gt;,<br>  padding5: f32,<br>  defocusDiskV: vec3&lt;f32&gt;,<br>  defocusAngle: f32,<br>  samplesPerPixel: u32,<br>  maxDepth: u32,<br>  frameCount: u32,<br>}</pre><p>Every property here has its counterpart in the Camera class, except for frameCount and the padding# fields. The padding is there to ensure 16-byte alignment, which WebGPU requires. For example, cameraOrigin is vec3&lt;f32&gt; which is 12 bytes. So before the next usable property (pixel00Loc, also vec3&lt;f32&gt;), we add 4 bytes of padding to reach 16.</p><p>frameCount tracks how many frames have been accumulated so far. The shader uses it for two things: seeding the PRNG (so each frame gets different random numbers) and computing the running average when accumulating samples across frames.</p><h4>Sphere</h4><pre>struct Sphere {<br>    center: vec3&lt;f32&gt;,<br>    radius: f32,<br>    albedo: vec3&lt;f32&gt;,<br>    matType: f32,<br>    matParam: f32,<br>    pad0: f32,<br>    pad1: f32,<br>    pad2: f32,<br>}</pre><p>Most properties map directly to the Sphere class in the CPU implementation. The additions are matParam and matType. matParam stores the fuzz value for metal materials or the refraction index for dielectric materials. matType indicates which material type it is. Moreover, it’s a float rather than an integer to keep alignment simple. The trailing pad0/pad1/pad2 fields round out the struct to 48 bytes.</p><h4>Ray and HitRecord</h4><pre>struct Ray {<br>    orig: vec3&lt;f32&gt;,<br>    dir: vec3&lt;f32&gt;,<br>}<br><br>struct HitRecord {<br>    t: f32,<br>    p: vec3&lt;f32&gt;,<br>    normal: vec3&lt;f32&gt;,<br>    frontFace: bool,<br>    sphereIndex: u32,<br>    didHit: bool,<br>}</pre><p>This is a straightforward translation of the Ray and HitRecord structs from the CPU implementation.</p><blockquote>Why there are no padding in HitRecord and Ray structs?</blockquote><p>The reason is that CameraParams and Sphere structs are passed as uniform and storage buffers respectively from the CPU to the GPU. But that is not the case for Ray and HitRecord. These are structs that are used only within the Compute shader code logic.</p><h4>Constants</h4><p>Next we have the constant definitions. Most of them are self-explanatory, so I won’t go through each one.</p><p>Worth noting though , I used AI to generate the PRNG (Pseudorandom Number Generator). WGSL doesn’t have a built-in random() like JavaScript’s Math.random(), so we need our own. The PRNG is used for random sampling, anti-aliasing jitter, and other stochastic processes in the shader.</p><h4>Buffer Bindings</h4><p>Next, we need to define the buffers that are created by the CPU and passed to the GPU.</p><p>WebGPU has a strict buffer binding mechanism, such that we need to ensure the binding points match on both the CPU and GPU code.</p><pre>@group(0) @binding(0) var&lt;uniform&gt; params: CameraParams;<br>@group(0) @binding(1) var&lt;storage, read&gt; spheres: array&lt;Sphere&gt;;<br>@group(0) @binding(2) var outputTex: texture_storage_2d&lt;bgra8unorm, write&gt;;<br>@group(0) @binding(3) var&lt;storage, read_write&gt; accumBuffer: array&lt;vec4&lt;f32&gt;&gt;;</pre><p>@group(X) @binding(Y) means that the buffer is in the group X and has a binding point of Y. Notice that we have used the same group number for each binding. <a href="https://toji.dev/webgpu-best-practices/bind-groups"><strong><em>WebGPU Best Practices — Bind Groups</em></strong></a> by “toji” is a great article that explains the use of different bind groups. However, in our implementation, there’s no repeated binding and we only dispatch the compute shader once. So, we don’t need to worry about the bind groups.</p><p>Looking at the types: CameraParams is a uniform because the shader only reads it and it stays constant during a dispatch. spheres is storage, read : a read-only array of all the sphere data. outputTex is a texture_storage_2d&lt;bgra8unorm, write&gt; : a write-only storage texture that holds the rendered pixels. And accumBuffer is storage, read_write because the shader both reads the previous frame’s accumulated color and writes the updated accumulation. It’s defined as array&lt;vec4&lt;f32&gt;&gt; (rather than a texture) because we need full 32-bit float precision for accumulation , a bgra8unorm texture would clamp to 8-bit per channel, losing information across frames.</p><h4>Pseudo Random Number Generator (PRNG)</h4><p>Here’s the PRNG implementation I mentioned earlier:</p><pre>// --- PRNG ---<br>var&lt;private&gt; rand_state: u32;<br><br>fn pcg_hash(seed: u32) -&gt; u32 {<br>    var state = seed * PCG_MULTIPLIER + PCG_INCREMENT;<br>    var word = ((state &gt;&gt; ((state &gt;&gt; 28u) + 4u)) ^ state) * PCG_MIX_MULTIPLIER;<br>    return (word &gt;&gt; 22u) ^ word;<br>}<br><br>fn rand() -&gt; f32 {<br>    rand_state = pcg_hash(rand_state);<br>    return f32(rand_state) / f32(0xffffffffu);<br>}</pre><h4>Utility Functions</h4><p>Next we have the utility functions that are used in the compute shader code. I tried to keep the implementation here as close to the CPU implementation as possible while also making them GPU-friendly.</p><p>Let’s take a look at each function.</p><p><strong>CPU Random Double:</strong></p><pre>export function randomDouble(min?: number, max?: number): number {<br>    if (min === undefined || max === undefined) {<br>        return Math.random();<br>    }<br>    return min + (max - min) * Math.random();<br>}</pre><p><strong>GPU Random Double:</strong></p><pre>fn randomDouble(min: f32, max: f32) -&gt; f32 {<br>    return min + (max - min) * rand();<br>}</pre><p><strong>CPU Random In Unit Disk:</strong></p><pre>static randomInUnitDisk(): Vec3 {<br>    const r = Math.sqrt(Math.random());<br>    const theta = 2 * Math.PI * Math.random();<br>    return new Vec3(r * Math.cos(theta), r * Math.sin(theta), 0);<br>}</pre><p><strong>GPU Random In Unit Disk:</strong></p><pre>fn randomInUnitDisk() -&gt; vec3&lt;f32&gt; {<br>    let r = sqrt(rand());<br>    let theta = TWO_PI * rand();<br>    return vec3&lt;f32&gt;(r * cos(theta), r * sin(theta), 0.0);<br>}</pre><p>As for randomInUnitDisk, I used the polar coordinate system to generate a random point in the unit disk instead of using a rejection sampling method which was used in <strong>Ray Tracing in One Weekend</strong>. This is because it is not GPU friendly to use rejection sampling method, as it may lead to thread divergence. Therefore, I also changed the randomInUnitDisk function in the CPU implementation to use the polar coordinate system to match with the GPU implementation.</p><p><strong>CPU Random Unit Vector:</strong></p><pre>export function randomUnitVector(): Vec3 {<br>  const z = 2.0 * Math.random() - 1.0;<br>  const r = Math.sqrt(1.0 - z * z);<br>  const theta = 2 * Math.PI * Math.random();<br>  return new Vec3(r * Math.cos(theta), r * Math.sin(theta), z);<br>}</pre><p><strong>GPU Random Unit Vector:</strong></p><pre>fn randomUnitVector() -&gt; vec3&lt;f32&gt; {<br>    let z = 2.0 * rand() - 1.0;<br>    let r = sqrt(max(0.0, 1.0 - z * z));<br>    let phi = TWO_PI * rand();<br>    return vec3&lt;f32&gt;(r * cos(phi), r * sin(phi), z);<br>}</pre><p>Same story as randomInUnitDisk : I changed the CPU implementation to use polar coordinates to match the GPU version.</p><p>You might also notice that the CPU codebase has a randomOnHemisphere() function, but the GPU shader doesn’t use it. That’s because the Lambertian scattering already achieves the same effect with rec.normal + randomUnitVector() , if the random vector points away from the surface, adding it to the normal naturally pulls it back toward the hemisphere. So there’s no need for a separate hemisphere rejection step.</p><p><strong>CPU Ray At Function (</strong>src/math/Ray.ts<strong>):</strong></p><pre>at(t: number): Point3 {<br>    return add(this.orig, multiplyScalar(t, this.dir));<br>}</pre><p><strong>GPU Ray At Function:</strong></p><pre>fn rayAt(r: Ray, t: f32) -&gt; vec3&lt;f32&gt; {<br>    return r.orig + t * r.dir;<br>}</pre><p><strong>HitSphere Function</strong></p><p>The below is the CPU implementaion (Refer to src/scene/Sphere.ts ).</p><pre>hit(r: Ray, rayInterval: Interval, rec: HitRecord): boolean {<br>    const oc = subtract(this.center, r.origin());<br>    const a = r.direction().lengthSquared();<br>    const h = dot(r.direction(), oc);<br>    const c = oc.lengthSquared() - this.radius * this.radius;<br><br>    const discriminant = h * h - a * c;<br>    if (discriminant &lt; 0) return false;<br><br>    const sqrtd = Math.sqrt(discriminant);<br><br>    // Find the nearest root that lies in the acceptable range.<br>    let root = (h - sqrtd) / a;<br>    if (!rayInterval.surrounds(root)) {<br>        root = (h + sqrtd) / a;<br>        if (!rayInterval.surrounds(root)) {<br>            return false;<br>        }<br>    }<br><br>    rec.t = root;<br>    rec.p = r.at(rec.t);<br>    const outwardNormal = divideScalar(subtract(rec.p, this.center), this.radius);<br>    rec.setFaceNormal(r, outwardNormal);<br>    rec.mat = this.mat;<br><br>    return true;<br>}</pre><p>The next one is the GPU implementation.</p><pre>fn hitSphere(center: vec3&lt;f32&gt;, radius: f32, r: Ray, tMin: f32, tMax: f32, rec: ptr&lt;function, HitRecord&gt;) -&gt; bool {<br>    let oc = center - r.orig;<br>    let a = dot(r.dir, r.dir);<br>    let h = dot(r.dir, oc);<br>    let c = dot(oc, oc) - radius * radius;<br>    let discriminant = h * h - a * c;<br><br>    if (discriminant &lt; 0.0) { return false; }<br>    let sqrtd = sqrt(discriminant);<br><br>    var root = (h - sqrtd) / a;<br>    if (root &lt;= tMin || root &gt;= tMax) {<br>        //Doesn&#39;t surround the interval with the smaller root, try the larger root<br>        root = (h + sqrtd) / a;<br>        if (root &lt;= tMin || root &gt;= tMax) {<br>            // Doesn&#39;t surround the interval with the larger root, return false<br>            return false;<br>        }<br>    }<br><br>    (*rec).t = root;<br>    (*rec).p = rayAt(r, root);<br>    let outwardNormal = ((*rec).p - center) / radius;<br>    (*rec).frontFace = dot(r.dir, outwardNormal) &lt; 0.0;<br>    if ((*rec).frontFace) {<br>        (*rec).normal = outwardNormal;<br>    } else {<br>        (*rec).normal = -outwardNormal;<br>    }<br><br>    return true;<br>}</pre><p>center refers to the sphere center, radius refers to the sphere radius, r refers to the ray, tMin and tMax refer to the interval of the ray, and rec refers to the hit record. We use pointer ptr&lt;function, HitRecord&gt; instead of HitRecord because we want to update the hit record in place.</p><p><strong>HitWorld Function</strong></p><p>The following is the CPU implementation (Refer to src/scene/HittableList.ts).</p><pre>hit(r: Ray, rayInterval: Interval, rec: HitRecord): boolean {<br>    let tempRec = new HitRecord();<br>    let hitAnything = false;<br>    let closestSoFar = rayInterval.max;<br><br>    for (const object of this.objects) {<br>        const currInt = new Interval(rayInterval.min, closestSoFar);<br>        if (object.hit(r, currInt, tempRec)) {<br>            hitAnything = true;<br>            closestSoFar = tempRec.t;<br>            // Copy tempRec properties to rec<br>            rec.t = tempRec.t;<br>            rec.p = tempRec.p;<br>            rec.normal = tempRec.normal;<br>            rec.frontFace = tempRec.frontFace;<br>            rec.mat = tempRec.mat;<br>        }<br>    }<br><br>    return hitAnything;<br>}</pre><p>And then we have it’s GPU equivalent.</p><pre>fn hitWorld(r: Ray) -&gt; HitRecord {<br>    var rec: HitRecord;<br>    rec.didHit = false;<br>    var closestSoFar = T_MAX;<br><br>    let numSpheres = arrayLength(&amp;spheres);<br>    for (var i = 0u; i &lt; numSpheres; i++) {<br>        let s = spheres[i];<br>        var tempRec: HitRecord;<br>        if (hitSphere(s.center, s.radius, r, T_MIN, closestSoFar, &amp;tempRec)) {<br>            closestSoFar = tempRec.t;<br>            rec = tempRec;<br>            rec.sphereIndex = i;<br>            rec.didHit = true;<br>        }<br>    }<br>    return rec;<br>}</pre><p>Here, instead of returning a boolean and mutating a passed-in record (like the CPU version), the WGSL version returns the HitRecord struct directly with a didHit field to indicate whether a hit occurred. We also store sphereIndex so the caller knows which sphere was hit . The CPU version doesn’t need this because it has access to the material via rec.mat.</p><p><strong>Reflectance Function</strong></p><pre>static reflectance(cosine: number, refractionIndex: number): number {<br>    // Use Schlick&#39;s approximation for reflectance.<br>    let r0 = (1 - refractionIndex) / (1 + refractionIndex);<br>    r0 = r0 * r0;<br>    return r0 + (1 - r0) * Math.pow(1 - cosine, 5);<br>}</pre><p>In the above code block, you can find the CPU implementation in src/materials/Dielectric.ts whereas the below code block is it’s GPU equivalent.</p><pre>fn reflectance(cosine: f32, ref_idx: f32) -&gt; f32 {<br>    var r0 = (1.0 - ref_idx) / (1.0 + ref_idx);<br>    r0 = r0 * r0;<br>    return r0 + (1.0 - r0) * pow((1.0 - cosine), SCHLICK_EXPONENT);<br>}</pre><p>In the CPU implementation, this lives inside the Dielectric class since reflectance is specific to dielectric materials. But WGSL doesn’t have classes, so we pull it out as a standalone function that gets called in the dielectric branch of rayColor.</p><p><strong>RayColor Function</strong></p><p>Next we have an important function of the ray tracing logic. Here’s the CPU implementation (Refer to src/render/Camera.ts).</p><pre>private rayColor(r: Ray, depth: number, world: Hittable): Color {<br>    if (depth &lt;= 0) {<br>        return new Vec3(0, 0, 0);<br>    }<br><br>    const rec = new HitRecord();<br>    const intVal = new Interval(0.001, Infinity);<br><br>    if (world.hit(r, intVal, rec)) {<br>        if (rec.mat) {<br>            const scatterResult = rec.mat.scatter(r, rec);<br>            if (scatterResult) {<br>                const { attenuation, scattered } = scatterResult;<br>                const c = this.rayColor(scattered, depth - 1, world);<br>                return new Vec3(<br>                    attenuation.x() * c.x(),<br>                    attenuation.y() * c.y(),<br>                    attenuation.z() * c.z(),<br>                );<br>            }<br>        }<br>        return new Vec3(0, 0, 0);<br>    }<br><br>    const unitDir = unitVector(r.direction());<br>    const a = 0.5 * (unitDir.y() + 1.0);<br>    const color1 = multiplyScalar(1.0 - a, SKY_COLOR_HORIZON);<br>    const color2 = multiplyScalar(a, SKY_COLOR_ZENITH);<br>    return add(color1, color2);<br>}</pre><p>Then we have it’s GPU translation.</p><pre>fn rayColor(r_in: Ray) -&gt; vec3&lt;f32&gt; {<br>    var current_ray = r_in;<br>    var accumulated_color = vec3&lt;f32&gt;(1.0, 1.0, 1.0);<br>    var final_color = vec3&lt;f32&gt;(0.0, 0.0, 0.0);<br><br>    for (var depth = 0u; depth &lt; params.maxDepth; depth++) {<br>        let rec = hitWorld(current_ray);<br><br>        if (!rec.didHit) {<br>            let unit_dir = normalize(current_ray.dir);<br>            let a = 0.5 * (unit_dir.y + 1.0);<br>            let sky_color = (1.0 - a) * SKY_COLOR_HORIZON + a * SKY_COLOR_ZENITH;<br>            final_color = accumulated_color * sky_color;<br>            break;<br>        }<br><br>        let s = spheres[rec.sphereIndex];<br>        var scattered_dir: vec3&lt;f32&gt;;<br>        var attenuation: vec3&lt;f32&gt;;<br><br>        //https://www.w3.org/TR/WGSL/#reflect-builtin<br>        //https://www.w3.org/TR/WGSL/#refract-builtin<br><br>        if (s.matType == MAT_LAMBERTIAN) { // Lambertian<br>            scattered_dir = rec.normal + randomUnitVector();<br>            if (dot(scattered_dir, scattered_dir) &lt; NEAR_ZERO_THRESHOLD) {<br>                scattered_dir = rec.normal;<br>            }<br>            attenuation = s.albedo;<br>        } else if (s.matType == MAT_METAL) { // Metal<br>            scattered_dir = reflect(normalize(current_ray.dir), rec.normal) + s.matParam * randomUnitVector();<br>            attenuation = s.albedo;<br>            if (dot(scattered_dir, rec.normal) &lt;= 0.0) {<br>                break;<br>            }<br>        } else { // Dielectric<br>            attenuation = vec3&lt;f32&gt;(1.0, 1.0, 1.0);<br>            let ri = select(s.matParam, 1.0 / s.matParam, rec.frontFace);<br>            let unitDirection = normalize(current_ray.dir);<br><br>            let cosTheta = min(dot(-unitDirection, rec.normal), 1.0);<br>            let sinTheta = sqrt(1.0 - cosTheta * cosTheta);<br>            let cannotRefract = (ri * sinTheta) &gt; 1.0;<br><br>            if (cannotRefract || reflectance(cosTheta, ri) &gt; rand()) {<br>                scattered_dir = reflect(unitDirection, rec.normal);<br>            } else {<br>                // wgsl has a refract function, but standard refract is refract(i, n, eta)<br>                scattered_dir = refract(unitDirection, rec.normal, ri);<br>            }<br>        }<br><br>        current_ray.orig = rec.p;<br>        current_ray.dir = scattered_dir;<br>        accumulated_color *= attenuation;<br>    }<br><br>    return final_color;<br>}</pre><p>This is probably the most interesting translation. The CPU version is recursive because rayColor calls itself with depth — 1. WGSL doesn’t support recursion, so we flatten it into a loop that accumulates the color multiplicatively. The accumulated_color variable tracks the product of all attenuation values along the ray’s path, and final_color only gets set when the ray finally misses all objects and hits the sky.</p><p>The other big change is materials. On the CPU, each material class (Lambertian, Metal, Dielectric) has its own .scatter() method. In WGSL there are no classes or virtual dispatch, so all the scattering logic is inlined into rayColor as if/else branches on matType. Also, WGSL provides built-in reflect and refract functions, which saves us from having to implement those ourselves.</p><h4><strong>The </strong><strong>main Entry Point — Putting It All Together</strong></h4><p>On the CPU side, the Camera.render() method handles pixel iteration, ray generation, color accumulation, gamma correction, and canvas output (all in one place). Here’s how the GPU shader’s main function handles the same responsibilities:</p><p>A few things to note about this entry point:</p><ul><li><strong>No pixel loops</strong> — each GPU thread processes one pixel, identified by GlobalInvocationID. The bounds check at the top replaces the CPU’s nested for loops.</li><li><strong>PRNG initialization</strong> — params.frameCount combined with the pixel coordinates ensures each thread and each frame gets a unique random seed.</li><li><strong>Two accumulation approaches</strong> — the shader supports both per-dispatch sampling (loop over samplesPerPixel inside the shader) and progressive accumulation (1 sample per dispatch, accumulated across frames via accumBuffer). I implemented both to compare performance. Notably, I didn’t see much improvement with the progressive approach — possibly something I could look into more. The progressive mode also doesn’t play well with interactive camera controls since moving the camera invalidates the accumulated data.</li></ul><p>Here’s the full shader main funcion code:</p><pre>@compute @workgroup_size(WORKGROUP_X, WORKGROUP_Y, 1)<br>fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3&lt;u32&gt;) {<br>    let dims = textureDimensions(outputTex);<br>    if (GlobalInvocationID.x &gt;= dims.x || GlobalInvocationID.y &gt;= dims.y) {<br>        return;<br>    }<br><br>    let pixelIndex = GlobalInvocationID.y * dims.x + GlobalInvocationID.x;<br><br>    rand_state = pcg_hash(<br>        GlobalInvocationID.x * SEED_PRIME_X<br>        + GlobalInvocationID.y * SEED_PRIME_Y<br>        + params.frameCount * SEED_PRIME_FRAME<br>    );<br><br>    var pixelColor = vec3&lt;f32&gt;(0.0);<br><br>    for (var s = 0u; s &lt; params.samplesPerPixel; s++) {<br>        let u = f32(GlobalInvocationID.x) + randomDouble(-AA_JITTER, AA_JITTER);<br>        let v = f32(GlobalInvocationID.y) + randomDouble(-AA_JITTER, AA_JITTER);<br><br>        let pixelSample = params.pixel00Loc + (u * params.deltaU) + (v * params.deltaV);<br><br>        var rayOrigin = params.cameraOrigin;<br>        if (params.defocusAngle &gt; 0.0) {<br>            let p = randomInUnitDisk();<br>            rayOrigin += p.x * params.defocusDiskU + p.y * params.defocusDiskV;<br>        }<br><br>        let rayDirection = pixelSample - rayOrigin;<br>        let r = Ray(rayOrigin, rayDirection);<br><br>        pixelColor += rayColor(r);<br>    }<br><br>    pixelColor /= f32(params.samplesPerPixel);<br><br>    // Accumulate into persistent buffer<br>    var accumulated: vec3&lt;f32&gt;;<br>    if (params.frameCount == 0u) {<br>        accumulated = pixelColor;<br>    } else {<br>        let prev = accumBuffer[pixelIndex];<br>        accumulated = prev.xyz + pixelColor;<br>    }<br>    accumBuffer[pixelIndex] = vec4&lt;f32&gt;(accumulated, 0.0);<br><br>    // Compute running average and apply gamma correction<br>    let avgColor = accumulated / f32(params.frameCount + 1u);<br>    let gammaColor = vec3&lt;f32&gt;(sqrt(avgColor.x), sqrt(avgColor.y), sqrt(avgColor.z));<br><br>    textureStore(outputTex, vec2&lt;i32&gt;(i32(GlobalInvocationID.x), i32(GlobalInvocationID.y)), vec4&lt;f32&gt;(gammaColor, 1.0));<br>}</pre><p>Let’s now zoom in on specific parts of the rendering logic to compare the CPU and GPU approaches more closely.</p><p><strong>Ray Generation: getRay + sampleSquare → Inlined Sampling</strong></p><p>In the CPU version, ray generation is split into two helper methods:</p><pre>private getRay(u: number, v: number): Ray {<br>    const offset = this.sampleSquare();<br>    const pixelSample = add(<br>        this.pixel00Loc,<br>        add(<br>            multiplyScalar(u + offset.x(), this.deltaU),<br>            multiplyScalar(v + offset.y(), this.deltaV),<br>        ),<br>    );<br><br>    const rayOrigin =<br>        this.defocusAngle &lt;= 0 ? this.cameraOrigin : this.defocusDiskSample();<br>    const rayDirection = subtract(pixelSample, rayOrigin);<br><br>    return new Ray(rayOrigin, rayDirection);<br>}<br><br>private sampleSquare(): Vec3 {<br>    return new Vec3(randomDouble() - 0.5, randomDouble() - 0.5, 0);<br>}</pre><p>In the GPU version, this is inlined directly in main:</p><pre>let u = f32(GlobalInvocationID.x) + randomDouble(-AA_JITTER, AA_JITTER);<br>let v = f32(GlobalInvocationID.y) + randomDouble(-AA_JITTER, AA_JITTER);<br><br>let pixelSample = params.pixel00Loc + (u * params.deltaU) + (v * params.deltaV);<br><br>var rayOrigin = params.cameraOrigin;<br>if (params.defocusAngle &gt; 0.0) {<br>    let p = randomInUnitDisk();<br>    rayOrigin += p.x * params.defocusDiskU + p.y * params.defocusDiskV;<br>}<br><br>let rayDirection = pixelSample - rayOrigin;<br>let r = Ray(rayOrigin, rayDirection);</pre><p>Notice how sampleSquare() is replaced by adding randomDouble(-AA_JITTER, AA_JITTER) directly to the pixel coordinates. The effect is identical: a random offset in [-0.5, 0.5] for anti-aliasing jitter, but it avoids creating a temporary Vec3 object.</p><p><strong>Defocus Blur: defocusDiskSample → Inline</strong></p><p>Similarly, the CPU’s defocusDiskSample method:</p><pre>private defocusDiskSample(): Point3 {<br>    const p = Vec3.randomInUnitDisk();<br>    return add(<br>        this.cameraOrigin,<br>        add(<br>            multiplyScalar(p.x(), this.defocusDiskU),<br>            multiplyScalar(p.y(), this.defocusDiskV),<br>        ),<br>    );<br>}</pre><p>becomes a simple inline block in the GPU shader:</p><pre>var rayOrigin = params.cameraOrigin;<br>if (params.defocusAngle &gt; 0.0) {<br>    let p = randomInUnitDisk();<br>    rayOrigin += p.x * params.defocusDiskU + p.y * params.defocusDiskV;<br>}</pre><p>The logic is the same. The GPU version benefits from WGSL’s operator overloading for vector math (e.g., += with vec3&lt;f32&gt;) which makes the code more concise compared to the CPU version’s explicit function calls like add() and multiplyScalar().</p><p><strong>Gamma Correction and Output</strong></p><p>In the CPU implementation, gamma correction and output happen together with per-channel clamping:</p><pre>let r = pixelColor.x() * this.pixelSamplesScale; // divide by sample count<br>let g = pixelColor.y() * this.pixelSamplesScale;<br>let b = pixelColor.z() * this.pixelSamplesScale;<br><br>r = Math.sqrt(r); // gamma correction (gamma = 2.0)<br>g = Math.sqrt(g);<br>b = Math.sqrt(b);<br><br>const intensity = new Interval(0.0, 0.999);<br>data[index++] = Math.floor(256 * intensity.clamp(r)); // write to ImageData<br>data[index++] = Math.floor(256 * intensity.clamp(g));<br>data[index++] = Math.floor(256 * intensity.clamp(b));<br>data[index++] = 255; // Alpha</pre><p>The GPU version does the same gamma correction but writes to a texture instead:</p><pre>pixelColor /= f32(params.samplesPerPixel);<br>....<br><br>let avgColor = accumulated / f32(params.frameCount + 1u);<br>let gammaColor = vec3&lt;f32&gt;(sqrt(avgColor.x), sqrt(avgColor.y), sqrt(avgColor.z));<br><br>textureStore(outputTex, vec2&lt;i32&gt;(...), vec4&lt;f32&gt;(gammaColor, 1.0));</pre><p>pixelColor /= f32(params.samplesPerPixel); and let avgColor = accumulated / f32(params.frameCount + 1u); have different purposes. The former one is GPU equivalent logic for the CPU’s following part:</p><pre>let r = pixelColor.x() * this.pixelSamplesScale;<br>let g = pixelColor.y() * this.pixelSamplesScale;<br>let b = pixelColor.z() * this.pixelSamplesScale;</pre><p>The latter code line (let avgColor = … ) is GPU specific. Remember the approach for accumulating the pixel color according to the sample size? If we are using the accumulating approach, params.samplesPerPixel is going to be 1 . Hence, we need to divide again to obtain the actual average color.</p><p>The GPU version doesn’t need explicit clamping to [0, 0.999] or conversion to [0, 255] integers because the output texture format bgra8unorm automatically clamps values to [0.0, 1.0] and maps them to 8-bit unsigned integers.</p><p>Also notice how the CPU writes to ImageData (a flat RGBA byte array accessed via putImageData), while the GPU writes directly to a texture via textureStore. The CPU must also periodically yield to the browser with setTimeout to keep the UI responsive, something the GPU doesn’t need to worry about since the entire render completes in a single dispatch.</p><h4><strong>WebGPU Renderer — The CPU Side</strong></h4><p>So far we’ve looked at the compute shader (the GPU side). But the GPU doesn’t run on its own — it needs a CPU-side driver to initialize the device, create buffers, upload data, and dispatch the shader. That’s the job of WebGPURenderer.ts.</p><p><strong>Initialization</strong></p><p>Before we can run any GPU code, we need to acquire a WebGPU device. This is an asynchronous, multi-step process (src/gpu/WebGPURenderer.ts):</p><pre>public static async init(): Promise&lt;WebGPURenderer | null&gt; {<br>    if (!navigator.gpu) {<br>        alert(&quot;WebGPU is not supported by your browser.&quot;);<br>        return null;<br>    }<br><br>    const adapter = await navigator.gpu.requestAdapter({<br>        powerPreference: &quot;high-performance&quot;,<br>    });<br>    if (!adapter) {<br>        alert(&quot;Failed to get WebGPU adapter.&quot;);<br>        return null;<br>    }<br><br>    const device = await adapter.requestDevice({<br>        requiredFeatures: [&quot;timestamp-query&quot;, &quot;bgra8unorm-storage&quot;],<br>        requiredLimits: {<br>            maxComputeWorkgroupStorageSize:<br>                adapter.limits.maxComputeWorkgroupStorageSize,<br>            maxComputeInvocationsPerWorkgroup:<br>                adapter.limits.maxComputeInvocationsPerWorkgroup,<br>            maxComputeWorkgroupSizeX: adapter.limits.maxComputeWorkgroupSizeX,<br>            maxComputeWorkgroupSizeY: adapter.limits.maxComputeWorkgroupSizeY,<br>            maxComputeWorkgroupSizeZ: adapter.limits.maxComputeWorkgroupSizeZ,<br>            maxComputeWorkgroupsPerDimension:<br>                adapter.limits.maxComputeWorkgroupsPerDimension,<br>        },<br>    });<br><br>    return new WebGPURenderer(device);<br>}</pre><ol><li><strong>navigator.gpu</strong> — check if WebGPU is supported at all.</li><li><strong>requestAdapter</strong> — get a handle to a physical GPU. We request ”high-performance” to prefer a discrete GPU over an integrated one.</li><li><strong>requestDevice</strong>— create a logical device with the features we need:<br>-”timestamp-query” — lets us measure GPU execution time in nanoseconds.<br>-”bgra8unorm-storage” — lets us use bgra8unorm textures as storage textures (needed because the canvas format is bgra8unorm).<br>-We also request the adapter’s maximum compute limits so we don’t artificially constrain ourselves below what the hardware supports.</li></ol><p>The constructor also sets up <strong>timestamp-query</strong> buffers — a resolve buffer and a result buffer — which are used later to measure how long each compute pass takes on the GPU.</p><p><strong>Scene Serialization</strong></p><p>Before we can render, we need to get the scene data onto the GPU. The SceneSerializer.ts handles this by packing each Sphere object into a flat Float32Array:</p><pre>// Layout per Sphere (12 floats = 48 bytes, aligned for WGSL):<br>// [0, 1, 2]   : center.x, center.y, center.z<br>// [3]         : radius<br>// [4, 5, 6]   : albedo.r, albedo.g, albedo.b<br>// [7]         : materialType (0.0 = Lambertian, 1.0 = Metal, 2.0 = Dielectric)<br>// [8]         : materialParam (fuzz for Metal, refractionIndex for Dielectric)<br>// [9, 10, 11] : padding (0.0)</pre><p>This flat layout matches the Sphere struct in the WGSL shader byte-for-byte. The key challenge here is the material system. On the CPU, we have separate classes such as Lambertian, Metal, Dielectric ; each with their own properties and scatter logic. But WGSL has no inheritance, interfaces, or polymorphism. So the serializer flattens each material into just two numbers: a type tag and a single parameter.</p><p>Here’s the core of the serialization:</p><pre>const mat = sphere.mat;<br>if (mat instanceof Lambertian) {<br>  buffer[offset + 4] = mat.albedo.x();<br>  buffer[offset + 5] = mat.albedo.y();<br>  buffer[offset + 6] = mat.albedo.z();<br>  buffer[offset + 7] = MaterialType.LAMBERTIAN; // 0.0<br>  buffer[offset + 8] = 0.0; // unused<br>} else if (mat instanceof Metal) {<br>  buffer[offset + 4] = mat.albedo.x();<br>  buffer[offset + 5] = mat.albedo.y();<br>  buffer[offset + 6] = mat.albedo.z();<br>  buffer[offset + 7] = MaterialType.METAL; // 1.0<br>  buffer[offset + 8] = mat.fuzz;<br>} else if (mat instanceof Dielectric) {<br>  buffer[offset + 4] = 1.0; // dielectrics are always white<br>  buffer[offset + 5] = 1.0;<br>  buffer[offset + 6] = 1.0;<br>  buffer[offset + 7] = MaterialType.DIELECTRIC; // 2.0<br>  buffer[offset + 8] = mat.refractionIndex;<br>}</pre><p>The instanceof checks on the CPU side become float comparisons (matType == MAT_LAMBERTIAN, etc.) in the shader’s if/else branches. The albedo, fuzz, and refractionIndex properties from three different classes all get packed into the same struct fields (albedo, matParam).</p><p><strong>Pipeline Setup</strong></p><p>The initializePipeline method creates all the GPU resources needed for rendering. Let’s walk through each step:</p><p><strong><em>Canvas Context Configuration</em></strong></p><pre>this.currentContext = canvas.getContext(&quot;webgpu&quot;) as GPUCanvasContext;<br><br>const presentationFormat = navigator.gpu.getPreferredCanvasFormat();<br>this.currentContext.configure({<br>  device: this.device,<br>  format: presentationFormat,<br>  alphaMode: &quot;premultiplied&quot;,<br>  usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,<br>});</pre><p>We configure the canvas with COPY_DST usage because we’ll copy the compute shader’s output texture into the canvas texture each frame — the compute shader can’t write directly to the canvas.</p><p><strong><em>Buffer Creation</em></strong></p><p>Four GPU buffers are created, each corresponding to a binding in the shader:</p><pre>// binding 0: Camera parameters (uniform)<br>this.paramsBuffer = this.device.createBuffer({<br>  size: this.getParamBufferSizeInBytes(),<br>  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,<br>});<br><br>// binding 1: Sphere data (storage, read-only)<br>const sceneData = serializeScene(world);<br>this.sceneBuffer = this.device.createBuffer({<br>  size: sceneData.byteLength,<br>  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,<br>});<br>this.device.queue.writeBuffer(this.sceneBuffer, 0, sceneData.buffer);<br><br>// binding 2: Output texture (storage, write-only)<br>this.computeTexture = this.device.createTexture({<br>  size: [this.imgWidth, imgHeight, 1],<br>  format: presentationFormat,<br>  usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_SRC,<br>});<br><br>// binding 3: Accumulation buffer (storage, read-write)<br>const accumBufferSize =<br>  this.imgWidth * imgHeight * 4 * Float32Array.BYTES_PER_ELEMENT;<br>this.accumBuffer = this.device.createBuffer({<br>  size: accumBufferSize,<br>  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,<br>});</pre><p>Notice how the usage flags on each buffer match the access patterns declared in the shader. The scene buffer uses COPY_DST because we write data into it from the CPU; the compute texture uses COPY_SRC because we’ll copy it to the canvas texture afterwards.</p><p><strong><em>Pipeline and Bind Group</em></strong></p><pre>const module = this.device.createShaderModule({ code: wgslCode });<br>this.pipeline = this.device.createComputePipeline({<br>  layout: &quot;auto&quot;,<br>  compute: { module, entryPoint: &quot;main&quot; },<br>});<br><br>this.bindGroup = this.device.createBindGroup({<br>  layout: this.pipeline.getBindGroupLayout(0),<br>  entries: [<br>    { binding: 0, resource: { buffer: this.paramsBuffer } },<br>    { binding: 1, resource: { buffer: this.sceneBuffer } },<br>    { binding: 2, resource: this.computeTexture.createView() },<br>    { binding: 3, resource: { buffer: this.accumBuffer } },<br>  ],<br>});</pre><p>The layout: “auto” tells WebGPU to infer the bind group layout from the shader’s @group and @binding annotations. The bind group then connects each binding index to the actual GPU resource. This is where the @group(0) @binding(0) declarations in the shader meet their CPU-side counterparts.</p><p><strong><em>Rendering a Frame</em></strong></p><p>The renderFrame method is where the actual GPU work happens. It follows this sequence:</p><p><strong>1. <em>Camera Parameter Packing</em></strong></p><p>Before packing, the renderFrame method recomputes all the camera math — viewport dimensions, basis vectors (u, v, w), pixel00Loc, deltaU/deltaV, and defocus disk vectors. This is essentially the same math as Camera.initialize() on the CPU side. The difference is that the CPU computes it once before the render loop, while the GPU version recomputes it every frame. Why? Because in real-time mode, the camera can move between frames (via WASD + mouse controls), so we need fresh parameters each dispatch.</p><p>Also worth mentioning is how we calculate the buffer size. The getParamBufferSizeInBytes method sums up all the fields (including padding) and then rounds up to the nearest multiple of 16:</p><pre>const alignment = 16;<br>bytes = Math.ceil(bytes / alignment) * alignment;</pre><p>This is required because WGSL structs align to their largest member’s alignment. Since CameraParams contains vec3&lt;f32&gt; (which has 16-byte alignment), the entire struct’s size must be a multiple of 16. In our case, the raw fields add up to 108 bytes, which gets rounded to 112.</p><p>The packed data uses a Float32Array/Uint32Array pair that shares the same ArrayBuffer:</p><pre>const paramsBufferData = new ArrayBuffer(this.getParamBufferSizeInBytes());<br>const paramsF32 = new Float32Array(paramsBufferData);<br>const paramsU32 = new Uint32Array(paramsBufferData);<br><br>paramsF32[0] = cameraOrigin.x(); // offset 0: cameraOrigin.x<br>paramsF32[1] = cameraOrigin.y(); // offset 1: cameraOrigin.y<br>paramsF32[2] = cameraOrigin.z(); // offset 2: cameraOrigin.z<br>// offset 3: padding (skipped)<br>paramsF32[4] = pixel00Loc.x(); // offset 4: pixel00Loc.x<br>// ... and so on<br><br>this.device.queue.writeBuffer(this.paramsBuffer, 0, paramsBufferData);</pre><p>We use two typed array views (Float32Array and Uint32Array) over the same ArrayBuffer because the struct has mixed types — f32 for vectors and u32 for samplesPerPixel, maxDepth, and frameCount. The index offsets (0, 1, 2, skip 3, 4, 5, 6, skip 7, …) reflect the padding fields we discussed earlier.</p><p><strong><em>2. Command Encoding and Dispatch</em></strong></p><pre>const encoder = this.device.createCommandEncoder();<br>const computePass = encoder.beginComputePass({<br>  timestampWrites: {<br>    querySet: this.timestampQueries,<br>    beginningOfPassWriteIndex: 0,<br>    endOfPassWriteIndex: 1,<br>  },<br>});<br><br>computePass.setPipeline(this.pipeline);<br>computePass.setBindGroup(0, this.bindGroup);<br>computePass.dispatchWorkgroups(<br>  Math.ceil(this.imgWidth / 16),<br>  Math.ceil(imgHeight / 16),<br>  1,<br>);<br>computePass.end();</pre><p>The dispatchWorkgroups call determines how many workgroups to launch. Since each workgroup is 16×16 threads (matching @workgroup_size(WORKGROUP_X, WORKGROUP_Y, 1) in the shader), we need ⌈width/16⌉ × ⌈height/16⌉ workgroups to cover every pixel. The Math.ceil ensures we don’t miss edge pixels when the image dimensions aren’t multiples of 16 (the bounds check in the shader handles the excess threads).</p><p><strong><em>3. Texture Copy</em></strong></p><pre>encoder.copyTextureToTexture(<br>  { texture: this.computeTexture },<br>  { texture: this.currentContext.getCurrentTexture() },<br>  [this.imgWidth, imgHeight, 1],<br>);</pre><p>The compute shader writes to computeTexture (a storage texture), but the canvas displays from its own swap-chain texture. This copy bridges the two: it’s essentially the GPU equivalent of ctx.putImageData().</p><p><strong><em>4. GPU Timing</em></strong></p><pre>encoder.resolveQuerySet(this.timestampQueries, 0, 2, this.tsResolveBuffer, 0);<br>encoder.copyBufferToBuffer(this.tsResolveBuffer, 0, this.tsResultBuffer, 0, ...);<br><br>this.device.queue.submit([encoder.finish()]);<br>await this.device.queue.onSubmittedWorkDone();<br><br>await this.tsResultBuffer.mapAsync(GPUMapMode.READ);<br>const times = new BigInt64Array(this.tsResultBuffer.getMappedRange());<br>const gpuTimeNs = Number(times[1] - times[0]);<br>this.tsResultBuffer.unmap();<br><br>return gpuTimeNs / 1_000_000; // convert nanoseconds to milliseconds</pre><p>The timestamp queries record the GPU clock at the beginning and end of the compute pass. After the work completes, we read back those timestamps, subtract to get elapsed nanoseconds, and convert to milliseconds. This gives us accurate GPU-side timing that excludes CPU overhead and queue latency.</p><p><strong><em>Two Rendering Modes</em></strong></p><p>The render method supports two strategies for multi-sample rendering:</p><pre>async render(world: HittableList, canvas: HTMLCanvasElement, onProgress) {<br>    await this.initializePipeline(world, canvas);<br>    this.resetAccumulation();<br><br>    if (this.useAccumulation) {<br>        // Progressive: N dispatches of 1 sample each<br>        let totalGpuTimeMs = 0;<br>        for (let s = 0; s &lt; this.samplesPerPixel; s++) {<br>            const frameTime = await this.renderFrame();<br>            if (frameTime !== undefined) totalGpuTimeMs += frameTime;<br>            onProgress((s + 1) / this.samplesPerPixel);<br>        }<br>        return totalGpuTimeMs;<br>    } else {<br>        // Batch: 1 dispatch of N samples<br>        onProgress(0.5);<br>        const time = await this.renderFrame();<br>        onProgress(1.0);<br>        return time;<br>    }<br>}</pre><ul><li><strong>Accumulation mode</strong> (useAccumulation = true): dispatches the shader N times, each with samplesPerPixel = 1. Each frame’s result is accumulated in the accumBuffer, and the running average is computed in the shader using frameCount. This allows progressive refinement where the image improves gradually over time.</li><li><strong>Batch mode </strong>(useAccumulation = false): dispatches the shader once with samplesPerPixel = N. All samples are computed in a single pass within the shader’s sample loop. This is simpler but the user sees nothing until the entire render is done.</li></ul><p>The accumulation approach also resets (resetAccumulation()) when the camera moves, since accumulated samples from a previous viewpoint would be invalid for the new one.</p><h3>Usage</h3><p>To use the GPU implementation, I have set up a util function as below:</p><pre>export async function handleGPURender(<br>  rendererInstance: WebGPURenderer,<br>  currentCanvas: HTMLCanvasElement,<br>  world: HittableList,<br>  canvasContainer: HTMLDivElement,<br>  progressBar: HTMLDivElement,<br>  progressText: HTMLSpanElement,<br>  timeText: HTMLSpanElement,<br>  isRealtime: boolean,<br>  params: RenderParams,<br>  cameraController: RealtimeCameraController | null,<br>  onCameraUpdate: (lookFrom: Vec3, lookAt: Vec3) =&gt; void<br>): Promise&lt;{ durationMs?: string, newCameraController: RealtimeCameraController | null, isRealtimeActive: boolean }&gt; {<br>  rendererInstance.setCamData(<br>    params.aspectRatio,<br>    params.imgWidth,<br>    params.samplesPerPixel,<br>    params.maxDepth,<br>    params.vfov,<br>  );<br>  rendererInstance.lookFrom = params.lookFromVec;<br>  rendererInstance.lookAt = params.lookAtVec;<br>  rendererInstance.vUp = params.vUpVec;<br>  rendererInstance.defocusAngle = params.defocusAngle;<br>  rendererInstance.focusDist = params.focusDist;<br>  rendererInstance.useAccumulation = params.useAccumulation;<br><br>  if (!isRealtime) {<br>    const gpuTime = await rendererInstance.render(world, currentCanvas, (progress) =&gt; {<br>      const percent = Math.floor(progress * 100);<br>      progressBar.style.width = `${percent}%`;<br>      progressText.textContent = `${percent}%`;<br>    });<br><br>    let durationMs = &quot;0&quot;;<br>    if (gpuTime !== undefined) {<br>      durationMs = gpuTime.toFixed(2);<br>    }<br>    return { durationMs, newCameraController: cameraController, isRealtimeActive: false };<br>  } else {<br>    await rendererInstance.initializePipeline(world, currentCanvas);<br>    rendererInstance.resetAccumulation();<br>    progressBar.style.width = `100%`;<br>    progressText.textContent = `Realtime Active`;<br><br>    let ctrl = cameraController;<br>    if (!ctrl) {<br>      ctrl = new RealtimeCameraController(<br>        canvasContainer,<br>        rendererInstance,<br>      );<br>      ctrl.onCameraUpdate = onCameraUpdate;<br>      ctrl.onFrameRendered = (gpuTime) =&gt; {<br>        if (gpuTime !== undefined) {<br>          timeText.textContent = `${gpuTime.toFixed(2)} ms`;<br>        }<br>      };<br>    }<br><br>    ctrl.start(params.lookFromVec, params.lookAtVec);<br><br>    return { newCameraController: ctrl, isRealtimeActive: true };<br>  }<br>}</pre><p>I’m not going over the details on real-time camera controls in this article. Just note that the RealtimeCameraController class is responsible for handling the real-time camera controls, using WASD keys to move the camera and mouse to control the direction. ctrl.start() function will start the real-time rendering which invokes the rendererInstance.renderFrame() function.</p><h3><strong>Closing Remarks</strong></h3><p>By following the steps and code snippets in this article, you will be able to translate your existing CPU-based ray tracer implementation to WebGPU and achieve significant performance improvements. I hope this article was able to present my thought process that was used to translate the CPU ray tracer to a GPU ray tracer. That being said, there are probably better ways to implement some of these features. Hence, it would be amazing if you can point out any mistakes or improvements that can be made to the code. I would love to learn from you and improve my understanding of WebGPU.</p><p>I plan to extend this project further to implement more advanced ray tracing features mentioned in the original resource. Until then, have a nice day!</p><h3><strong>References</strong></h3><ul><li>Ray Tracing in One Weekend Series by Peter Shirley: <a href="https://raytracing.github.io/books/RayTracingInOneWeekend.html">https://raytracing.github.io/books/RayTracingInOneWeekend.html</a></li><li>MDN WebGPU API: <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API">https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API</a></li><li>WebGPU Fundamentals: <a href="https://webgpufundamentals.org/">https://webgpufundamentals.org/</a></li><li>Learn WebGPU C++ by Élie Michel and contributors: <a href="https://eliemichel.github.io/LearnWebGPU/">https://eliemichel.github.io/LearnWebGPU/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b6de7881ae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebXR Device API Depth Sensing — Implementing Depth Occlusion]]></title>
            <link>https://medium.com/@ramithrodrigo/webxr-device-api-depth-sensing-implementing-depth-occlusion-4eba480cd689?source=rss-5003525022b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eba480cd689</guid>
            <category><![CDATA[webxr]]></category>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[depth-sensing]]></category>
            <dc:creator><![CDATA[Ramith D. Rodrigo]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 11:19:48 GMT</pubDate>
            <atom:updated>2026-01-03T11:19:48.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebXR Device API Depth Sensing — Implementing Depth Occlusion</h3><p>In my series on creating a simple WebAR app using the WebXR Device API, I mentioned that occlusion is essential for making the experience more entertaining and immersive. However, before implementing depth occlusion, it is important to understand how depth sensing works in the context of the WebXR Device API. That is why, in my <a href="https://medium.com/@ramithrodrigo/webxr-device-api-depth-sensing-an-introduction-72accf544e3d">previous article</a>, I introduced the <strong>depth-sensing</strong> feature and demonstrated how to implement a simple depth map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-XpznaRq02LYlmzyHi1PMw.jpeg" /><figcaption>Virtual object being occluded by real world object using Depth Occlusion — Source: <a href="https://www.augmentedstartups.com/blog/how-google-s-arcore-depth-api-tackles-occlusion-with-a-single-camera?srsltid=AfmBOoodtV6qF0oDGH289y9PR74F1ZTYI4QY8DlYJ2vnUAmwsYRMwEvU">Google ARCore</a></figcaption></figure><p>Now that that’s covered, we can move on to the next feature of our WebAR app — one that’s been long overdue, so thanks for your patience. Since we’ve already gone through the concept, let’s jump straight into the implementation.</p><h3>Implementation</h3><h4>Prerequisite</h4><p>It’s advantageous to have experience working with WebGL shaders, as we will be writing custom shaders in the implementation, like in my previous article.</p><h4>Coding</h4><p>As with my other articles, I’ll be modifying the same project but creating a separate version for this one, so we can keep different versions for each article. Let’s start from where we left off in my <a href="https://medium.com/@ramithrodrigo/webxr-device-api-hit-test-adding-virtual-objects-to-the-ar-session-manually-91c1201cc555"><strong>hit-test</strong> article</a>.</p><p>First we introduce 2 new global variables.</p><pre>// Global Variables<br>let gl: WebGL2RenderingContext;<br>let renderer: GLRenderer;<br>let model: GLModel;<br>let depthTexture: WebGLTexture;<br>let customShader: Shader;</pre><p>depthTexture will store the depth texture created for each frame, while customShader will hold the custom shader used to implement the required occlusion logic. I already explained these variables in my introductory depth-sensing article, so I won’t go into detail here. That said, the actual shader implementation will be different, and I’ll explain that shader code later on.</p><p>Next, we need to request the depth-sensingfeature from the WebXR Device API. Make sure to include the required depthSensing properties as well. A detailed explanation of these properties is available in my other article, so I won’t repeat it here.</p><pre>const options: XRSessionInit = {<br>  requiredFeatures: [&quot;unbounded&quot;, &quot;hit-test&quot;, &quot;depth-sensing&quot;], // request depth sensing<br>  depthSensing: {<br>    usagePreference: [&quot;cpu-optimized&quot;],<br>    dataFormatPreference: [&quot;luminance-alpha&quot;],<br>  },<br>};</pre><p>Next, we need to modify our initialization by updating the setupRenderer function. Here, we create the depth texture and assign its required parameters after setting up the renderer and the gl context. Finally, we create our custom shader.</p><pre>async function setupRenderer() {<br>  // To get the GL context<br>  const canvas = document.createElement(&quot;canvas&quot;);<br><br>  renderer = await GLRenderer.RendererInstance(canvas, {<br>    powerPreference: &quot;high-performance&quot;,<br>    antialias: false,<br>    alpha: true,<br>    depth: true,<br>    stencil: false,<br>    xrCompatible: true,<br>  });<br><br>  // Add a virtual light<br>  const light: GLDirectionalLight = renderer.createDirectionalLight(<br>    1,<br>    vec3.fromValues(1, 1, 1),<br>    1,<br>    vec3.fromValues(2, -1, -2)<br>  );<br>  renderer.addLightToScene(light);<br><br>  // We need the GL context to pass that to XR<br>  gl = renderer.getGL();<br><br>  //-------- Initialize Depth Texture -----------<br><br>  depthTexture = gl.createTexture();<br>  gl.bindTexture(gl.TEXTURE_2D, depthTexture);<br>  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);<br>  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);<br>  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);<br>  gl.bindTexture(gl.TEXTURE_2D, null);<br><br>  // Create a custom shader<br>  customShader = Shader.getInstance(gl);<br>  customShader.createFromString(vertexShader, fragmentShader);<br>}</pre><p>You can see that I’ve passed the vertexShader and fragmentShader variables. These should be defined at the import level, so go to the top of the file and add the following lines.</p><pre>import vertexShader from &quot;./simpleShader.vert.glsl&quot;;<br>import fragmentShader from &quot;./simpleShader.frag.glsl&quot;;</pre><p>As you can see, these are separate files, so make sure to create both of them in the src directory.</p><blockquote><strong>Spoiler:</strong> These two files already exist in my WebGL framework. However, I won’t be using my renderer functions here, since they abstract away the logic — and where’s the fun in that? So instead, we’ll be reimplementing everything manually :)</blockquote><p>Now that you have the two empty files, open the simpleShader.vert.glsl file and add the following lines.</p><pre>#version 300 es<br><br>precision highp float;<br>layout (location = 0) in vec3 position;<br>layout (location = 1) in vec3 normal;<br>layout (location = 2) in vec2 tex;</pre><p>The #version 300 es line defines the shader language version we’re going to use. The precision highp float statement ensures that our floating-point values use higher precision for better accuracy.</p><p>After that, we define three inputs used to pass data related to our virtual object: <strong>position</strong>, <strong>normal</strong>, and <strong>texture coordinates</strong>.</p><p>Then we define the output of the vertex shader.</p><pre>#version 300 es<br><br>precision highp float;<br>layout (location = 0) in vec3 position;<br>layout (location = 1) in vec3 normal;<br>layout (location = 2) in vec2 tex;<br><br>out vec2 texCoord;<br>out vec3 normalFrag;<br>out vec4 viewPosition;</pre><p>Since texture coordinates are accessed in the fragment shader, we need to pass them through using texCoord. The normalFrag output is used for lighting calculations. This is not directly related to occlusion, but it is part of my framework’s implementation, so I’ve kept it as is. Finally, viewPosition is used to output the transformed position of the virtual object in camera space. I’ll explain this in more detail later.</p><p>Next, we define the uniforms.</p><pre>#version 300 es<br><br>precision highp float;<br>layout (location = 0) in vec3 position;<br>layout (location = 1) in vec3 normal;<br>layout (location = 2) in vec2 tex;<br><br>out vec2 texCoord;<br>out vec3 normalFrag;<br>out vec4 viewPosition;<br><br>uniform mat4 projection;<br>uniform mat4 model;<br>uniform mat4 view;<br>uniform mat4 modelInverse;</pre><p>Naturally, we need these uniforms: projection to project from camera space to screen space, model to transform the virtual object from object space to world space, and view to convert from world space to camera space.</p><p>Finally, we define the main function of the vertex shader.</p><pre>#version 300 es<br><br>precision highp float;<br>layout (location = 0) in vec3 position;<br>layout (location = 1) in vec3 normal;<br>layout (location = 2) in vec2 tex;<br><br>out vec2 texCoord;<br>out vec3 normalFrag;<br>out vec4 viewPosition;<br><br>uniform mat4 projection;<br>uniform mat4 model;<br>uniform mat4 view;<br>uniform mat4 modelInverse;<br><br>void main() {<br>    viewPosition = view * model * vec4(position, 1.0f);<br><br>    gl_Position = projection * viewPosition;<br><br>    texCoord = tex;<br><br>    normalFrag = mat3(transpose(modelInverse)) * normal;  <br>    <br>    //mat3 because we don&#39;t want to translate the normal<br>    //inverse because we want to transform the normal from world space to object space<br>    //transpose because we want to transform the normal from row-major to column-major<br>}</pre><p>When we multiply position by model, we obtain the world-space coordinates. Let’s call this result <strong>w</strong>. Multiplying <strong>w</strong> by view then gives us the camera-space coordinates. In other words, these represent the coordinates of the virtual object when the camera is at the origin (0, 0, 0).</p><p>This step is crucial because the <strong>z-value</strong> of these camera-space coordinates represents the depth of the object from the camera.</p><p>The rest of the code is fairly standard and not directly relevant to this article, so I won’t go into detail here. However, it is still necessary for rendering the scene.</p><p>Now, let’s move on to the fragment shader. Open the empty simpleShader.frag.glsl file and add the following lines.</p><pre>#version 300 es<br><br>precision highp float;<br><br>in vec2 texCoord;<br>in vec3 normalFrag;<br>in vec4 viewPosition;</pre><p>Similar to the vertex shader, we define the shader version and precision. In contrast to the vertex shader, texCoord, normalFrag, and viewPosition are declared as in variables, since they are passed from the vertex shader and used as inputs in the fragment shader.</p><p>Next, we define the uniforms.</p><pre>#version 300 es<br><br>precision highp float;<br><br>in vec2 texCoord;<br>in vec3 normalFrag;<br>in vec4 viewPosition;<br><br>uniform sampler2D depthTexture;<br>uniform mat4 depthUVTransform; // UV transform matrix in normalized view space<br>uniform float depthScale; // Depth scale factor (unspecified unit to meters)<br>uniform vec2 resolution; // Resolution of the depth texture</pre><p>It would be redundant to explain these again, as they were already covered in my other article and serve the same purpose here. The only difference lies in how the final depth value is used.</p><p>After that, we define the remaining values required for fragment rendering. Keep in mind that these lines are essential for producing the final rendered output, but they are not part of the depth-occlusion implementation itself.</p><pre>#version 300 es<br><br>precision highp float;<br><br>in vec2 texCoord;<br>in vec3 normalFrag;<br>in vec4 viewPosition;<br><br>uniform sampler2D depthTexture;<br>uniform mat4 depthUVTransform; // UV transform matrix in normalized view space<br>uniform float depthScale; // Depth scale factor (unspecified unit to meters)<br>uniform vec2 resolution; // Resolution of the depth texture<br><br>out vec4 color;<br><br>struct DirectionalLight {<br>    vec3 color;<br>    float ambientIntensity;<br>    vec3 direction;<br>    float diffuseIntensity;<br>};<br><br>uniform sampler2D theTexture;<br>uniform DirectionalLight directionalLight;</pre><p>And, of course, we need to define the custom functions.</p><pre>#version 300 es<br><br>precision highp float;<br><br>in vec2 texCoord;<br>in vec3 normalFrag;<br>in vec4 viewPosition;<br><br>uniform sampler2D depthTexture;<br>uniform mat4 depthUVTransform; // UV transform matrix in normalized view space<br>uniform float depthScale; // Depth scale factor (unspecified unit to meters)<br>uniform vec2 resolution; // Resolution of the depth texture<br><br>out vec4 color;<br><br>struct DirectionalLight {<br>    vec3 color;<br>    float ambientIntensity;<br>    vec3 direction;<br>    float diffuseIntensity;<br>};<br><br>uniform sampler2D theTexture;<br>uniform DirectionalLight directionalLight;<br><br>float DepthGetMeters(in sampler2D depth_texture, in vec2 depth_uv) {<br>    vec2 packedDepthAndVisibility = texture(depth_texture, depth_uv).ra;<br>    return dot(packedDepthAndVisibility, vec2(255.0, 256.0 * 255.0)) * depthScale;<br>}<br><br>vec2 NormalizeFragCoords(in vec2 fragCoords) {<br>    //fragCoords&#39;s left lower corner is (0.5, 0.5)<br>    //normalized one should have (0,0) on top left corner and (1,1) on bottom right corner<br>    //resolution&#39;s x and y are the width and height of the screen respectively<br>    <br>    return vec2(fragCoords.x / resolution.x, 1.0 - fragCoords.y / resolution.y);<br>}</pre><p>Lastly, we define the main function.</p><pre>#version 300 es<br><br>precision highp float;<br><br>in vec2 texCoord;<br>in vec3 normalFrag;<br>in vec4 viewPosition;<br><br>uniform sampler2D depthTexture;<br>uniform mat4 depthUVTransform; // UV transform matrix in normalized view space<br>uniform float depthScale; // Depth scale factor (unspecified unit to meters)<br>uniform vec2 resolution; // Resolution of the depth texture<br><br>out vec4 color;<br><br>struct DirectionalLight {<br>    vec3 color;<br>    float ambientIntensity;<br>    vec3 direction;<br>    float diffuseIntensity;<br>};<br><br>uniform sampler2D theTexture;<br>uniform DirectionalLight directionalLight;<br><br>float DepthGetMeters(in sampler2D depth_texture, in vec2 depth_uv) {<br>    vec2 packedDepthAndVisibility = texture(depth_texture, depth_uv).ra;<br>    return dot(packedDepthAndVisibility, vec2(255.0, 256.0 * 255.0)) * depthScale;<br>}<br><br>vec2 NormalizeFragCoords(in vec2 fragCoords) {<br>    //fragCoords&#39;s left lower corner is (0.5, 0.5)<br>    //normalized one should have (0,0) on top left corner and (1,1) on bottom right corner<br>    //resolution&#39;s x and y are the width and height of the screen respectively<br>    <br>    return vec2(fragCoords.x / resolution.x, 1.0 - fragCoords.y / resolution.y);<br>}<br><br>void main() {<br>    vec2 depthTexCoord = (depthUVTransform * vec4(NormalizeFragCoords(gl_FragCoord.xy), 0, 1)).xy;<br>    float depth = DepthGetMeters(depthTexture, depthTexCoord);<br><br>    // OCCLUSION LOGIC AND REST OF THE RENDERING LOGIC<br>}</pre><p>If we take a look at the first two lines of the main function, you’ll notice that they are exactly the same as the code from my other article, so I won’t explain them again here. Just keep in mind that once those lines are executed, we obtain the actual depth of the fragment currently being processed. This value is stored in the depth variable.</p><p>While this depth value is not perfectly accurate, it is sufficient for implementing occlusion.</p><p>You might be wondering about the rest of the code, but you may be surprised by how straightforward it is once the concept is clear. Here’s the logic:</p><pre>// OCCLUSION LOGIC<br><br>if(depth &lt; (viewPosition.z) * -1.0f) { //virtual object is behind the real object<br>    discard; //discard the virtual object<br>}</pre><p>See? Simple, right? Now let me explain.</p><p>depth is a floating-point value, and it is always positive because it represents a distance measured in meters. If we look at the viewPosition value passed from the vertex shader, its <strong>z-component</strong> corresponds to the depth of the virtual object.</p><p>In WebGL’s coordinate system, negative <strong>z-values</strong> point into the screen, while positive values point out of the screen. This means that if an object is in front of us and the camera is at the origin (0, 0, 0), the object’s z-value will be negative. To work with a positive depth value, we therefore multiply it by -1.</p><p>At this point, we have two positive values: the estimated real-world depth and the virtual object’s depth. If the estimated depth is <strong>smaller</strong> than the virtual object’s positive z-value, we know that the real-world surface is closer to the camera.</p><p>Using this logic, we can discard the fragment currently being rendered. When a fragment is discarded, that pixel becomes transparent. Since alpha blending is enabled in our rendering context, no virtual content will be rendered on top of the camera feed at that location — effectively simulating depth occlusion.</p><p>That’s it! After applying this logic, simply add the following lighting calculations to complete the rest of the rendering.</p><pre>// OCCLUSION LOGIC<br><br>if(depth &lt; (viewPosition.z) * -1.0f) { //virtual object is behind the real object<br>    discard; //discard the virtual object<br>}<br><br>// RENDERING LOGIC<br>vec4 ambientColor = vec4(directionalLight.color, 1.0) * directionalLight.ambientIntensity;<br><br>float diffuseFactor = max(dot(normalize(normalFrag), -normalize(directionalLight.direction)), 0.0f);<br>vec4 diffuseColor = vec4(directionalLight.color, 1.0) * directionalLight.diffuseIntensity * diffuseFactor;<br><br>vec4 textureVal = texture(theTexture, texCoord);<br>color = textureVal * (ambientColor + diffuseColor);</pre><p>Now that the shader part is complete, the next step is to prepare the depth data on the CPU so it can be sent to the GPU.</p><p>Go back to index.ts and locate the onDrawFrame function. Inside the views loop, we’ll make the necessary changes.</p><p>First, remove the following lines:</p><pre>const shader = renderer.getShader() as Shader;<br>shader.useShader(); // Use the shader program</pre><p>And replace them with following:</p><pre>customShader.useShader(); // Use the custom shader program</pre><p>This is because we’ve defined our own shader, so we won’t be using the framework’s built-in one.</p><p>Now, let’s add the depth-processing logic. Make sure to insert it exactly where I placed the comment.</p><pre>const viewport = glLayer.getViewport(view) as XRViewport;<br>renderer.setViewPort(<br>  viewport.x,<br>  viewport.y,<br>  viewport.width,<br>  viewport.height<br>); // Set the frambuffer viewport. This matches the camera display<br><br><br>// DEPTH INFO LOGIC<br><br><br>const uniforms = renderer.getUniforms();<br>renderer.useLights(scene, uniforms);<br><br>const projectionMatrix = view.projectionMatrix;<br>const viewMatrix = view.transform.inverse.matrix; // Inverse because view camera / the user should be at the origin</pre><p>Here’s what you need to add in there:</p><pre>const depthInfo = frame.getDepthInformation(view);<br>if (depthInfo) {<br>  gl.activeTexture(gl.TEXTURE1); //texture 1 because scene object textures are added to 0<br>  gl.bindTexture(gl.TEXTURE_2D, depthTexture);<br>  gl.texImage2D(<br>    gl.TEXTURE_2D,<br>    0,<br>    gl.LUMINANCE_ALPHA,<br>    depthInfo.width,<br>    depthInfo.height,<br>    0,<br>    gl.LUMINANCE_ALPHA,<br>    gl.UNSIGNED_BYTE,<br>    new Uint8Array(depthInfo.data, 0, depthInfo.data.byteLength)<br>  );<br><br>  gl.uniform1i(customShader.getUniformDepthTexture(), 1); //texture 1 because scene object textures are added to 0<br>  // Set up UV transform<br>  const uvTransformLocation = customShader.getUniformDepthUVTransform();<br>  const matrix = depthInfo.normDepthBufferFromNormView.matrix;<br>  // Bind the uv transform matrix<br>  gl.uniformMatrix4fv(uvTransformLocation, false, matrix);<br>  // Set the depth scale<br>  const depthScaleLocation = customShader.getUniformDepthScale();<br>  gl.uniform1f(depthScaleLocation, depthInfo.rawValueToMeters);<br>  // Set the resolution<br>  gl.uniform2f(<br>    customShader.getUniformResolution(),<br>    viewport.width,<br>    viewport.height<br>  );<br>}</pre><p>This code is essentially the same as in my other article, with only a few minor changes, so I won’t go into detailed explanations here. Instead, let’s focus on those small differences.</p><p>Take a look at the following line:</p><pre>gl.activeTexture(gl.TEXTURE1); //texture 1 because scene object textures are added to 0</pre><p>In my other article, I used TEXTURE0. However, in this case, we can’t use it because the virtual object’s textures are already bound to that texture unit. Therefore, we use TEXTURE1 instead. The same applies to the following line:</p><pre>gl.uniform1i(customShader.getUniformDepthTexture(), 1); //texture 1 because scene object textures are added to 0</pre><h3>Quick Demo</h3><p>That is all. All you have to do is now to run the web app and you will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*rZpfor18ILtSJsiwFMky2A.gif" /><figcaption>Occlusion Demo</figcaption></figure><p>You can see that the virtual objects are properly occluded by real-world objects. However, it’s also clear that the results are not very accurate and that the response time is somewhat limited. Still, this is the best we can achieve with the current capabilities.</p><p>It’s not as if we have access to LiDAR sensors to measure depth with much higher accuracy. Although iPhones do have LiDAR, WebXR does not currently support it.</p><h3>Wrap Up</h3><p>By following this article, I hope you were able to implement a simple depth-based occlusion technique in your WebAR application using estimated depth data. In this article, we used the following techniques:</p><ul><li>Using <strong>WebXR depth sensing</strong> to obtain estimated real-world depth data</li><li>Creating and updating a <strong>depth texture each frame</strong></li><li>Passing depth information to <strong>custom vertex and fragment shaders</strong></li><li>Comparing <strong>real-world depth with virtual object depth</strong> in camera space</li><li><strong>Discarding fragments</strong> in the fragment shader to achieve depth-based occlusion</li></ul><p>There are many other features provided by the WebXR Device API. Hopefully, I’ll be able to explore them and share more articles in the future. Until then, see you — and do your best!</p><h3>Resources</h3><p>Source Code: <a href="https://github.com/Ramith-D-Rodrigo/Medium/tree/master/webar-depth-occlusion">https://github.com/Ramith-D-Rodrigo/Medium/tree/master/webar-depth-occlusion</a></p><p>My WebXR Device API depth-sensing introductory article: <a href="https://medium.com/@ramithrodrigo/webxr-device-api-depth-sensing-an-introduction-72accf544e3d">https://medium.com/@ramithrodrigo/webxr-device-api-depth-sensing-an-introduction-72accf544e3d</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eba480cd689" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebXR Device API Depth Sensing — An Introduction]]></title>
            <link>https://medium.com/@ramithrodrigo/webxr-device-api-depth-sensing-an-introduction-72accf544e3d?source=rss-5003525022b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/72accf544e3d</guid>
            <category><![CDATA[webxr]]></category>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[glsl]]></category>
            <category><![CDATA[depth-sensing]]></category>
            <category><![CDATA[ar]]></category>
            <dc:creator><![CDATA[Ramith D. Rodrigo]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 08:50:04 GMT</pubDate>
            <atom:updated>2026-01-03T05:50:00.650Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebXR Device API Depth Sensing — An Introduction</h3><p>In this article, I’d like to dive into the semantics of depth sensing in the WebXR Device API. I mentioned this feature in my previous article; however, this isn’t a continuation of that one. I thought it might be better to first briefly talk about this feature, and then move on to our use case. So, I’m reserving this article to give an introduction to the feature and implement a simple WebAR app that utilizes it.</p><p>That said, I still think it’s better to read the previous articles, as I’ll be implementing this app in a similar way to the ones covered there. Because of that, I won’t be going through the most basic steps.</p><h3>What is “Depth Sensing”?</h3><p>In an interactive 3D application, you can move along all three axes — assuming the application allows it. Typically, the x and y axes represent the horizontal and vertical directions, while the z axis represents depth — going into or coming out of the screen. (See Figure 1.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*SSV1G_Sl8OPhib82DIL6Wg.png" /><figcaption>Figure 1: 3D Coordinate System (Ref: <a href="https://buzzcoder.gitbooks.io/codecraft-javascript/content/codecraft-game/3d-coordinates.html">https://buzzcoder.gitbooks.io/</a>)</figcaption></figure><p>In a 3D scene, every object has a coordinate with x, y, and z values — where the z value represents depth.</p><blockquote>How so?</blockquote><p>In the context of an AR application, it’s clear that the XY plane can be considered the application’s view or camera overlay. We know that every 3D object in this WebAR app is projected onto this XY plane by the rendering pipeline.</p><p>However, I’d argue that the XY plane here is different from the XY plane in the scene coordinate space. Remember that once the rendering pipeline has done its job, the camera is positioned at the origin. But I think you get the idea.</p><p>Essentially,</p><ol><li>3D objects have their own depth in the 3D virtual world.</li><li>After projection, they all appear in screen space.</li><li>Still, the projection creates the<strong><em> illusion that depth exists.</em></strong></li></ol><p>However, there’s an issue when it comes to AR applications, especially with how the WebXR Device API works. It’s clear that we render these virtual 3D objects on top of the camera overlay. No matter what, our virtual 3D objects will always display on top of the real objects shown by the camera overlay.</p><p>The API is smart enough to create a coordinate system for the real world, which is displayed through the camera overlay. What I mean is, when you start the AR session, the API establishes a coordinate system for the environment you’re in. This ensures consistency between the 3D virtual object coordinates and the real world (<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Geometry#on_the_origins_of_spaces">Ref</a>). However, it won’t detect real-world objects and define coordinates for them.</p><p>This is problematic, isn’t it?</p><p>Yes. Now, let’s think about how we can solve this. Let’s consider an example scenario. Suppose we have a virtual 3D object in the scene, and there are several real-world objects or obstacles displayed in the camera overlay. For simplicity, let’s focus on one such object. We have two cases. Let me depict them as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCZAIDsrc8L46hBLUUzEvg.png" /><figcaption>Figure 2: Object placements</figcaption></figure><p>In the first case, there’s no issue, because that’s the expected behavior. But consider the second case: even though the real object is closer to the mobile device than the virtual object, the virtual object will still be displayed on top of the real object. The yellow line represents the projection.</p><p>Perhaps, if we can <strong><em>calculate the distance</em></strong> from the mobile device to both the virtual object and the real object separately, we could compare those distances and decide whether to render the virtual object or not.</p><p>Now take a look at the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atu_KBJb7mKUrESOafHZtA.png" /><figcaption>Figure 3: Coordinate values</figcaption></figure><p>We know the coordinate values for both the mobile device and the virtual object, so we can easily calculate the distance between them — in other words, the depth from the mobile device to the virtual object. This is simply a matter of linear algebra calculations.</p><p>But we can’t do the same for the real object, as we don’t know its coordinates, right?</p><p>Yes, but the ingenuity of computer vision algorithms allows us to calculate the real-world depth, or the distance from the camera/mobile to the real world. This is what we refer to as “<strong>Depth Sensing.</strong>” By using it, we can obtain a distance value that we can compare with the distances in our 3D scene to decide whether or not to render the object.</p><p>The WebXR Device API has a feature called “depth-sensing,” which you can easily request when creating an AR session. Once the session is created, you can access the depth information at each frame.</p><p>Okay, I hope the idea is clear. What we want here is to access the depth information processed by the API and use it for relevant purposes. One use case is to decide which objects should be rendered or not.</p><p>In this article, I will demonstrate how to access this depth information and process it to create a simple depth map (See Figure 4) of the session environment at each frame. So, let’s move on to the implementation!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*0sqlwMEskvqTK7U8ED0VGw.png" /><figcaption>Figure 4: Depth map (Adaptive Depth-Map Coding for 3D-Video — Scientific Figure on ResearchGate. Available from: <a href="https://www.researchgate.net/figure/Real-image-and-its-depth-map-in-Ballet-sequence_fig1_220235505">https://www.researchgate.net/figure/Real-image-and-its-depth-map-in-Ballet-sequence_fig1_220235505</a> [accessed 9 Apr 2025])</figcaption></figure><h3>Implementation</h3><h4><strong>PREREQUISITE</strong></h4><p>It’s advantageous to have experience working with WebGL shaders, as we will be writing custom shaders in the implementation.</p><h4>CODING</h4><p>I recommend reading <a href="https://medium.com/@ramithrodrigo/on-to-the-realm-of-web-based-augmented-reality-using-webxr-device-api-creating-a-basic-webar-70727865f8fb">this article</a> to get started with initializing the project and setting up the necessary dependencies. Assuming that the project has already been initialized, let’s begin coding the app.</p><p>First, let’s define the global variables we’ll be using.</p><pre>// Global Variables<br>let gl : WebGL2RenderingContext;<br>let renderer : GLRenderer;<br>let depthTexture: WebGLTexture;<br>let customShader: Shader;</pre><p>GLRenderer is a type from my minimalistic WebGL framework. depthTexture is a WebGL texture that will hold the depth information provided by the WebXR Device API. I will explain its usage later. Next, we have Shader, which is also a custom type provided by the framework. We need it because we’ll be writing our own shader.</p><pre>const options : XRSessionInit = {<br>    requiredFeatures: [&#39;unbounded&#39;, &#39;depth-sensing&#39;], // request depth-sensing feature<br>    depthSensing: {<br>        usagePreference: [&#39;cpu-optimized&#39;],<br>        dataFormatPreference: [&#39;luminance-alpha&#39;]<br>        <br>    }<br>}</pre><p>Next, we define the options we need for our AR app. As you can see, I’ve added the depth-sensing feature to the requiredFeatures array. Now, we need to specify how the depth data should be provided by the API. In this particular app, I’ve requested the configuration shown above. Let me explain this.</p><p>When we retrieve the depth data, it should represent the depth from the device to the environment in each pixel of the frame. This is important because, ultimately, we see the real-world environment through our app’s rendered frames, so the depth data needs to map correctly. Here, the first property, usagePreference, refers to where we’ll use this depth data. There are two options.</p><ol><li>cpu-optimized: The API will send the data in a format that is easier to process on the CPU side (Array Buffer).</li><li>gpu-optimized: The API will send the data in a format that is easier to process on the GPU side (WebGL texture).</li></ol><p>If you want to use the depth data to measure a distance and process that value with other data, cpu-optimized is a good choice, as the operations will be performed on the CPU. However, if you want to directly manipulate the rendering frame with this data, then gpu-optimized is the better approach.</p><blockquote>Then Why did you choose cpu-optimized if we are going to render a depth map?</blockquote><p>Basically, the array buffer provided by the cpu-optimized option can be used to directly create a WebGL texture. So, I decided to go with that option. This sample code follows a similar approach, and I will be using its concept to implement the depth map.</p><p>Next, we have the dataFormatPreference option. Here, we specify how we want our data to be packed within the texture. Textures can hold multiple values per pixel. For example, in an RGBA texture, each pixel (or texel) contains 4 values: Red, Green, Blue, and Alpha channels. This is an efficient way to pass lots of data from the CPU to the GPU as a uniform.</p><p>Returning to dataFormatPreference, I’ve selected the luminance-alpha mode. This means the data is packed into the Luminance (Same value in all Red, Blue and Green) and Alpha channels. There are other modes as well, which you can refer to <a href="https://www.w3.org/TR/webxr-depth-sensing-1/#usage-and-formats">here</a>.</p><p>Also, notice that these preferences and modes are provided inside an array for each property. This indicates that we can request multiple values, but the order of the array gives higher priority to the options listed at the beginning. I haven’t actually tested this behavior, so I’m not entirely confident about this part.</p><p>Moving on, let’s add another global variable.</p><pre>let unboundedRefSpace: XRReferenceSpace;</pre><p>This will hold the reference to the global reference space that we request from the API.</p><p>Now we define the main function which initializes the app.</p><pre>async function main() {<br>    await setupRenderer();<br><br>    // Add an event listener to the AR button<br>    const arButton = document.querySelector(&#39;#btn&#39;);<br>    arButton?.addEventListener(&#39;click&#39;, startARSession);<br>}<br><br>main();</pre><p>You can also call it right below. Now, let’s create our setupRenderer function.</p><pre>// Setup our Renderer object<br>async function setupRenderer() {<br>    // To get the GL context<br>    const canvas = document.createElement(&#39;canvas&#39;);<br><br>    renderer = await GLRenderer.RendererInstance(canvas, {<br>        powerPreference: &quot;high-performance&quot;,<br>        antialias: false,<br>        alpha: true,<br>        depth: true,<br>        stencil: false,<br>        xrCompatible: true<br>    });<br><br>    // We need the GL context to pass that to XR<br>    gl = renderer.getGL();<br><br>    // Initialize depth texture<br>    depthTexture = gl.createTexture();<br>    gl.bindTexture(gl.TEXTURE_2D, depthTexture);<br>    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);<br>    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);<br>    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);<br>    gl.bindTexture(gl.TEXTURE_2D, null);<br><br>    // Create a custom shader<br>    customShader = Shader.getInstance(gl);<br>    customShader.createFromString(vertexShader, fragmentShader);<br>}</pre><p>Simply put, we create a canvas element to generate a WebGL context. Then, we pass the canvas element to my framework’s function to create a Renderer instance, which is assigned to the global variable. We also store the context in our previously defined global variable. After that, we create a WebGL texture to pass the depth data to the rendering pipeline in each frame.</p><p>Finally, we create our custom shaders. You can see that I’ve passed vertexShader and fragmentShader as arguments. So, where did these come from?</p><p>Well, I’ve written the custom shaders and imported them at the top of the file as follows:</p><pre>import vertexShader from &quot;./custom.vert.glsl&quot;;<br>import fragmentShader from &quot;./custom.frag.glsl&quot;;</pre><p>Now, let’s move on to writing our custom shaders! First, we’ll start with the vertex shader. (Also, make sure that customShader is a global variable.)</p><p>This shader is pretty simple. Given the use case of this app — rendering the depth map of the environment — every pixel is involved. The fragment shader is invoked for all the vector points that fall within the clip bounds once they are transformed by the vertex shader.</p><p>To achieve this, we need to ensure that, once these vertices are transformed, the enclosing areas of these vectors cover the entire screen.</p><p>To implement this, our custom.vert.glsl will look as follows:</p><pre>#version 300 es<br><br>precision highp float;<br><br>const vec2 positions[6] = vec2[](<br>    vec2(-1.0, -1.0), vec2( 1.0, -1.0), vec2(-1.0,  1.0),<br>    vec2(-1.0,  1.0), vec2( 1.0, -1.0), vec2( 1.0,  1.0)<br>);<br><br>void main() {<br>    gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0);<br>}</pre><p>For all the frames, the vertices don’t change, so we don’t need to pass them from the CPU to the GPU. Instead, we can define them directly inside the shader. The positions array contains 6 elements of vec2 type, each representing one corner of the device screen/frame.</p><blockquote>But why 6? Isn’t 4 enough?</blockquote><p>Yes, but the thing is, we’re defining the triangles. Let’s take the first 3 vertices:</p><ul><li>(-1, -1)</li><li>(1.0, -1.0)</li><li>(-1.0, 1.0)</li></ul><p>These 3 vectors define the coordinates in clip space. If we look at the following figure, you’ll see that in Figure 5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*RGuLXNdzyjb3RaBv3cGGwA.png" /><figcaption>Figure 5: WebGL Clip space (From <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_model_view_projection">MDN web docs</a>)</figcaption></figure><ul><li>(-1,-1) is at the bottom left</li><li>(1.0,-1.0) is at the bottom right</li><li>(-1.0, 1.0) is at the top left</li></ul><p>These 3 corners form a triangle on the left side, and likewise, the remaining 3 vertices form a triangle on the right side. We’ve redefined 2 corners twice because we are using gl_VertexID to identify a particular vertex inside the vertex shader. Since we aren’t using any index buffers, we must individually define all the corners for the triangles.</p><p>Also, I haven’t considered the z-values in these vectors because we’re rendering a texture and coloring it in the fragment shader to create the depth map for each frame.</p><p>If you want to learn more about clip space and other coordinate spaces, I recommend <a href="https://olegvaraksin.medium.com/convert-world-to-screen-coordinates-and-vice-versa-in-webgl-c1d3f2868086">this article</a>.</p><p>If you’re wondering about positions[gl_VertexID], it’s related to how we issue the draw call, which I’ll explain later. So, our gl_Position is directly set to some clip space coordinate.</p><p>Now, let’s move on to the fragment shader, custom.frag.glsl. This one is more descriptive, and I’ll try my best to explain it. I’ve also added comments in the shader code.</p><pre>#version 300 es<br><br>precision highp float;<br><br>uniform sampler2D depthTexture;<br>uniform mat4 depthUVTransform; // UV transform matrix in normalized view space<br>uniform float depthScale; // Depth scale factor (unspecified unit to meters)<br>uniform vec2 resolution; // Resolution of our screen<br><br>const highp float kMaxDepth = 3.5; // Max depth in meters<br><br>out vec4 color;<br><br>// Convert depth texture value to meters<br>float depthGetMeters(in sampler2D depth_texture, in vec2 depth_uv) {<br>    vec2 packedDepthAndVisibility = texture(depth_texture, depth_uv).ra;<br>    return dot(packedDepthAndVisibility, vec2(255.0, 256.0 * 255.0)) * depthScale;<br>}<br><br>// Convert fragment coordinates to normalized [0,1] UV space<br>vec2 normalizeFragCoords(in vec2 fragCoords) {<br>    //fragCoords&#39;s left lower corner is (0.5, 0.5)<br>    //normalized one should have (0,0) on top left corner and (1,1) on bottom right corner<br>    //resolution&#39;s x and y are the width and height of the screen respectively<br>    return vec2((fragCoords.x - 0.5) / resolution.x, 1.0 - (fragCoords.y - 0.5) / resolution.y);<br>}<br><br>// Maps a value from one range to another<br>float mapRange(float inputValue, float inputMin, float inputMax, float outputMin, float outputMax) {<br>    return outputMin + (inputValue - inputMin) * (outputMax - outputMin) / (inputMax - inputMin);<br>}<br><br>void main() {<br>    // Transform screen-space coordinates to depth texture UV<br>    vec2 depthTexCoord = (depthUVTransform * vec4(normalizeFragCoords(gl_FragCoord.xy), 0, 1)).xy;<br><br>    // Sample depth and convert to meters<br>    float depth = depthGetMeters(depthTexture, depthTexCoord);<br><br>    // Map depth to grayscale range [0,1]<br>    float mappedValue = mapRange(clamp(depth, 0.0, kMaxDepth), 0.0, kMaxDepth, 0.0, 1.0);<br><br>    // Visualize as grayscale<br>    color = vec4(vec3(mappedValue), 1.0);<br>}</pre><p>First, let’s take a look at the uniform variables.</p><pre>uniform sampler2D depthTexture;<br>uniform mat4 depthUVTransform; // UV transform matrix in normalized view space<br>uniform float depthScale; // Depth scale factor (unspecified unit to meters)<br>uniform vec2 resolution; // Resolution of the depth texture</pre><p>depthTexture is the texture that we create using the depth data provided by the API. depthUVTransform is a 4x4 matrix provided by the API to convert the normalized depth texture coordinates to absolute coordinates. We can then use these coordinates (U, V) to index our depthTexture. I’ll explain the exact usage of this later.</p><p>Next, we have depthScale, which is a float value that converts the depth values to meters (unit). Finally, we have resolution to normalize our current fragment’s coordinates. I’ll also explain the usage of this later.</p><p>Now, let’s look at a constant value defined as follows:</p><pre>const highp float kMaxDepth = 3.5; // Max depth in meters</pre><p>This is a custom value I’ve used to define the maximum depth in meters. Since we are creating a depth map in grayscale, we need to define the range appropriately, which is why a maximum value is necessary. This value is not provided by the API, so I experimented and found a “sweet spot.” You’re free to experiment and find a value that works best for your use case.</p><p>Next, we define the output color, as usual.</p><pre>out vec4 color;</pre><p>Next, we have a function called depthGetMeters.</p><pre>// Convert depth texture value to meters<br>float depthGetMeters(in sampler2D depth_texture, in vec2 depth_uv) {<br>    vec2 packedDepthAndVisibility = texture(depth_texture, depth_uv).ra;<br>    return dot(packedDepthAndVisibility, vec2(255.0, 256.0 * 255.0)) * depthScale;<br>}</pre><p>As the comment explains, we retrieve the depth texture passed as a uniform along with the depth texture coordinates. We can use GLSL’s texture function to fetch the texture&#39;s value. However, remember that we want the depth data in a luminance-alpha format. This means that the depth values are only available in the Red and Alpha channels. That doesn’t mean there aren’t values in the Green and Blue channels—those values are replicated in the Green and Blue channels, so we can access them as well. Therefore, we access the relevant components by indexing texture(depth_texture, depth_uv).ra.</p><p>Now, consider this line: dot(packedDepthAndVisibility, vec2(255.0, 256.0 * 255.0)). We know what the dot product does. We also know that packedDepthAndVisibility is a vec2. If this vector’s values are x and y, then the dot product is essentially x * 255.0 + y * 255.0 * 256.0. Here, x is the Red channel’s value, and y is the Alpha channel’s value. Since these values are in the [0–1] range, we multiply them by 255 to convert them into the RGB range of [0–255], the 8-bit range.</p><blockquote>Then what about 256.0?</blockquote><p>When we request the depth data to be packed into the Luminance and Alpha channels (luminance-alpha), we are essentially dividing the depth value into two bytes. One byte corresponds to the Luminance channel, and the other corresponds to the Alpha channel. The Luminance channel holds the lower byte, and the Alpha channel holds the higher byte, which is guaranteed. This means that the value of Alpha will always be in the higher byte, starting from 256.</p><p>By performing the dot product as shown earlier (dot(packedDepthAndVisibility, vec2(255.0, 256.0 * 255.0))), we are reconstructing the depth value from these two components. The result is the actual depth data for that particular fragment coordinate, but it is in some unspecified units. To convert it into a meaningful depth value in meters, we multiply the result by the depthScale uniform, which serves as the conversion factor.</p><pre>// Convert fragment coordinates to normalized [0,1] UV space<br>vec2 normalizeFragCoords(in vec2 fragCoords) {<br>    //fragCoords&#39;s left lower corner is (0.5, 0.5)<br>    //normalized one should have (0,0) on top left corner and (1,1) on bottom right corner<br>    //resolution&#39;s x and y are the width and height of the screen respectively<br>    return vec2((fragCoords.x - 0.5) / resolution.x, 1.0 - (fragCoords.y - 0.5) / resolution.y);<br>}</pre><p>This function is responsible for converting the fragment coordinates into a normalized form. In this <a href="https://www.w3.org/TR/webxr-depth-sensing-1/#terminology">particular context</a>, ‘normalized’ means that the coordinates are in the range of (0,0) to (1,1), where (0,0) is at the top left and (1,1) is at the bottom right. This is different from gl_FragCoord, as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYA6KZJqLKetwSy2vmD-tg.png" /><figcaption>Figure 6: Difference between gl_FragCoords and Normalized Coordinates</figcaption></figure><p>The 0.5 in gl_FragCoord represents the center of a particular pixel.<a href="https://computergraphics.stackexchange.com/questions/5724/glsl-can-someone-explain-why-gl-fragcoord-xy-screensize-is-performed-and-for"> Here&#39;s a useful link for reference</a>. To convert this range to normalized coordinates, the function above is used. Next, we define a custom function to map the depth values to a desired range. This is useful for calculating the final depth color of the map.</p><pre>// Maps a value from one range to another<br>float mapRange(float inputValue, float inputMin, float inputMax, float outputMin, float outputMax) {<br>    return outputMin + (inputValue - inputMin) * (outputMax - outputMin) / (inputMax - inputMin);<br>}</pre><p>Next we have the main function of the fragment shader.</p><pre>void main() {<br>    // Transform screen-space coordinates to depth texture UV<br>    vec2 depthTexCoord = (depthUVTransform * vec4(normalizeFragCoords(gl_FragCoord.xy), 0, 1)).xy;<br><br>    // Sample depth and convert to meters<br>    float depth = depthGetMeters(depthTexture, depthTexCoord);<br><br>    // Map depth to grayscale range [0,1]<br>    float mappedValue = mapRange(clamp(depth, 0.0, kMaxDepth), 0.0, kMaxDepth, 0.0, 1.0);<br><br>    // Visualize as grayscale<br>    color = vec4(vec3(mappedValue), 1.0);<br>}</pre><p>Let’s take a look at the lines one by one.</p><pre>vec2 depthTexCoord = (depthUVTransform * vec4(normalizeFragCoords(gl_FragCoord.xy), 0, 1)).xy;</pre><p>depthUVTransform is the uniform value we pass. We access the current fragment&#39;s x and y coordinates with gl_FragCoord.xy and normalize them using our custom normalizeFragCoords function. Then, we create a vec4 with z set to 0 and w set to 1. This is because we are multiplying it with a 4x4 matrix (depthUVTransform). After that, we index only the x and y components of the multiplied result to obtain the u and v coordinates of the depth texture.</p><pre>float depth = depthGetMeters(depthTexture, depthTexCoord);</pre><p>We pass this vector and our uniform depthTexture to depthGetMeters to obtain the depth value for this fragment in meters.</p><pre>float mappedValue = mapRange(clamp(depth, 0.0, kMaxDepth), 0.0, kMaxDepth, 0.0, 1.0);</pre><p>Then we map that value between 0 and kMaxDepth for depth map coloring.</p><pre>color = vec4(vec3(mappedValue), 1.0);</pre><p>Finally, we express that value as a grayscale color by spreading it across the R, G, and B channels while keeping the alpha channel as 1.0. That’s it! We have completed the heavy lifting. Next, we need to prepare the data to be passed from the CPU to the GPU. Let’s go back to index.ts.</p><p>To do this, we need to prepare the AR session. As always, we need a function to check for support</p><pre>async function isARSupported() : Promise&lt;boolean&gt; {<br>    if(!navigator.xr) {<br>        console.error(&quot;WebXR not supported&quot;);<br>        return false;<br>    }<br><br>    if(!await navigator.xr.isSessionSupported(&#39;immersive-ar&#39;)) {<br>        console.error(&quot;WebAR not supported&quot;);<br>        return false;<br>    }<br><br>    return true;<br>}</pre><p>Then we define the startARSession function that is added to the AR button in the main function.</p><pre>async function startARSession() {<br>    if(!await isARSupported()) {<br>        return;<br>    }<br><br>    const ARSession : XRSession = await navigator.xr?.requestSession(&#39;immersive-ar&#39;, options) as XRSession;<br>    ARSession.addEventListener(&#39;end&#39;, () =&gt; {<br>        shutDownARSession(ARSession);<br>    });<br><br>    // Create a WebGL layer to present the rendered frames to the session.<br>    await ARSession.updateRenderState({<br>        baseLayer: new XRWebGLLayer(ARSession, gl)<br>    });<br><br>    // Request the reference spaces<br>    viewerRefSpace = await ARSession.requestReferenceSpace(&#39;viewer&#39;);<br>    localRefSpace = await ARSession.requestReferenceSpace(&#39;local&#39;);<br>    unboundedRefSpace = await ARSession.requestReferenceSpace(&#39;unbounded&#39;);<br><br>    // Request the animation frame<br>    const animationID = ARSession.requestAnimationFrame(onDrawFrame);<br>}<br><br>async function shutDownARSession(session: XRSession) {<br>    await session.end();<br>}</pre><p>I am not going to explain the above code as I have done it in my previous articles.</p><p>Now we have to create onDrawFrame function.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br><br>    if(pose) {<br>        // Get the rendering layers and the views<br>        const glLayer = session.renderState.baseLayer as XRWebGLLayer;<br>        const views = pose.views;<br><br>        // Do the Rendering<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);<br>        <br>        gl.clearColor(0, 0, 0, 0); // RGBA values, fully transparent<br>        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);<br><br>        customShader.useShader();<br><br>        for(let i = 0; i &lt; views.length; i++) { // As this is AR, only one view<br>            const viewport = glLayer.getViewport(views[i]) as XRViewport;<br>            renderer.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height);  // Set the frambuffer viewport. This matches the camera display<br>            <br>            // DEPTH SENSING CODE &lt;--- OUR NEW CODE<br>            <br>        }<br><br>        gl.useProgram(null); // Un assign the shader program<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, null); // Unbind the framebuffer<br>    }<br>}</pre><p>This is the basic skeleton of the function that is called in every frame. I have used this in my previous articles, and I’m not going to explain the skeleton. However, I have left a comment where I will add the code related to depth sensing. So let’s see what needs to be added.</p><pre>for(let i = 0; i &lt; views.length; i++) { // As this is AR, only one view<br>    const viewport = glLayer.getViewport(views[i]) as XRViewport;<br>    renderer.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height);  // Set the frambuffer viewport. This matches the camera display<br>    <br>    // DEPTH SENSING CODE &lt;--- OUR NEW CODE<br>    const depthInfo = frame.getDepthInformation(views[i]);<br>    if(depthInfo){<br><br>    }<br>}</pre><p>We can get the depth information for the current frame by calling frame.getDepthInformation(views[i]); . Then we proceed only if the information is available.</p><pre>for(let i = 0; i &lt; views.length; i++) { // As this is AR, only one view<br>    const viewport = glLayer.getViewport(views[i]) as XRViewport;<br>    renderer.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height);  // Set the frambuffer viewport. This matches the camera display<br>    <br>    // DEPTH SENSING CODE &lt;--- OUR NEW CODE<br>    const depthInfo = frame.getDepthInformation(views[i]);<br>    if(depthInfo){<br>        gl.activeTexture(gl.TEXTURE0);<br>        gl.bindTexture(gl.TEXTURE_2D, depthTexture);<br>        gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE_ALPHA, <br>            depthInfo.width, depthInfo.height, <br>            0, gl.LUMINANCE_ALPHA, <br>            gl.UNSIGNED_BYTE, <br>            new Uint8Array(depthInfo.data, 0, depthInfo.data.byteLength)<br>        );<br>        <br>        gl.uniform1i(customShader.getUniformDepthTexture(), 0);<br>        // Set up UV transform<br>        const uvTransformLocation = customShader.getUniformDepthUVTransform();<br>        const matrix = depthInfo.normDepthBufferFromNormView.matrix;<br>        // Bind the uv transform matrix<br>        gl.uniformMatrix4fv(uvTransformLocation, false, matrix);<br>        // Set the depth scale<br>        const depthScaleLocation = customShader.getUniformDepthScale();<br>        gl.uniform1f(depthScaleLocation, depthInfo.rawValueToMeters);<br>        // Set the resolution<br>        gl.uniform2f(customShader.getUniformResolution(), viewport.width, viewport.height);<br>    }<br>}</pre><p>If available, we activate and bind the texture we created earlier so that we can update it’s data with the new data that we have. Take a look at the following.</p><pre>gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE_ALPHA, <br>    depthInfo.width, depthInfo.height, <br>    0, gl.LUMINANCE_ALPHA, <br>    gl.UNSIGNED_BYTE, <br>    new Uint8Array(depthInfo.data, 0, depthInfo.data.byteLength)<br>);</pre><p>Remember that we requested luminance-alpha? So, we need to make sure that when we create the texture, we pass gl.LUMINANCE_ALPHA. Since depthInfo has width and height properties, we can easily use them to set the texture&#39;s width and height. The actual texture/depth data is stored in depthInfo.data, so create an array with that and pass it into the function.</p><pre>gl.uniform1i(customShader.getUniformDepthTexture(), 0);<br>// Set up UV transform<br>const uvTransformLocation = customShader.getUniformDepthUVTransform();<br>const matrix = depthInfo.normDepthBufferFromNormView.matrix;<br>// Bind the uv transform matrix<br>gl.uniformMatrix4fv(uvTransformLocation, false, matrix);<br>// Set the depth scale<br>const depthScaleLocation = customShader.getUniformDepthScale();<br>gl.uniform1f(depthScaleLocation, depthInfo.rawValueToMeters);<br>// Set the resolution<br>gl.uniform2f(customShader.getUniformResolution(), viewport.width, viewport.height);</pre><p>In the above code, we set the uniform values to be passed. Notice that we get the depthUVTransform matrix from depthInfo.normDepthBufferFromNormView.matrix, and we get the depthScale from depthInfo.rawValueToMeters property. When setting the resolution, we simply use our viewport&#39;s width and height.</p><pre>for(let i = 0; i &lt; views.length; i++) { // As this is AR, only one view<br>    const viewport = glLayer.getViewport(views[i]) as XRViewport;<br>    renderer.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height);  // Set the frambuffer viewport. This matches the camera display<br>    <br>    // DEPTH SENSING CODE &lt;--- OUR NEW CODE<br>    const depthInfo = frame.getDepthInformation(views[i]);<br>    if(depthInfo){<br>        gl.activeTexture(gl.TEXTURE0);<br>        gl.bindTexture(gl.TEXTURE_2D, depthTexture);<br>        gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE_ALPHA, <br>            depthInfo.width, depthInfo.height, <br>            0, gl.LUMINANCE_ALPHA, <br>            gl.UNSIGNED_BYTE, <br>            new Uint8Array(depthInfo.data, 0, depthInfo.data.byteLength)<br>        );<br>        <br>        gl.uniform1i(customShader.getUniformDepthTexture(), 0);<br>        // Set up UV transform<br>        const uvTransformLocation = customShader.getUniformDepthUVTransform();<br>        const matrix = depthInfo.normDepthBufferFromNormView.matrix;<br>        // Bind the uv transform matrix<br>        gl.uniformMatrix4fv(uvTransformLocation, false, matrix);<br>        // Set the depth scale<br>        const depthScaleLocation = customShader.getUniformDepthScale();<br>        gl.uniform1f(depthScaleLocation, depthInfo.rawValueToMeters);<br>        // Set the resolution<br>        gl.uniform2f(customShader.getUniformResolution(), viewport.width, viewport.height);<br>    }<br>    // Draw two triangles to encompass the whole screen (Already defined in the shader)<br>    gl.drawArrays(gl.TRIANGLES, 0, 6);<br>}</pre><p>Then, we simply call the gl.drawArrays function with 6 indices. This lets the shader know that we are drawing the vertices from an array of size 6, where the main function is invoked 6 times. Each time, it will have a gl_VertexID to index the array. We specify the mode as gl.TRIANGLES so that those indices are used to create triangles. The rest is handled by our custom vertex shader.</p><p>And that’s it!</p><h3>A Quick Run</h3><p>Let’s run this app for a quick demo and see the results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NWuJN1hI_js3oB_VAI2IIw.gif" /><figcaption>Demo Run</figcaption></figure><p>I find it really cool!</p><h3>Wrap up</h3><p>I plan to extend this feature to our AR app that we have been implementing thus far to write these articles. I mentioned in my previous article that we can use this feature to implement occlusion with real-world objects. So hopefully, in one of my next articles, we will dive into that use-case. For that, this understanding is needed. I hope you were able to grasp everything. If not, please let me know. I will help. Until next time, do your best!</p><h3>External Links</h3><p>Source code: <a href="https://github.com/Ramith-D-Rodrigo/Medium/tree/master/webar-depth-sensing-intro">https://github.com/Ramith-D-Rodrigo/Medium/tree/master/webar-depth-sensing-intro</a></p><p>The codes I got inspired from: <a href="https://immersive-web.github.io/webxr-samples/proposals/">https://immersive-web.github.io/webxr-samples/proposals/</a></p><p>A useful youtube video: <a href="https://www.youtube.com/watch?v=ywtNVL-nkAw">https://www.youtube.com/watch?v=ywtNVL-nkAw</a> (uses Three.js)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72accf544e3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebXR Device API Hit Test — Adding virtual objects to the AR session manually]]></title>
            <link>https://medium.com/@ramithrodrigo/webxr-device-api-hit-test-adding-virtual-objects-to-the-ar-session-manually-91c1201cc555?source=rss-5003525022b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/91c1201cc555</guid>
            <category><![CDATA[hittest]]></category>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[webar]]></category>
            <category><![CDATA[webxr]]></category>
            <dc:creator><![CDATA[Ramith D. Rodrigo]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 16:05:07 GMT</pubDate>
            <atom:updated>2025-03-04T16:05:07.784Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebXR Device API Hit Test — Adding virtual objects to the AR session manually</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6BYrfpUJGa9A_BLG9EPu3g.jpeg" /><figcaption>Hit Testing in AR</figcaption></figure><p>In my <a href="https://medium.com/@ramithrodrigo/on-to-the-realm-of-web-based-augmented-reality-using-webxr-device-api-creating-a-basic-webar-70727865f8fb">previous article</a>, we went through the fundamentals of WebXR Device API and how to create a small WebAR session to render a single 3D model on our immersive augmented world using simply WebGL.</p><p>However, we did not have any control over the placement of the 3D model in our augmented world. Well, if you want your 3D models to be in some exact place, that is some other story. But, it gives a sense of immersion and power to the end-user if they can place these models at their desired places. To do so, we need to utilize some specific feature. It is called <strong>“Hit Testing”</strong>.</p><h3>Hit Testing</h3><p>You can read the full definition from the <a href="https://immersive-web.github.io/hit-test/hit-testing-explainer.html#introduction">spec itself</a>, but I am going to briefly explain that definition. If you are familiar with game development, you might know about raycasting. Essentially, it is a technique used to draw a virtual ray (most of the time, it is a line) from a given location (start) to some other location (end). The starting location is usually the in-game camera. The idea is to find 3D objects that are intersected when we draw this line between the defined points. With this we can identify the objects in between these two points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*uyhOa5wUBkfBYvUL.jpg" /><figcaption>Raycasting example (Taken from: <a href="https://www.codinblack.com/raycasting-in-unity3d/">https://www.codinblack.com/raycasting-in-unity3d/</a>)</figcaption></figure><p>But it is kind of easy to do this if the whole scene is virtual, because the application knows everything about the 3D scene. But that is not the case for AR. The API does not have a 3D scene of the user’s real-world. Hence, API needs to understand the real-world first. Once that is achieved, it provides a method to do hit testing (raycasting) against that understood real-world.</p><p>The difference is that when we perform the hit test in an AR session, it tries to find any intersections/hits with the real world geometry, unlike the virtual 3D objects in games as I have mentioned previously.</p><blockquote>But what does this has to do with placing the 3D objects?</blockquote><p>Once we request this feature, the API will perform the hit test in each frame. When the frame has any hit test result, we know that result refers to a location where this ray has hit in the real world. We can use that result to do useful rendering. One use case is to place a 3D model where the ray has hit. This is possible because the result contains the real-world transform where the ray has hit. Let’s take the above figure for an example. Suppose our mobile device is at the origin. When the API performs the hit test, the virtual ray will hit the box. That hit location is the hit-test result, which contains the real-world transform (position and orientation).</p><h3>Implementation</h3><p>We can jump straight into the implementation because that is all we need to know from a theoretical perspective, at least for our use case. Now, I will be modifying our project that we have created in the previous article. But rest assured, I pushed it to GitHub as a different project, so that we will have the both implementations.</p><h4>Modifying the main function: Load Reticle 3D model</h4><p>First, let’s modify the main function.</p><pre>async function main() {<br>    await setupRenderer();<br><br>    // Load the model <br>    model = await renderer.loadModelData(&#39;models/yoshikage_kira/scene.gltf&#39;);<br><br>    // Load the reticle model<br>    const reticle = await renderer.loadModelData(&#39;models/reticle/reticle.gltf&#39;);<br>    reticleSceneObj = await renderer.createModelSceneObject(reticle, vec3.fromValues(0, 0, 0,), vec3.fromValues(0, 0, 0), vec3.fromValues(1, 1, 1));<br>    renderer.addSceneObjectToScene(reticleSceneObj);<br><br>    // Add an event listener to the AR button<br>    const arButton = document.querySelector(&#39;#btn&#39;);<br>    arButton?.addEventListener(&#39;click&#39;, startARSession);<br>}</pre><p>You see that, unlike the last time we don’t add our 3D object directly into the scene. Because we want to load the model and keep it for later use, so that we can add multiple instances during the runtime.</p><p>Next, I also load another 3D model called “reticle” and add it to the scene directly to keep track of the hit location in each frame. So it is easy to understand for the user where the actual 3D object will be placed in the real-world. This “reticle” 3D model is taken from <a href="https://github.com/immersive-web/webxr-samples/">WebXR Samples GitHub repository</a>.</p><p>Since, the reticle scene object’s position and orientation is changed during the runtime, we need to store the object reference globally. So, I declare that variable below our previous global variables.</p><pre>// Global Variables<br>let gl : WebGL2RenderingContext;<br>let renderer : GLRenderer;<br>let model: GLModel;<br><br>let reticleSceneObj: GLSceneObject; // keep the reference to change the transform</pre><h4>Requesting the Hit-test feature</h4><p>Like I stated in my previous article, due to security considerations, not all features are available by default when we initialize an AR session. We must request each feature during the initialization. If you remember, I also kept the options variable that we pass to the requestSession function as a global variable for easier modification. So let’s modify it.</p><pre>const options : XRSessionInit = {<br>    requiredFeatures: [&#39;unbounded&#39;, &#39;hit-test&#39;] // also request hit-test feature<br>}</pre><p>You can see that, apart from the unbounded feature, we now also request the hit-test feature.</p><h4>Modify the startARSession function</h4><p>This was our startARSession function.</p><pre>async function startARSession() {<br>    if(!await isARSupported()) {<br>        return;<br>    }<br><br>    const ARSession : XRSession = await navigator.xr?.requestSession(&#39;immersive-ar&#39;, options) as XRSession;<br>    ARSession.addEventListener(&#39;end&#39;, () =&gt; {<br>        shutDownARSession(ARSession);<br>    });<br><br>    // Create a WebGL layer to present the rendered frames to the session.<br>    await ARSession.updateRenderState({<br>        baseLayer: new XRWebGLLayer(ARSession, gl)<br>    });<br><br>    // Request the reference spaces<br>    viewerRefSpace = await ARSession.requestReferenceSpace(&#39;viewer&#39;);<br>    localRefSpace = await ARSession.requestReferenceSpace(&#39;local&#39;);<br>    unboundedRefSpace = await ARSession.requestReferenceSpace(&#39;unbounded&#39;);<br><br>    //Hit-test specific configuration<br><br>    // Request the animation frame<br>    const animationID = ARSession.requestAnimationFrame(onDrawFrame);<br>}</pre><p>You can notice that I have added a comment: //Hit-test specific configuration. This is where we initialize our variables related to the hit-test feature. So let’s start. Once we request the session from navigator.xr with our required features, it will return an object of type XRSession . This object is generic for all the requests, regardless of the options that we require. We know that in JavaScript/TypeScript, an object can have optional fields and functions. So, we need to make sure if our ARSession object contains the relevant fields and functions. Since we have requested the session using requiredFeatures , it is guaranteed to have the relevant requested features given that the device supports them. But just to be sure, we check if there are available. So we create an if condition as follows.</p><pre>if(ARSession.requestHitTestSource){<br>  //config<br>}</pre><p>requestHitTestSource is a function. So we check whether the function is available because we need that to configure our hit testing.</p><p>Inside the if condition, we add the following code.</p><pre>if(ARSession.requestHitTestSource){<br>    arHitTestSource = await ARSession.requestHitTestSource({<br>        space: viewerRefSpace<br>    });<br><br>    ARSession.addEventListener(&#39;select&#39;, onSelect);<br>}</pre><p>Let me you explain the configuration.</p><p>await keyword is used because that function is asynchronous. In that function, we pass an object that has a field called space . And the value of that field is viewerRefSpace .</p><blockquote>But why viewerRefSpace ?</blockquote><p>Remember, in the previous article I explained what is the viewer reference space and what is used for. When we request the hit test source, we say that the space of that source is viewer reference space. Viewer represents the device. Thus, if we want our hit test to originate from our device (source), then we must use the viewer reference space. Here’s how the <a href="https://immersive-web.github.io/hit-test/hit-testing-explainer.html">explainer </a>describe space property:</p><blockquote>space is required and is the XRSpace to be tracked by the hit test source. As this XRSpace updates its location each frame, the XRHitTestSource will move with it.</blockquote><p>You can see why viewerRefSpace matters because, we move our device in each frame and thus the hit-test source has to keep track of that to conduct accurate hit-testing.</p><p>Also arHitTestSource is declared globally because we will be using in our rendering loop.</p><pre>let reticleSceneObj: GLSceneObject; // keep the reference to change the transform<br>let arHitTestSource: XRHitTestSource | undefined;</pre><p>Finally, we add an event listener to our ARSession . Like I mentioned, what we are trying to achieve here is to render 3D models at specific locations during the runtime. But we must give the option of placing the model to the user. The user can point the device where they want and if they are satisfied they notify the app to place the 3D model. We can achieve this by simply adding a select event, where the user touches the screen to invoke it.</p><h4>Creating the onSelect event function</h4><p>Okay, let’s create the onSelect function.</p><pre>// Function to spawn model on touch select event<br>async function onSelect(event: Event) {<br><br>    const sceneObject = await renderer.createModelSceneObjectFromQuats(model, <br>        reticleSceneObj.getPosition(),<br>        reticleSceneObj.getRotation(),<br>        vec3.fromValues(0.5, 0.5, 0.5)<br>    );<br><br>    sceneObject.rotate(vec3.fromValues(-90, 0, 0));<br><br>    renderer.addSceneObjectToScene(sceneObject);<br>}</pre><p>The logic is pretty simple. When the user touches the screen, we call our renderer’s creating model scene object function with our original 3D model. Notice that we pass our reticle scene object’s position and rotation as the arguments because that is where we want to place our 3D model! If you are having difficulties to understand this one, let me break it down:</p><ol><li>Reticle object is used to represent the hit test result location.</li><li>Meaning, reticle object is placed where the current hit test has occurred in the real-world.</li><li>So, if we get it’s position and rotation at the time of select event occurs, we actually get the current hit test result location.</li></ol><blockquote>But how do we actually change the reticle position and rotation?</blockquote><p>We will get to that very soon. For now, let’s focus on here. After we create the scene object, we simply need to add it to our scene. But before that, I have rotated it in the x-axis with the degree of -90. It is actually because, the 3D model that I am using is not correctly oriented, or atleast when using in my renderer. So I just rotate it by -90 degrees to make my 3D model correctly oriented. I also did this in my previous article.</p><h4>Modifying the rendering loop</h4><p>So, currently our rendering loop looks like this.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br><br>    if(pose) {<br>        // Get the rendering layers and the views<br>        const glLayer = session.renderState.baseLayer as XRWebGLLayer;<br>        const views = pose.views;<br><br>        // Check for hit-test results &lt;---- RIGHT HERE!!!<br><br>        // Do the Rendering<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);<br>        <br>        gl.clearColor(0, 0, 0, 0); // RGBA values, fully transparent<br>        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);<br><br>        const scene = renderer.getScene() as GLScene; // Contains the virtual objects<br>        const shader = renderer.getShader() as Shader;<br><br>        shader.useShader(); // Use the shader program<br><br>        for(let i = 0; i &lt; views.length; i++) { // As this is AR, only one view<br>            const viewport = glLayer.getViewport(views[i]) as XRViewport;<br>            renderer.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height);  // Set the frambuffer viewport. This matches the camera display<br>            const uniforms = renderer.getUniforms();<br>            renderer.useLights(scene, uniforms);<br><br>            const projectionMatrix = views[i].projectionMatrix;<br>            const viewMatrix = views[i].transform.inverse.matrix; // Inverse because view camera / the user should be at the origin<br>    <br>            gl.uniformMatrix4fv(uniforms.uniformProjection, false, projectionMatrix);<br>            gl.uniformMatrix4fv(uniforms.uniformView, false, viewMatrix);<br><br>            const sceneObjects = scene.getSceneObjects();<br>            for(let i = 0; i &lt; sceneObjects.length; i++) {<br>                renderer.renderSceneObject(sceneObjects[i] as GLSceneObject, mat4.create(), uniforms.uniformModel as WebGLUniformLocation, <br>                uniforms.uniformModelInverse as WebGLUniformLocation, uniforms.uniformTexture as WebGLUniformLocation);<br>            }<br>        }<br><br>        gl.useProgram(null); // Un assign the shader program<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, null); // Unbind the framebuffer<br>    }<br>}</pre><p>I have added a comment, which you may have noticed. That is where we implement the hit test logic that is suited for our use case.</p><p>Remember the arHitTestSource variable, which we declared globally? We will be using that. First, we need to make sure it is clearly defined and has a value. Thus, we create an if condition.</p><pre>// Check for hit-test results<br>if(arHitTestSource) {<br><br>}</pre><p>Then, we use the frame variable, which is of type XRFrame . Remember that we got our viewer pose that variable? Likewise, we also get the hit-test results from it. This is because it contains all the information of the XR session for that particular frame. I mean, this is the<a href="https://immersive-web.github.io/webxr/#xrframe-interface"> definition taken from the spec</a>:</p><blockquote>Represents a snapshot of the state of all of the tracked objects for an XRSession. Applications can acquire an XRFrame by calling requestAnimationFrame() on an XRSession with an XRFrameRequestCallback. When the callback is called it will be passed an XRFrame. Events which need to communicate tracking state, such as the select event, will also provide an XRFrame.</blockquote><p>So, we will have a line like below.</p><pre>// Check for hit-test results<br>if(arHitTestSource) {<br>  const hitResults = frame.getHitTestResults(arHitTestSource as XRHitTestSource);<br>}</pre><p>Notably, hitResults is an array. In game development also, when we do raycasting, it will provide all the hit-test results from the source to the destination. We can decide which one is useful for us. As for this API, it conveniently orders the hit-test results based on the distance. That means, the 1st element (0th index) of the array is the closest hit-test result from the device. In this implementation, we will consider the nearest hit-test result only.</p><p>Also remember that the array can be empty, meaning the API could not find any hit-test results for that particular frame.</p><pre>// Check for hit-test results<br>if(arHitTestSource) {<br>  const hitResults = frame.getHitTestResults(arHitTestSource as XRHitTestSource);<br>  if(hitResults.length &gt; 0) {<br>      let hitResultPose = hitResults[0].getPose(unboundedRefSpace);<br>      if(hitResultPose) {<br><br>      }<br>  }<br>}</pre><p>So, if the length is greater than 0, we know that we have some hit-test results. Then we access the first element and get it’s pose relative to the unboundedRefSpace because we want the location relative to the immersive world.</p><p>The rest is quite simple. We just use that pose to get the position and orientation of that hit-test result and assign it to our reticle scene object.</p><pre>// Check for hit-test results<br>if(arHitTestSource) {<br>  const hitResults = frame.getHitTestResults(arHitTestSource as XRHitTestSource);<br>  if(hitResults.length &gt; 0) {<br>      let hitResultPose = hitResults[0].getPose(unboundedRefSpace);<br>      if(hitResultPose) {<br>        let posX = hitResultPose.transform.position.x;<br>        let posY = hitResultPose.transform.position.y;<br>        let posZ = hitResultPose.transform.position.z;<br>  <br>        let rotX = hitResultPose.transform.orientation.x;<br>        let rotY = hitResultPose.transform.orientation.y;<br>        let rotZ = hitResultPose.transform.orientation.z;<br>        let rotW = hitResultPose.transform.orientation.w;<br>  <br>        const hitLocationPosition = vec3.fromValues(posX, posY, posZ);<br>        const hitLocationOrientation = quat.fromValues(rotX, rotY, rotZ, rotW);<br>  <br>        reticleSceneObj.setPosition(hitLocationPosition);<br>        reticleSceneObj.setRotation(hitLocationOrientation);<br>      }<br>  }<br>}</pre><p>In my renderer framework, it is impossible to pass the transform matrix directly. So I had to extract the position and orientations separately and create the vector and quaternion. Then I used them to set the new position and rotation of our reticle scene object.</p><p>That’s it! Because, since this is being done in each frame, reticle’s position and orientation is updated accordingly. If the user decides to place a 3D model, they will touch the screen, which will invoke the onSelect function, taking care of placing the model correctly within the world.</p><p>Rest of the code remains unchanged, as the rendering is already implemented and the scene rendering is handled by our renderer.</p><p>Here’s a small GIF showcasing our current WebAR app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*SjG_JCPs5IcOGlV8UEpoWw.gif" /><figcaption>Hit test demo</figcaption></figure><p>Unlike the previous article, this one is a bit short as we only discussed one feature of WebAR. If you require the code of this implementation, please refer <a href="https://github.com/Ramith-D-Rodrigo/Medium/tree/master/webar-hittest">here</a>.</p><p>One thing, you might have noticed that even if we place the 3D model behind a real-world object, it still renders on top of the real-world object. This is because, we are actually rendering our virtual object <strong>on top </strong>of the camera overlay. That kinds of take away the immersion, right? Yes. But there’s a neat trick to mitigate this up to some degree. It is called depth sensing, which is going to be the topic of my next article (Hopefully).</p><p>Until I get to it, please wait. I hope this article has helped you in any manner. If there’s any question or suggestion, please let me know in the comments. I am happy to have a conversation. Until next time, do your best!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91c1201cc555" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On to the realm of Web-based Augmented Reality using WebXR Device API — Creating a basic WebAR…]]></title>
            <link>https://medium.com/@ramithrodrigo/on-to-the-realm-of-web-based-augmented-reality-using-webxr-device-api-creating-a-basic-webar-70727865f8fb?source=rss-5003525022b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/70727865f8fb</guid>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[webar]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[webxr]]></category>
            <dc:creator><![CDATA[Ramith D. Rodrigo]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 09:28:42 GMT</pubDate>
            <atom:updated>2025-01-19T09:28:42.135Z</atom:updated>
            <content:encoded><![CDATA[<h3>On to the realm of Web-based Augmented Reality using WebXR Device API — Creating a basic WebAR session</h3><figure><img alt="Augmented Reality" src="https://cdn-images-1.medium.com/max/1024/0*ZuQ0Wb3wTekjgdIU" /><figcaption>Photo by <a href="https://unsplash.com/@uniboa?utm_source=medium&amp;utm_medium=referral">UNIBOA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Content</h3><ul><li>Introduction to Extended Reality</li><li>Why we should understand the bridge between WebAR and rendering</li><li>Prerequisites</li><li>Introduction to WebXR Device API</li><li>Create a basic WebAR session</li></ul><h3>Introduction to Extended Reality</h3><p>Extended Reality (XR) refers to technologies designed to create immersive digital experiences. It’s an umbrella term that covers three main categories:</p><ol><li><strong>Virtual Reality (VR):</strong> Fully immersive experiences that place users in a completely virtual environment.</li><li><strong>Augmented Reality (AR):</strong> Enhancing the real world by overlaying virtual elements, like 3D models or interactive visuals.</li><li><strong>Mixed Reality (MR):</strong> The combination of VR and AR.</li></ol><h3>Connection between WebXR and rendering</h3><p>In this article, I’ll focus on Augmented Reality (AR), specifically on the web. As part of my journey to learn about WebAR implementation, I’ve been exploring the <strong>WebXR Device API</strong>. While the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API">MDN documentation</a> provides a solid introduction to using it, I noticed a lack of tutorials that highlight the connection between the WebXR Device API and rendering — and how they remain decoupled.</p><p>Most tutorials rely heavily on libraries like Three.js, which abstract away the lower-level details to speed up implementation. While this is great for quick prototyping, I believe it’s important to first understand the fine line between WebXR and rendering before diving into higher-level abstractions.</p><p>That said, it’s not practical to explain everything from scratch for someone entirely new to this topic. So, before we dive deeper, let’s define some prerequisites.</p><h3>Prerequisites</h3><ul><li><strong>Fundamental Knowledge of Computer Graphics</strong> <br>- You should have a good understanding of the rendering pipeline, shaders, linear algebra, and matrices. This foundation is essential to grasp how the WebXR Device API is decoupled from rendering.</li><li><strong>Basic rendering using WebGL</strong><br>- You should know how to render a simple scene using only the WebGL library. This includes tasks like allocating GPU buffers, setting uniform variables, and working with shader programs.<br>- Don’t worry, though — I’ll abstract most of these details and only highlight the commands necessary to show how the WebXR Device API and WebGL work together to create a WebAR session.</li><li><strong>TypeScript Proficiency</strong><br>- Yes, I’ll be using TypeScript instead of JavaScript. Why? Because TypeScript’s strong typing helps reduce runtime errors, which is a big deal in graphics programming. Debugging is already a time-consuming process, so the last thing we need is dealing with CPU-side type errors on top of it.</li></ul><h3>Introduction to WebXR Device API</h3><p>Let’s kick things off with a brief introduction to the <strong>WebXR Device API</strong>. This API is a specification developed by <a href="https://www.w3.org/">W3C</a>, meaning it defines the standards that browser vendors must follow when implementing it.</p><p>Unlike native applications, web-based apps operate in a sandboxed environment with limited access to device hardware. This limitation is intentional — it ensures user privacy and security. The WebXR Device API specification outlines how the API can work within these constraints, including how to request additional access with user consent when needed.</p><p>You’ve probably noticed that web browsers don’t automatically use your device hardware. Instead, they prompt you for permission before accessing features like your camera or motion sensors. This behavior is critical for protecting user privacy, and it’s something the WebXR Device API adheres to, even when enabling XR capabilities.</p><p>The WebXR Device API includes “XR” in its name for a reason — it can be used to implement both AR and VR applications. However, for this article, I’ll only focus on AR.</p><p>Regardless of whether you’re working with AR or VR, the API has one primary responsibility:</p><blockquote><strong>To handle the necessary computations for XR tasks</strong></blockquote><p>The WebXR Device API fulfills its responsibility by leveraging device sensors and hardware. As developers, it’s up to us to call the necessary functions provided by the API to retrieve the results of these XR computations. Then, we must use those results to handle the rendering. This is the “fine line” I mentioned earlier between the API and rendering.</p><p>However, there’s a catch. For instance, to create a WebAR session, we need a camera overlay. That overlay must be rendered and displayed as part of the session. In this case, the WebXR Device API takes care of requesting camera access from the user and initializing the rendering context for the overlay.</p><p>So, while the WebXR Device API is mostly decoupled from rendering, it’s not entirely independent. (I’ll include example code to demonstrate where this happens.)</p><p>I believe the information we’ve covered so far is enough to get started on our WebAR journey. Here’s what we’ll be doing in this article:</p><ol><li>Initialize the TypeScript project.</li><li>Configure the project.</li><li>Setup the renderer.</li><li>Initialize a WebAR session.</li><li>Load a 3D model and render it in the augmented world.</li></ol><h3>Initialize the TypeScript Project</h3><p>Let’s dive into our first task! To get started, we’ll need a few dependencies. First, make sure you have <strong>Node.js</strong> and <strong>npm</strong> installed.</p><p>Once that’s set up, create a new folder for your project. You can name it whatever you like, but for this guide, I’ll refer to the project as <strong>“webar-intro”</strong>.</p><p>After creating the folder, open your terminal in that directory and run the following command to initialize the project:</p><pre>npm init -y</pre><p>Once completed, run the following command to install TypeScript, and Vite as dev dependencies.</p><pre>npm install --save-dev typescript vite @types/three </pre><p>Finally, run the following command to initialize a TypeScript project.</p><pre>npx tsc --init</pre><p>With that, we can continue to configure our project.</p><h3>Configure the Project</h3><p>Before installing the necessary dependencies, let’s configure the tsconfig.json file. Open the file and modify the following values:</p><pre>{<br>  &quot;compilerOptions&quot; : {<br>    &quot;target&quot;: &quot;ES2020&quot;,<br>    &quot;module&quot;: &quot;ESNext&quot;,<br>    &quot;moduleResolution&quot;: &quot;Node&quot;,<br>    &quot;allowJs&quot;: true,<br>    &quot;checkJs&quot;: false,<br>    &quot;outDir&quot;: &quot;./dist&quot;<br>  },<br>  &quot;include&quot;: [&quot;src/*&quot;],<br>}</pre><p>Now we will install the necessary project dependencies.</p><p>Earlier, I mentioned that it’s impractical to build everything from scratch. What I meant by that is we don’t need to reinvent the wheel when it comes to loading 3D models, uploading vertex data to buffers, and handling other low-level rendering tasks. These concepts are more relevant to graphics programming and are not directly tied to AR. That’s why I’ve abstracted this logic for you.</p><p>I’ve created a minimalistic WebGL framework that you can use in this project. Here’s the <a href="https://github.com/Ramith-D-Rodrigo/WebGL-Framework">GitHub link</a>.</p><p>Instead of diving into all the nitty-gritty details, we’ll use this framework as a library. First, clone the repository and build it. Once that’s done, create a folder called src in the root directory of your project. Inside src, create a folder called webgl-framework, and paste the built files there.</p><p>I know this isn’t the most efficient way to manage and share custom npm packages across projects, but my main focus here is the WebAR implementation. With that said, we’ll need to install some dependencies for the framework in this project. So, please bear with me and run the following command in your terminal:</p><pre>npm install dat.gui &quot;@loaders.gl/gltf&quot;</pre><p>Then, we install the other dependencies required by this project.</p><pre>npm install @types/webxr gl-matrix</pre><p>And yes, we can combine the above commands into one. I just divided them into two to give clarity. @types/webxr is needed to handle the XR related types. gl-matrix is a math library where we can manipulate vertices and matrices.</p><p>Then, open the package.json file and the following fields.</p><pre>{<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;<br>  }<br>}</pre><p>&quot;type”:”module&quot; is needed for the vite configuration which we are going to do next. &quot;dev”:”vite” is added to run a development server of our project.</p><p>Now, create a file called vite.config.ts in the root directory of the project and add the following content to it.</p><pre>import {defineConfig} from &quot;vite&quot;;<br>import glsl from &quot;vite-plugin-glsl&quot;;<br><br>export default defineConfig({<br>  server: {<br>    open: true,<br>    port: 5500<br>  },<br><br>  plugins: [<br>    glsl()<br>  ]<br>});</pre><p>Now you might get an error related to vte-plugin-glsl. This is needed to load our shader files of our framework. Hence, we need to install it by executing the following command in the terminal.</p><pre>npm install --save-dev vite-plugin-glsl</pre><p>Next task is to create the index.html, which is our entry point html file of the app. So, go ahead and create that file in the project root directory. Then add the following content.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;title&gt;WebAR Example&lt;/title&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>        &lt;script type=&quot;module&quot; src=&quot;src/index.ts&quot;&gt;&lt;/script&gt;<br>        &lt;style&gt;<br>            /* Add CSS to ensure the canvas occupies the full viewport */<br>            body, html {<br>                margin: 0;<br>                padding: 0;<br>                width: 100%;<br>                height: 100%;<br>                overflow: hidden; /* Prevent scrolling */<br>            }<br><br>            .btn-container {<br>                display: flex;<br>                align-items: center;<br>                justify-content: center;<br>            }<br>            .btn {<br>                background-color: blue;<br>                color: white;<br>                font-size: larger;<br>            }<br>        &lt;/style&gt;<br>    &lt;/head&gt;<br><br>    &lt;body class=&quot;btn-container&quot;&gt;<br>        &lt;button id=&quot;btn&quot; class=&quot;btn&quot;&gt;Start AR&lt;/button&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>So in the html file, we can see that we are importing a script of module type. So let’s create it inside the <strong>src </strong>folder. Name that file index.ts .</p><p>And that is about it for the configuration. Now we can start implementing our WebAR app.</p><h3>Setup the renderer</h3><p>First things first, we need to set up our renderer, which is provided by the framework. Open the index.ts file and create a function called setupRenderer().</p><p>This function needs to be asynchronous because we’ll be loading shader files. In the framework, I’ve implemented a plugin that allows us to load shader files directly, so we don’t have to manually fetch them. Initially, when I built the framework, I didn’t use this plugin and had to rely on the fetch method. But since the framework’s implementation already defines an asynchronous function for this task, we need to mark our setupRenderer() function as asynchronous as well.</p><p>Here’s how you can define the function:</p><pre>// Setup our Renderer object<br>async function setupRenderer() {<br>  // To get the GL context<br>  const canvas = document.createElement(&#39;canvas&#39;);<br><br>  renderer = await GLRenderer.RendererInstance(canvas, {<br>      powerPreference: &quot;high-performance&quot;,<br>      antialias: false,<br>      alpha: true,<br>      depth: true,<br>      stencil: false,<br>      xrCompatible: true<br>  });<br><br>  // Add a virtual light<br>  const light: GLDirectionalLight = renderer.createDirectionalLight(1, vec3.fromValues(1, 1, 1), 1, vec3.fromValues(2, -1, -2));<br>  renderer.addLightToScene(light);<br><br>  // We need the GL context to pass that to XR<br>  gl = renderer.getGL();<br>}</pre><p>Let’s walk through what’s happening in the setupRenderer() function.</p><p>First, we create a <strong>canvas</strong> element. This is essential because to access the WebGL context, we need a canvas.</p><p>Next, we create a <strong>renderer</strong> instance with specific options. The key options here are:</p><ul><li><strong>alpha</strong>: This is crucial because we need our WebGL framebuffer to support transparency, allowing us to render virtual objects on top of the camera overlay. If we set alpha to false, a solid background color would appear, and the camera overlay wouldn’t be visible.</li><li><strong>xrCompatible</strong>: This option ensures that the rendering context is properly configured for WebXR.</li></ul><p>We store this renderer instance in a global variable called renderer, so we can use it later.</p><p>Then, we add a <strong>virtual light</strong> to our scene. The reason for this is that our shader code calculates light contribution based on normals. While this virtual light will work for now, in the future, we could estimate the real-world light in the AR scene and use those values instead. This is something we’ll likely revisit later, but for now, this virtual light suffices.</p><p>Finally, we retrieve the <strong>WebGL rendering context</strong> and store it in a global variable called gl. We’re using this context outside the renderer object to show you exactly how WebGL is incorporated into the application.</p><p>And that’s all for setting up the renderer!</p><h3>Initialize a WebAR session</h3><p>When creating a WebAR session, we need to follow a specific protocol. The first step is to check if the device is capable of running the application. To do this, we’ll define a function called isARSupported(), which will return a boolean value indicating whether the device supports AR.</p><p>This function is asynchronous because we’ll be using the navigator object provided by the browser. The navigator object contains a property named xr, which includes the necessary functions for initializing an XR session.</p><p>Here’s what the body of our isARSupported() function will look like:</p><pre>async function isARSupported() : Promise&lt;boolean&gt; {<br>  if(!navigator.xr) {<br>      console.error(&quot;WebXR not supported&quot;);<br>      return false;<br>  }<br><br>  if(!await navigator.xr.isSessionSupported(&#39;immersive-ar&#39;)) {<br>      console.error(&quot;WebAR not supported&quot;);<br>      return false;<br>  }<br><br>  return true;<br>}</pre><p>First, we check if the xr property is available in the navigator object. If it is, we can then proceed to check whether the specific session type we need is supported. As mentioned earlier, WebXR supports both AR and VR, so we need to specify that we want to initialize an AR session. We do this by checking if the session type immersive-ar is supported using the isSessionSupported() function. If both conditions are met, we know the device is capable of supporting AR, and we return true.</p><p>The next step in the protocol is to <strong>request a session</strong>.</p><p>Since we’re building a web-based application, which runs inside a browser, we can’t directly access hardware or sensors the way native apps can. Browsers require user consent before allowing access to device hardware. To implement this, we can use a simple solution:</p><blockquote><strong>Adding a button</strong>.</blockquote><p>When the user presses the button, it signals the app that they’re ready to start the session. At this point, the browser will request the necessary permissions through a consent prompt or an alert, as shown in the following picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sftMT3-daF2alFfjYYwXqg.png" /><figcaption>Web browser is requesting for the permissions</figcaption></figure><p>So what we have to do is to add a button to our HTML body and add an event listener to that button. So let’s do that.</p><pre>  // Add an event listener to the AR button<br>  const arButton = document.querySelector(&#39;#btn&#39;);<br>  arButton?.addEventListener(&#39;click&#39;, startARSession);</pre><p>In the index.html file, we have already defined a button with the btn ID. Using this ID, we can reference the button in our JavaScript (or TypeScript) code and attach an event listener to handle the click event. Now, let&#39;s define the startARSession() function to trigger the AR session when the user clicks the button.</p><pre>async function startARSession() {<br>    // Check for support<br><br>    // Request the session<br><br>    // Create a WebGL layer to present the rendered frames to the session<br><br>    // Request the reference spaces<br><br>    // Request the animation frame<br>}</pre><p>The above code demonstrates the general structure and flow of the startARSession() function.</p><p>Since we’ll be using the xr property from the navigator object, we need to make this function asynchronous as well. The first thing we do is check if the device supports AR sessions by calling the isARSupported() function we defined earlier.</p><pre>async function startARSession() {<br>    // Check for support<br>    if(!await isARSupported()) {<br>        return;<br>    }<br><br>    // Request the session<br><br>    // Create a WebGL layer to present the rendered frames to the session<br><br>    // Request the reference spaces<br><br>    // Request the animation frame<br>}</pre><p>Next, we request the AR session by using the requestSession function from the xr property. We pass &#39;immersive-ar&#39; as the first argument to specify that we want to start an augmented reality session. Additionally, we provide an object called options as the second argument to configure the session.</p><pre>async function startARSession() {<br>    // Check for support<br>    if(!await isARSupported()) {<br>        return;<br>    }<br><br>    // Request the session<br>    const ARSession : XRSession = await navigator.xr?.requestSession(&#39;immersive-ar&#39;, options) as XRSession;<br>    ARSession.addEventListener(&#39;end&#39;, () =&gt; {<br>        shutDownARSession(ARSession);<br>    });<br><br>    // Create a WebGL layer to present the rendered frames to the session<br><br>    // Request the reference spaces<br><br>    // Request the animation frame<br>}</pre><blockquote>What is options?</blockquote><p>In the WebXR Device API, an immersive session doesn’t come with all features enabled by default. As developers, we need to specify which features we require for our application. While there are many possible features, in this article, we will focus only on the essential ones for creating a basic WebAR session.</p><p>Let’s define the options object as a global constant at the top of the code. This way, it will be easy to find and modify if we need to change or add more required features later.</p><pre>const options : XRSessionInit = {<br>  requiredFeatures: [&#39;unbounded&#39;]<br>}</pre><p>The options object has the type XRSessionInit. It includes a mandatory property called requiredFeatures, which accepts an array of strings where we specify the features we need. When requesting the session, if any of the requested features are not supported by the device, an error will be thrown.</p><p>However, if there are features that are not critical and can be omitted if not supported, we can use the optionalFeatures property. This allows us to create the session even if some of the features are unavailable. Here&#39;s how you can define it:</p><pre>const options : XRSessionInit = {<br>    requiredFeatures: [&#39;unbounded&#39;],<br>    optionalFeatures: [&#39;hit-test&#39;]<br>}</pre><p>In the above code fragment, we request both the unbounded and hit-test features. However, hit-test is not mandatory. If the device doesn&#39;t support the hit-test feature, the session will still be created without it. If we had included it in the requiredFeatures array, an error would be thrown if the feature is unsupported.</p><p>For now, we’ll use the previous options object with only the unbounded feature. The unbounded feature is used to specify that the session we&#39;re creating has no specific bounds. This is ideal for an AR session in an outdoor environment, where the viewer&#39;s position can change significantly during the session runtime. I chose this option because it’s more generalized and can encompass other session types.</p><p>There are many other features available, but I won’t go into all of them here. If you’re interested in exploring the full list, you can refer to this <a href="https://developer.mozilla.org/en-US/docs/Web/API/XRSystem/requestSession#session_features">link</a>.</p><p>Additionally, we also add an event listener to handle ending the immersive session.</p><pre>async function shutDownARSession(session: XRSession) {<br>    await session.end();<br>}</pre><p>Now let’s move on to the next part.</p><pre>async function startARSession() {<br>    // Check for support<br>    if(!await isARSupported()) {<br>        return;<br>    }<br><br>    // Request the session<br>    const ARSession : XRSession = await navigator.xr?.requestSession(&#39;immersive-ar&#39;, options) as XRSession;<br>    ARSession.addEventListener(&#39;end&#39;, () =&gt; {<br>        shutDownARSession(ARSession);<br>    });<br><br>    // Create a WebGL layer to present the rendered frames to the session.<br>    await ARSession.updateRenderState({<br>        baseLayer: new XRWebGLLayer(ARSession, gl)<br>    });<br><br>    // Request the reference spaces<br><br>    // Request the animation frame<br>}</pre><p>As mentioned earlier, we need a proper rendering context and layer to allow the WebXR Device API to display the AR session. To achieve this, we update the renderer’s gl context using the session object’s updateRenderState() function. This function requires an object with a property called baseLayer, which we assign a new instance of XRWebGLLayer. This is the place that I mentioned previously which has some dependency between WebXR and rendering.</p><p>The XRWebGLLayer is provided by the browser and represents the XR rendering layer. It links our AR session with the WebGL context (gl). The layer will handle rendering the XR content, including the AR camera feed, and manage all the layers that are being rendered on top.</p><p>After setting up the render layer, the next task is to request the reference spaces.</p><blockquote>What are “Reference Spaces”?</blockquote><p>Reference spaces are a critical concept in WebXR. Different XR devices (VR, AR, etc.) may have varying coordinate systems, and the WebXR Device API needs a standard way to translate between those device-specific coordinates and a more consistent, global coordinate system. This translation is done via <strong>reference spaces</strong>.</p><p>Essentially, a reference space maps the device’s local coordinate system to a global reference point (often the world or the viewer’s starting position). By using reference spaces, the WebXR Device API ensures that the positioning of virtual objects is consistent regardless of the device’s internal coordinate system.</p><p>For more detailed information on reference spaces and their types, you can refer to this <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API/Geometry">link</a>.</p><pre>async function startARSession() {<br>    // Check for support<br>    if(!await isARSupported()) {<br>        return;<br>    }<br><br>    // Request the session<br>    const ARSession : XRSession = await navigator.xr?.requestSession(&#39;immersive-ar&#39;, options) as XRSession;<br>    ARSession.addEventListener(&#39;end&#39;, () =&gt; {<br>        shutDownARSession(ARSession);<br>    });<br><br>    // Create a WebGL layer to present the rendered frames to the session.<br>    await ARSession.updateRenderState({<br>        baseLayer: new XRWebGLLayer(ARSession, gl)<br>    });<br><br>    // Request the reference spaces<br>    viewerRefSpace = await ARSession.requestReferenceSpace(&#39;viewer&#39;);<br>    localRefSpace = await ARSession.requestReferenceSpace(&#39;local&#39;);<br>    unboundedRefSpace = await ARSession.requestReferenceSpace(&#39;unbounded&#39;);<br><br>    // Request the animation frame<br>}</pre><p>For example, if we request the viewer reference space, we get a reference space that represents the device’s position and orientation in the session space. This reference space is useful for tracking the device’s position relative to the session’s coordinate system. It’s ideal for adding virtual objects or UI elements that should stay fixed relative to the viewer’s position or orientation.</p><p>However, since we requested the unbounded feature when initializing the session, we should use a reference space that represents the augmented world space. This type of reference space will track the position and orientation of virtual objects within the AR scene, while the world space remains anchored in the real-world environment.</p><p>In addition, I have also requested the local space, just to demonstrate how multiple reference spaces can be requested.</p><p>When you request reference spaces, make sure to store the resulting reference in a global variable, as we will need it for updating the positions of virtual objects and interacting with the AR world later.</p><p>After setting up the reference spaces, we initiate the rendering loop. Instead of using the browser’s standard requestAnimationFrame() function, we rely on the session object’s defined animation function. This is necessary because the display is managed by the WebXR Device API, ensuring that our content is displayed correctly in the AR session.</p><pre>async function startARSession() {<br>    // Check for support<br>    if(!await isARSupported()) {<br>        return;<br>    }<br><br>    // Request the session<br>    const ARSession : XRSession = await navigator.xr?.requestSession(&#39;immersive-ar&#39;, options) as XRSession;<br>    ARSession.addEventListener(&#39;end&#39;, () =&gt; {<br>        shutDownARSession(ARSession);<br>    });<br><br>    // Create a WebGL layer to present the rendered frames to the session.<br>    await ARSession.updateRenderState({<br>        baseLayer: new XRWebGLLayer(ARSession, gl)<br>    });<br><br>    // Request the reference spaces<br>    viewerRefSpace = await ARSession.requestReferenceSpace(&#39;viewer&#39;);<br>    localRefSpace = await ARSession.requestReferenceSpace(&#39;local&#39;);<br>    unboundedRefSpace = await ARSession.requestReferenceSpace(&#39;unbounded&#39;);<br><br>    // Request the animation frame<br>    const animationID = ARSession.requestAnimationFrame(onDrawFrame);<br>}</pre><p>Now we have to define, what we are going to do in each frame. For that we define a function called onDrawFrame(). This is where all the runtime execution is happening. So it is best to understand the logic very well.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    <br>    // Get the viewer&#39;s pose<br><br>    <br>    // Do the Rendering if the pose exists<br>}</pre><p>The onDrawFrame() function accepts two arguments. The first argument, t, is the timestamp of the current rendering frame. This is useful for performance metrics such as FPS and frame time. Additionally, it can be used to calculate delta time, which helps make the movements of virtual objects independent of platform performance. However, we won’t be using it for that purpose here, but we still need to define the argument.</p><p>The second argument is frame, which is an object containing data related to the current rendering frame.</p><p>In the onDrawFrame() function, we first request the next frame from the immersive session. This ensures that the onDrawFrame function will be called repeatedly.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br><br>    <br>    // Do the Rendering if the pose exists<br>}</pre><p>Once that is done, we have to retrieve the viewer’s pose. By viewer, we mean our device.</p><blockquote>But what is a pose?</blockquote><p>A pose represents a position and orientation in the current immersive session’s 3D space relative to a specified reference space. This definition is provided on this <a href="https://developer.mozilla.org/en-US/docs/Web/API/XRPose">webpage</a>. Remember how we requested some reference spaces earlier? We will be using them here.</p><p>To get the viewer’s / device’s pose relative the world that we intialized, we do the following.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br>    <br>    // Do the Rendering if the pose exists<br>}</pre><p>Notice that I have used the unboundedRefSpace. This is because that reference space is our world reference space. We are moving our device within that world, so it is imperative that we use this reference space to get the pose of the viewer/device.</p><p>Sometimes, the API might not be able to compute the relevant data before the app reaches the animation frame function. In such cases, the pose may not be available. Therefore, we need to ensure that the pose we are trying to access is available. To do this, we simply use an if condition. This is where we use the XR data to render the frame.</p><p>So, the first task of rendering is to get the rendering layer of the immersive session.</p><p>Then, we also access the views of the pose.</p><blockquote>What are views?</blockquote><p>A view is a description of how the frame should be rendered. For example, if we are creating a VR session, it should have two views, one for each eye. In an AR session, it will have only one view. Essentially, you can think of it as the camera(s) attached to that particular pose, facing towards the orientation specified in the pose. More on that can be found <a href="https://developer.mozilla.org/en-US/docs/Web/API/XRView">here</a>.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br>    <br>    // Do the Rendering if the pose exists<br>    if(pose) {<br>        // Get the rendering layers and the views<br>        const glLayer = session.renderState.baseLayer as XRWebGLLayer;<br>        const views = pose.views;<br>    }<br>}</pre><p>Once we get the GL layer, we access it’s framebuffer.</p><blockquote>What is a framebuffer?</blockquote><p>A framebuffer is the destination of the rendering pipeline. In other words, it is where the resulting frame rendered by the pipeline is stored. However, we can modify the destination. In WebGL, we create a WebGL context using an HTML canvas. When rendering, the resulting frame is displayed by this canvas, and WebGL stores the rendered frame in the canvas’s framebuffer. You could say that the canvas has its own framebuffer, which is the default framebuffer.</p><p>If we want to change that location, we can create a framebuffer object and specify it as the destination before issuing the draw calls.</p><p>In this scenario, however, that is already handled by the WebXR Device API. All we need to do is use the framebuffer created by the API to render the scene, so it will correctly display within our immersive session.</p><p>To use it, we simply bind the framebuffer, reset its values to clear any previous frame data, and, once rendering is complete, unbind the framebuffer.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br>    <br>    // Do the Rendering if the pose exists<br>    if(pose) {<br>        // Get the rendering layers and the views<br>        const glLayer = session.renderState.baseLayer as XRWebGLLayer;<br>        const views = pose.views;<br><br>        // Bind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);<br>        <br>        // Reset<br>        gl.clearColor(0, 0, 0, 0); // RGBA values, fully transparent<br>        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);<br><br>        // REMAINING CODE GOES HERE<br><br>        // Unbind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, null); <br>    }<br>}</pre><p>Notice that gl.clearColor(0, 0, 0, 0);&#39;s four zeros represent the RGBA values. We set the alpha to 0 because this makes the frame fully transparent. As mentioned earlier, this is necessary to display the virtual content on top of the camera overlay. You can experiment with different alpha values (e.g., set it to 1 for fully opaque) and observe how the camera overlay visibility changes.</p><p>Next, we have some lines of code related to our custom renderer. Keep in mind that this code should be placed between the binding and unbinding of the framebuffer.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br>    <br>    // Do the Rendering if the pose exists<br>    if(pose) {<br>        // Get the rendering layers and the views<br>        const glLayer = session.renderState.baseLayer as XRWebGLLayer;<br>        const views = pose.views;<br><br>        // Bind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);<br>        <br>        // Reset<br>        gl.clearColor(0, 0, 0, 0); // RGBA values, fully transparent<br>        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);<br><br>        const scene = renderer.getScene() as GLScene; // Contains the virtual objects<br>        const shader = renderer.getShader() as Shader;<br><br>        shader.useShader(); // Use the shader program<br><br>        // REMAINING CODE GOES HERE<br>         <br>        // Un assign the shader program<br>        gl.useProgram(null); <br>        // Unbind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, null);<br>    }<br>}</pre><p>We retrieve the scene, which contains all the scene objects/virtual objects. This is used later in the process. We also get the shader for our render because we need to enable it. In rendering, we could use different shader programs, but in this case, we only have one shader, so we use that one. At the end, we unassign the shader that was in use.</p><p>The next step is to traverse all the views and render them.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br>    <br>    // Do the Rendering if the pose exists<br>    if(pose) {<br>        // Get the rendering layers and the views<br>        const glLayer = session.renderState.baseLayer as XRWebGLLayer;<br>        const views = pose.views;<br><br>        // Bind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);<br>        <br>        // Reset<br>        gl.clearColor(0, 0, 0, 0); // RGBA values, fully transparent<br>        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);<br><br>        const scene = renderer.getScene() as GLScene; // Contains the virtual objects<br>        const shader = renderer.getShader() as Shader;<br><br>        shader.useShader(); // Use the shader program<br><br>        for(let i = 0; i &lt; views.length; i++) { // As this is AR, only one view<br>            const viewport = glLayer.getViewport(views[i]) as XRViewport;<br>            // Set the frambuffer viewport. This matches the camera display<br>            renderer.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height); <br>            const uniforms = renderer.getUniforms();<br>            renderer.useLights(scene, uniforms);<br><br>            // REMAINING CODE GOES HERE<br>        }<br><br>        // Un assign the shader program<br>        gl.useProgram(null); <br>        // Unbind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, null);<br>    }<br>}</pre><p>I mentioned that for AR sessions, we only have one view. However, the value returned by pose.views is an array. We simply create a for loop that will iterate only once.</p><p>The first step in the loop is to get the viewport. This is particularly important for VR, where each eye has a different viewport. In our case, the viewport represents the total viewport of the rendering frame, so we use its values for our renderer’s viewport.</p><p>Next, we retrieve the uniform locations of the shader program. As I mentioned earlier, I abstracted the process enough to remove unnecessary details. We know that the light is uniform for all the vertices and fragments, so we first set the virtual light with our uniform location. Remember that we can adjust the light’s values at this point.</p><p>The next task is to get the projection and view matrices of our scene camera. But what exactly is the scene camera? It’s the viewer, or our device. This means we can use view[i] to access both the projection matrix and the view matrix. The view object has a property called projectionMatrix, but not viewMatrix. However, we know that the view matrix corresponds to the camera’s transformation. This means, if we obtain the transformation matrix of our view, we can derive the view matrix. But that’s not enough. In graphics programming, we know that every object in the scene is translated so that the camera is positioned at the origin. This is achieved by taking the inverse of the camera’s transformation matrix. So, the relevant code will look as follows.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br>    <br>    // Do the Rendering if the pose exists<br>    if(pose) {<br>        // Get the rendering layers and the views<br>        const glLayer = session.renderState.baseLayer as XRWebGLLayer;<br>        const views = pose.views;<br><br>        // Bind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);<br>        <br>        // Reset<br>        gl.clearColor(0, 0, 0, 0); // RGBA values, fully transparent<br>        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);<br><br>        const scene = renderer.getScene() as GLScene; // Contains the virtual objects<br>        const shader = renderer.getShader() as Shader;<br><br>        shader.useShader(); // Use the shader program<br><br>        for(let i = 0; i &lt; views.length; i++) { // As this is AR, only one view<br>            const viewport = glLayer.getViewport(views[i]) as XRViewport;<br>            // Set the frambuffer viewport. This matches the camera display<br>            renderer.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height); <br>            const uniforms = renderer.getUniforms();<br>            renderer.useLights(scene, uniforms);<br><br>            const projectionMatrix = views[i].projectionMatrix;<br>            const viewMatrix = views[i].transform.inverse.matrix; // Inverse because view camera / the user should be at the origin<br>    <br>            gl.uniformMatrix4fv(uniforms.uniformProjection, false, projectionMatrix);<br>            gl.uniformMatrix4fv(uniforms.uniformView, false, viewMatrix);<br><br>            // REMAINING CODE GOES HERE<br>        }<br><br>        // Un assign the shader program<br>        gl.useProgram(null); <br>        // Unbind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, null);<br>    }<br>}</pre><p>We will use that matrices and bind them to the uniform locations accordingly.</p><p>And that is about it for using the XR values. The rest is about rendering our scene objects.</p><pre>function onDrawFrame(t: DOMHighResTimeStamp, frame: XRFrame) {<br>    // Get the current session and request the next frame<br>    const session = frame.session;<br>    session.requestAnimationFrame(onDrawFrame);<br>    <br>    // Get the viewer&#39;s pose<br>    const pose = frame.getViewerPose(unboundedRefSpace); // We need the world refernce space to do the rendering<br>    <br>    // Do the Rendering if the pose exists<br>    if(pose) {<br>        // Get the rendering layers and the views<br>        const glLayer = session.renderState.baseLayer as XRWebGLLayer;<br>        const views = pose.views;<br><br>        // Bind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);<br>        <br>        // Reset<br>        gl.clearColor(0, 0, 0, 0); // RGBA values, fully transparent<br>        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);<br><br>        const scene = renderer.getScene() as GLScene; // Contains the virtual objects<br>        const shader = renderer.getShader() as Shader;<br><br>        shader.useShader(); // Use the shader program<br><br>        for(let i = 0; i &lt; views.length; i++) { // As this is AR, only one view<br>            const viewport = glLayer.getViewport(views[i]) as XRViewport;<br>            // Set the frambuffer viewport. This matches the camera display<br>            renderer.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height); <br>            const uniforms = renderer.getUniforms();<br>            renderer.useLights(scene, uniforms);<br><br>            const projectionMatrix = views[i].projectionMatrix;<br>            const viewMatrix = views[i].transform.inverse.matrix; // Inverse because view camera / the user should be at the origin<br>    <br>            gl.uniformMatrix4fv(uniforms.uniformProjection, false, projectionMatrix);<br>            gl.uniformMatrix4fv(uniforms.uniformView, false, viewMatrix);<br><br>            const sceneObjects = scene.getSceneObjects();<br>            for(let i = 0; i &lt; sceneObjects.length; i++) {<br>                renderer.renderSceneObject(sceneObjects[i] as GLSceneObject, mat4.create(), uniforms.uniformModel as WebGLUniformLocation, <br>                uniforms.uniformModelInverse as WebGLUniformLocation, uniforms.uniformTexture as WebGLUniformLocation);<br>            }<br>        }<br><br>        // Un assign the shader program<br>        gl.useProgram(null); <br>        // Unbind the framebuffer<br>        gl.bindFramebuffer(gl.FRAMEBUFFER, null);<br>    }<br>}</pre><p>What we do is simply retrieve the objects in our scene and render them one by one. I won’t go into the details of the added for loop and the function it calls. It’s the logic I used to traverse all the scene objects and render them with the help of the uniform locations.</p><p>Alright, we have implemented all the necessary functions to create our first WebAR app.</p><h3>Load a 3D model and render it in the augmented world</h3><p>Even though we implemented the functions, we don’t know how to call them or what is the entry point of the app yet. So let’s create the main function.</p><pre>async function main() {<br>    await setupRenderer();<br><br>    // Load the model <br>    model = await renderer.loadModelData(&#39;models/yoshikage_kira/scene.gltf&#39;);<br><br>    // Create a virtual scene object and add to the scene<br>    const sceneObject = await renderer.createModelSceneObject(model, vec3.fromValues(0, 0, -2), vec3.fromValues(-90, 0, 0), vec3.fromValues(0.5, 0.5, 0.5));<br>    renderer.addSceneObjectToScene(sceneObject);<br><br>    // Add an event listener to the AR button<br>    const arButton = document.querySelector(&#39;#btn&#39;);<br>    arButton?.addEventListener(&#39;click&#39;, startARSession);<br>}</pre><p>The first task is to set up our renderer, so we call our user-defined setupRenderer() function. Then, using the renderer object, we load a GLTF model. I have placed the model in the project by creating a folder called models in the root directory and added the folder containing the .gltf file. This is the model I will be using, so credits to the owner.</p><p>Also, if you’re using a model without textures, make sure to create a folder called assets in the root directory. Then, create a folder called textures inside the assets folder and add a texture file (.png) named plain. This is because, in my renderer, if it cannot find a texture, it will use this plain texture instead.</p><p>After loading the model, we create a scene object using specified position, rotation, and scale. You can set these values however you’d like. But keep in mind that these values are the transformation values in the augmented world. For example, I use 0, 0, -2 for the position. When the WebAR app starts, we are at 0, 0, 0 (the origin). So, the scene object will be 2 units away from us in the direction of the z axis, meaning it will be in front of us.</p><p>Finally, we move the AR button event listener addition to this main function. As I mentioned previously, this is because we cannot automatically start the session without the user’s consent. If you try to call the startARSession function directly within the main function, it will throw an error. You are welcome to experiment with this.</p><p>Then all we have to do is call the main function.</p><pre>async function main() {<br>    await setupRenderer();<br><br>    // Load the model <br>    model = await renderer.loadModelData(&#39;models/yoshikage_kira/scene.gltf&#39;);<br><br>    // Create a virtual scene object and add to the scene<br>    const sceneObject = await renderer.createModelSceneObject(model, vec3.fromValues(0, 0, -2), vec3.fromValues(-90, 0, 0), vec3.fromValues(0.5, 0.5, 0.5));<br>    renderer.addSceneObjectToScene(sceneObject);<br><br>    // Add an event listener to the AR button<br>    const arButton = document.querySelector(&#39;#btn&#39;);<br>    arButton?.addEventListener(&#39;click&#39;, startARSession);<br>}<br><br>// Call the function<br>main();</pre><p>Now it’s time to run the web app. But before that, you need to set up the environment to run it. It’s best to connect your device to your development environment (laptop/PC) using USB debugging (I don’t know about iPhones, sorry). Then, you can use ADB reverse or Google Chrome’s port forwarding feature. I personally use the Chrome approach because I can see the console. I’m not sure whether it’s possible with reverse ADB. If it is, please let me know in the comments.</p><p>Otherwise, you can use the <a href="https://chromewebstore.google.com/detail/webxr-api-emulator/mjddjgeghkdijejnciaefnkjmkafnnje?hl=en">WebXR Emulator extension</a>. It’s not very easy to use, but it can give you an overall idea of how the WebAR app would work.</p><p>‘m not going to explain how to set up port forwarding in Chrome. You can follow <a href="https://developer.chrome.com/docs/devtools/remote-debugging/local-server">this tutorial</a> to get it working. Remember that we set port: 5500 in our Vite configuration file, meaning we run our app on this port. So make sure you forward that port.</p><p>Given that you have already set it up, you can run the following command to start the server.</p><pre>npm run dev</pre><p>If you go to the link in your device (it will most probably be http://localhost:5500), the website will display as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fd_-ezt9UVyvA71JO0IQRQ.png" /><figcaption>WebAR app with the Start AR button</figcaption></figure><p>All you have to do is press the button and the immersive AR session will start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*ZNMksopamLJOUwrtADoGIA.gif" /><figcaption>Immersive AR Session</figcaption></figure><p>And now I can say that I own a Kira Yoshikage figure (hope it counts).</p><p>You might notice that the virtual scene object may seem to change its position during the session. This is mostly because we are directly setting the position, instead of using a feature called anchors. We will see how we can add that later on.</p><p>But this is more than enough to understand the fundamentals of the WebXR Device API for building an immersive AR session with WebGL!</p><p>I hope my explanation is clear and easy to follow. If you have any issues related to the code, please check out <a href="https://github.com/Ramith-D-Rodrigo/Medium/tree/master/webar-intro">this link</a>. It is the GitHub repository where I pushed the code for this tutorial. For any other issues you have, feel free to comment below. I will try my best to help.</p><p>Thank you for following through until the end. I will try my best to add more articles related to WebAR implementation where we make use of the features provided by the API. Until we meet again, do your best!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70727865f8fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>