<commit_before><!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 <NAME>

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!-- 
    Original example by <NAME>: 
    https://github.com/tsherif/webgl2examples/blob/master/occlusion.html

    Occlusion culling algorithm based on: 
    https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter06.html
 -->
<html>
<head>
    <title>WebGL 2 Example: Occlusion Culling</title>
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css">
    <style>
        #occlusion-controls {
            position: absolute;
            bottom: 20px;
            right: 20px;
            color: white;
        }
    </style>
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Occlusion Culling
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/occlusion.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas>
    <div id="occlusion-controls">
        Spheres: <span id="num-spheres"></span><br>
        Culled spheres: <span id="num-invisible-spheres"></span><br>
        Enable occlusion culling: <input id="occlusion-toggle" type="checkbox" checked><br>
        Top-down HUD: <input id="hud-toggle" type="checkbox" checked> 
    </div>
    <script type="x-shader/vs" id="vertex-draw">
        #version 300 es

        layout(std140, column_major) uniform;
        
        layout(location=0) in vec4 position;
        layout(location=1) in vec2 uv;
        layout(location=2) in vec3 normal;
        
        uniform SceneUniforms {
            mat4 viewProj;
            vec4 eyePosition;
            vec4 lightPosition;
        };       
        
        uniform mat4 uModel;

        out  vec3 vPosition;
        out  vec2 vUV;
        out  vec3 vNormal;
        void main() {
            vec4 worldPosition = uModel * position;
            vPosition = worldPosition.xyz;
            vUV = uv;
            vNormal = (uModel * vec4(normal, 0.0)).xyz;
            gl_Position = viewProj * worldPosition;
        }
    </script>
    <script type="x-shader/vf" id="fragment-draw">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        uniform SceneUniforms {
            mat4 viewProj;
            vec4 eyePosition;
            vec4 lightPosition;
        };

        uniform sampler2D tex;
        
        in vec3 vPosition;
        in vec2 vUV;
        in vec3 vNormal;

        out vec4 fragColor;
        void main() {
            vec3 color = texture(tex, vUV).rgb;

            vec3 normal = normalize(vNormal);
            vec3 eyeVec = normalize(eyePosition.xyz - vPosition);
            vec3 incidentVec = normalize(vPosition - lightPosition.xyz);
            vec3 lightVec = -incidentVec;
            float diffuse = max(dot(lightVec, normal), 0.0);
            float highlight = pow(max(dot(eyeVec, reflect(incidentVec, normal)), 0.0), 100.0);
            float ambient = 0.1;
            fragColor = vec4(color * (diffuse + highlight + ambient), 1.0);
        }
    </script>
    <script type="x-shader/vs" id="vertex-boundingBox">
        #version 300 es

        layout(std140, column_major) uniform;
        
        layout(location=0) in vec4 position;
        
        uniform SceneUniforms {
            mat4 viewProj;
            vec4 eyePosition;
            vec4 lightPosition;
        };       
        
        uniform mat4 uModel;

        void main() {
            gl_Position = viewProj * uModel * position;
        }
    </script>
    <script type="x-shader/vf" id="fragment-boundingBox">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        out vec4 fragColor;

        void main() {
            fragColor = vec4(1.0, 1.0, 1.0, 1.0);
        }
    </script>
    <script type="x-shader/vs" id="vertex-hud">
        #version 300 es

        layout(location=0) in vec4 position;
        
        uniform mat4 uViewProj;
        uniform mat4 uModel;

        void main() {
            gl_Position = uViewProj * uModel * position;
        }
    </script>
    <script type="x-shader/vf" id="fragment-hud">
        #version 300 es
        precision highp float;

        out vec4 fragColor;

        void main() {
            fragColor = vec4(1.0, 0.0, 0.0, 0.2);
        }
    </script>
    <script type="text/javascript">
        utils.addTimerElement();

        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        var occlusionCullingEnabled = true;
        var showHUD = true;

        document.getElementById("occlusion-toggle").addEventListener("change", function() {
            occlusionCullingEnabled = this.checked;
        });

        document.getElementById("hud-toggle").addEventListener("change", function() {
            showHUD = this.checked;
        });

        var sphereCountElement = document.getElementById("num-spheres");
        var occludedSpheresElement = document.getElementById("num-invisible-spheres");

        var canvas = document.getElementById("gl-canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var app = PicoGL.createApp(canvas);

        var hudViewport = [
            0, 
            0,
            app.width / 5, 
            app.height / 5
        ];
        app.depthTest()
        .blendFunc(PicoGL.SRC_ALPHA, PicoGL.ONE_MINUS_SRC_ALPHA)
        .scissor(hudViewport[0], hudViewport[1], hudViewport[2], hudViewport[3]);

        var timer = app.createTimer();

        /////////////////////
        // SET UP PROGRAM
        /////////////////////

        var drawVsSource =  document.getElementById("vertex-draw").text.trim();
        var drawFsSource =  document.getElementById("fragment-draw").text.trim();
        var drawProgram = app.createProgram(drawVsSource, drawFsSource);


        var boundingBoxVSource =  document.getElementById("vertex-boundingBox").text.trim();
        var boundingBoxFSource =  document.getElementById("fragment-boundingBox").text.trim();
        var boundingBoxProgram = app.createProgram(boundingBoxVSource, boundingBoxFSource);
        

        var hudVSSource =  document.getElementById("vertex-hud").text.trim();
        var hudFSSoure =  document.getElementById("fragment-hud").text.trim();
        var hudProgram = app.createProgram(hudVSSource, hudFSSoure);

        /////////////////////
        // SET UP GEOMETRY 
        /////////////////////

        var positionBuffer, uvBuffer, normalBuffer, indices;

        // Sphere geometry
        var sphereData = utils.createSphere({ radius: 0.6 });

        var spherePositions = app.createVertexBuffer(PicoGL.FLOAT, 3, sphereData.positions);
        var sphereUVs = app.createVertexBuffer(PicoGL.FLOAT, 2, sphereData.uvs);
        var sphereNormals = app.createVertexBuffer(PicoGL.FLOAT, 3, sphereData.normals);
        var sphereIndices = app.createIndexBuffer(PicoGL.UNSIGNED_SHORT, 3, sphereData.indices);

        var sphereArray = app.createVertexArray()
        .vertexAttributeBuffer(0, spherePositions)
        .vertexAttributeBuffer(1, sphereUVs)
        .vertexAttributeBuffer(2, sphereNormals)
        .indexBuffer(sphereIndices)


        // Bounding box geometry
        var boundingBoxData = utils.computeBoundingBox(sphereData.positions, { buildGeometry: true });
        var boundingBoxPositions = app.createVertexBuffer(PicoGL.FLOAT, 3, boundingBoxData.geometry.positions);
        var boundingBoxArray = app.createVertexArray()
        .vertexAttributeBuffer(0, boundingBoxPositions);

        //////////////////////////
        // UNIFORM DATA
        //////////////////////////

        // Main camera
        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(0, 0, 5);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        // HUD
        var hudProjMatrix = mat4.create();
        mat4.perspective(hudProjMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);

        var hudViewMatrix = mat4.create();
        var hudEyePosition = vec3.fromValues(0, 5, 0);
        mat4.lookAt(hudViewMatrix, hudEyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 0, -1));

        var hudViewProjMatrix = mat4.create();
        mat4.multiply(hudViewProjMatrix, hudProjMatrix, hudViewMatrix);

        var lightPosition = vec3.fromValues(1, 1, 40);

        var modelMatrix = mat4.create();
        var rotateXMatrix = mat4.create();
        var rotateYMatrix = mat4.create();

        var sceneUniformBuffer = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, viewProjMatrix)
        .set(1, eyePosition)
        .set(2, lightPosition)
        .update();

        //////////////////////////
        // DEPTH SORT FUNCTION
        //////////////////////////

        var sortPositionA = vec4.create();
        var sortPositionB = vec4.create();
        var sortModelView = mat4.create();

        function depthSort(a, b) {
            vec4.set(sortPositionA, a.translate[0], a.translate[1], a.translate[2], 1.0);
            vec4.set(sortPositionB, b.translate[0], b.translate[1], b.translate[2], 1.0);

            mat4.mul(sortModelView, viewMatrix, a.modelMatrix);
            vec4.transformMat4(sortPositionA, sortPositionA, sortModelView);
            mat4.mul(sortModelView, viewMatrix, b.modelMatrix);
            vec4.transformMat4(sortPositionB, sortPositionB, sortModelView);
            
            return sortPositionB[2] - sortPositionA[2];
        }

        /////////////////
        // LOAD TEXTURE
        /////////////////

        var image = new Image();
        var firstFrame = true;
        var occludedSpheres = 0;

        image.onload = function() {
            var texture = app.createTexture2D(image, { flipY: true });
        
            // Object definitions
            var GRID_DIM = 6;
            var GRID_OFFSET = GRID_DIM / 2 - 0.5;
            var NUM_SPHERES = GRID_DIM * GRID_DIM;
            var spheres = new Array(NUM_SPHERES);

            for (var i = 0; i < NUM_SPHERES; ++i) {
                var x = Math.floor(i / GRID_DIM) - GRID_OFFSET;
                var z = i % GRID_DIM - GRID_OFFSET;

                spheres[i] = {
                    rotate: [0, 0, 0], // Will be used for global rotation
                    translate: [x, 0, z],
                    modelMatrix: mat4.create(),

                    vertexArray: sphereArray,
                    boundingBoxVertexArray: boundingBoxArray,

                    mainDrawCall: app.createDrawCall(drawProgram, sphereArray)
                        .uniformBlock("SceneUniforms", sceneUniformBuffer)
                        .texture("tex", texture),
                    boundingBoxDrawCall: app.createDrawCall(boundingBoxProgram, boundingBoxArray)
                        .uniformBlock("SceneUniforms", sceneUniformBuffer),
                    hudDrawCall: app.createDrawCall(hudProgram, sphereArray)
                        .uniform("uViewProj", hudViewProjMatrix),
                    query: app.createQuery(PicoGL.ANY_SAMPLES_PASSED_CONSERVATIVE),
                    occluded: false,

                };
                
                utils.xformMatrix(spheres[i].modelMatrix, spheres[i].translate);
            }

            sphereCountElement.innerHTML = spheres.length;

            var rotationMatrix = mat4.create();
            var sphere, boundingBox;
            var samplesPassed;
            
            var i;

            function draw() {
                occludedSpheres = 0;

                // Note: Sort based on previous frame's transformations
                if (occlusionCullingEnabled) {
                    spheres.sort(depthSort);
                }

                app.viewport(0, 0, app.width, app.height)
                .clearColor(0, 0, 0, 1)
                .depthTest()
                .colorMask(true, true, true, true)
                .depthMask(true)
                .clear();

                for (i = 0; i < NUM_SPHERES; ++i) {
                    sphere = spheres[i];
                    boundingBox = sphere.boundingBox;

                    // Update transforms
                    sphere.rotate[1] += 0.003;

                    utils.xformMatrix(sphere.modelMatrix, sphere.translate, null, sphere.scale);
                    mat4.fromYRotation(rotationMatrix, sphere.rotate[1]);
                    mat4.multiply(sphere.modelMatrix, rotationMatrix, sphere.modelMatrix);
                    
                    //////////////////
                    // OCCLUSION TEST
                    //////////////////
                    
                    if (occlusionCullingEnabled) {

                        // Check query results here (will be from previous frame or earlier)
                        if (sphere.query.ready()) {
                            sphere.occluded = sphere.query.result === 0;
                            if (sphere.occluded) {
                                occludedSpheres++;
                            }
                        }
    
                        // Query is initiated here by drawing the bounding box of the sphere
                        if (!sphere.query.active) {
                            app.colorMask(false, false, false, false)
                            .depthMask(false);

                            sphere.query.begin();
                            
                            sphere.boundingBoxDrawCall
                            .uniform("uModel", sphere.modelMatrix)
                            .draw();
                            
                            sphere.query.end();
                        }
                        
                    } else {
                        sphere.occluded = false;
                    }

                    
                    if (!sphere.occluded) {
                        app.colorMask(true, true, true, true)
                        .depthMask(true);

                        sphere.mainDrawCall
                        .uniform("uModel", sphere.modelMatrix)
                        .draw();
                    }
                }

                // Draw HUD (visualize occlusion results)
                if (showHUD) {
                    app.viewport(hudViewport[0], hudViewport[1], hudViewport[2], hudViewport[3])
                    .blend()
                    .noDepthTest()
                    .scissorTest()
                    .colorMask(true, true, true, true)
                    .depthMask(true)
                    .clearColor(0.3, 0.3, 0.3, 1)
                    .clear();

                    for (i = 0; i < NUM_SPHERES; ++i) {
                        sphere = spheres[i];
                        if (!sphere.occluded) {
                            sphere.hudDrawCall.uniform("uModel", sphere.modelMatrix).draw();
                        }
                    }

                    app.noBlend()
                    .noScissorTest();
                }

                occludedSpheresElement.innerHTML = occludedSpheres;

                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        }

        image.src = "img/khronos_webgl.png";

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>
<commit_msg>Update title<commit_after><!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 <NAME>

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<!-- 
    Original example by <NAME>: 
    https://github.com/tsherif/webgl2examples/blob/master/occlusion.html

    Occlusion culling algorithm based on: 
    https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter06.html
 -->
<html>
<head>
    <title>PicoGL.js Example: Occlusion Culling</title>
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css">
    <style>
        #occlusion-controls {
            position: absolute;
            bottom: 20px;
            right: 20px;
            color: white;
        }
    </style>
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Occlusion Culling
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/occlusion.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas>
    <div id="occlusion-controls">
        Spheres: <span id="num-spheres"></span><br>
        Culled spheres: <span id="num-invisible-spheres"></span><br>
        Enable occlusion culling: <input id="occlusion-toggle" type="checkbox" checked><br>
        Top-down HUD: <input id="hud-toggle" type="checkbox" checked> 
    </div>
    <script type="x-shader/vs" id="vertex-draw">
        #version 300 es

        layout(std140, column_major) uniform;
        
        layout(location=0) in vec4 position;
        layout(location=1) in vec2 uv;
        layout(location=2) in vec3 normal;
        
        uniform SceneUniforms {
            mat4 viewProj;
            vec4 eyePosition;
            vec4 lightPosition;
        };       
        
        uniform mat4 uModel;

        out  vec3 vPosition;
        out  vec2 vUV;
        out  vec3 vNormal;
        void main() {
            vec4 worldPosition = uModel * position;
            vPosition = worldPosition.xyz;
            vUV = uv;
            vNormal = (uModel * vec4(normal, 0.0)).xyz;
            gl_Position = viewProj * worldPosition;
        }
    </script>
    <script type="x-shader/vf" id="fragment-draw">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        uniform SceneUniforms {
            mat4 viewProj;
            vec4 eyePosition;
            vec4 lightPosition;
        };

        uniform sampler2D tex;
        
        in vec3 vPosition;
        in vec2 vUV;
        in vec3 vNormal;

        out vec4 fragColor;
        void main() {
            vec3 color = texture(tex, vUV).rgb;

            vec3 normal = normalize(vNormal);
            vec3 eyeVec = normalize(eyePosition.xyz - vPosition);
            vec3 incidentVec = normalize(vPosition - lightPosition.xyz);
            vec3 lightVec = -incidentVec;
            float diffuse = max(dot(lightVec, normal), 0.0);
            float highlight = pow(max(dot(eyeVec, reflect(incidentVec, normal)), 0.0), 100.0);
            float ambient = 0.1;
            fragColor = vec4(color * (diffuse + highlight + ambient), 1.0);
        }
    </script>
    <script type="x-shader/vs" id="vertex-boundingBox">
        #version 300 es

        layout(std140, column_major) uniform;
        
        layout(location=0) in vec4 position;
        
        uniform SceneUniforms {
            mat4 viewProj;
            vec4 eyePosition;
            vec4 lightPosition;
        };       
        
        uniform mat4 uModel;

        void main() {
            gl_Position = viewProj * uModel * position;
        }
    </script>
    <script type="x-shader/vf" id="fragment-boundingBox">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;

        out vec4 fragColor;

        void main() {
            fragColor = vec4(1.0, 1.0, 1.0, 1.0);
        }
    </script>
    <script type="x-shader/vs" id="vertex-hud">
        #version 300 es

        layout(location=0) in vec4 position;
        
        uniform mat4 uViewProj;
        uniform mat4 uModel;

        void main() {
            gl_Position = uViewProj * uModel * position;
        }
    </script>
    <script type="x-shader/vf" id="fragment-hud">
        #version 300 es
        precision highp float;

        out vec4 fragColor;

        void main() {
            fragColor = vec4(1.0, 0.0, 0.0, 0.2);
        }
    </script>
    <script type="text/javascript">
        utils.addTimerElement();

        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        var occlusionCullingEnabled = true;
        var showHUD = true;

        document.getElementById("occlusion-toggle").addEventListener("change", function() {
            occlusionCullingEnabled = this.checked;
        });

        document.getElementById("hud-toggle").addEventListener("change", function() {
            showHUD = this.checked;
        });

        var sphereCountElement = document.getElementById("num-spheres");
        var occludedSpheresElement = document.getElementById("num-invisible-spheres");

        var canvas = document.getElementById("gl-canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var app = PicoGL.createApp(canvas);

        var hudViewport = [
            0, 
            0,
            app.width / 5, 
            app.height / 5
        ];
        app.depthTest()
        .blendFunc(PicoGL.SRC_ALPHA, PicoGL.ONE_MINUS_SRC_ALPHA)
        .scissor(hudViewport[0], hudViewport[1], hudViewport[2], hudViewport[3]);

        var timer = app.createTimer();

        /////////////////////
        // SET UP PROGRAM
        /////////////////////

        var drawVsSource =  document.getElementById("vertex-draw").text.trim();
        var drawFsSource =  document.getElementById("fragment-draw").text.trim();
        var drawProgram = app.createProgram(drawVsSource, drawFsSource);


        var boundingBoxVSource =  document.getElementById("vertex-boundingBox").text.trim();
        var boundingBoxFSource =  document.getElementById("fragment-boundingBox").text.trim();
        var boundingBoxProgram = app.createProgram(boundingBoxVSource, boundingBoxFSource);
        

        var hudVSSource =  document.getElementById("vertex-hud").text.trim();
        var hudFSSoure =  document.getElementById("fragment-hud").text.trim();
        var hudProgram = app.createProgram(hudVSSource, hudFSSoure);

        /////////////////////
        // SET UP GEOMETRY 
        /////////////////////

        var positionBuffer, uvBuffer, normalBuffer, indices;

        // Sphere geometry
        var sphereData = utils.createSphere({ radius: 0.6 });

        var spherePositions = app.createVertexBuffer(PicoGL.FLOAT, 3, sphereData.positions);
        var sphereUVs = app.createVertexBuffer(PicoGL.FLOAT, 2, sphereData.uvs);
        var sphereNormals = app.createVertexBuffer(PicoGL.FLOAT, 3, sphereData.normals);
        var sphereIndices = app.createIndexBuffer(PicoGL.UNSIGNED_SHORT, 3, sphereData.indices);

        var sphereArray = app.createVertexArray()
        .vertexAttributeBuffer(0, spherePositions)
        .vertexAttributeBuffer(1, sphereUVs)
        .vertexAttributeBuffer(2, sphereNormals)
        .indexBuffer(sphereIndices)


        // Bounding box geometry
        var boundingBoxData = utils.computeBoundingBox(sphereData.positions, { buildGeometry: true });
        var boundingBoxPositions = app.createVertexBuffer(PicoGL.FLOAT, 3, boundingBoxData.geometry.positions);
        var boundingBoxArray = app.createVertexArray()
        .vertexAttributeBuffer(0, boundingBoxPositions);

        //////////////////////////
        // UNIFORM DATA
        //////////////////////////

        // Main camera
        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(0, 0, 5);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        // HUD
        var hudProjMatrix = mat4.create();
        mat4.perspective(hudProjMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);

        var hudViewMatrix = mat4.create();
        var hudEyePosition = vec3.fromValues(0, 5, 0);
        mat4.lookAt(hudViewMatrix, hudEyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 0, -1));

        var hudViewProjMatrix = mat4.create();
        mat4.multiply(hudViewProjMatrix, hudProjMatrix, hudViewMatrix);

        var lightPosition = vec3.fromValues(1, 1, 40);

        var modelMatrix = mat4.create();
        var rotateXMatrix = mat4.create();
        var rotateYMatrix = mat4.create();

        var sceneUniformBuffer = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, viewProjMatrix)
        .set(1, eyePosition)
        .set(2, lightPosition)
        .update();

        //////////////////////////
        // DEPTH SORT FUNCTION
        //////////////////////////

        var sortPositionA = vec4.create();
        var sortPositionB = vec4.create();
        var sortModelView = mat4.create();

        function depthSort(a, b) {
            vec4.set(sortPositionA, a.translate[0], a.translate[1], a.translate[2], 1.0);
            vec4.set(sortPositionB, b.translate[0], b.translate[1], b.translate[2], 1.0);

            mat4.mul(sortModelView, viewMatrix, a.modelMatrix);
            vec4.transformMat4(sortPositionA, sortPositionA, sortModelView);
            mat4.mul(sortModelView, viewMatrix, b.modelMatrix);
            vec4.transformMat4(sortPositionB, sortPositionB, sortModelView);
            
            return sortPositionB[2] - sortPositionA[2];
        }

        /////////////////
        // LOAD TEXTURE
        /////////////////

        var image = new Image();
        var firstFrame = true;
        var occludedSpheres = 0;

        image.onload = function() {
            var texture = app.createTexture2D(image, { flipY: true });
        
            // Object definitions
            var GRID_DIM = 6;
            var GRID_OFFSET = GRID_DIM / 2 - 0.5;
            var NUM_SPHERES = GRID_DIM * GRID_DIM;
            var spheres = new Array(NUM_SPHERES);

            for (var i = 0; i < NUM_SPHERES; ++i) {
                var x = Math.floor(i / GRID_DIM) - GRID_OFFSET;
                var z = i % GRID_DIM - GRID_OFFSET;

                spheres[i] = {
                    rotate: [0, 0, 0], // Will be used for global rotation
                    translate: [x, 0, z],
                    modelMatrix: mat4.create(),

                    vertexArray: sphereArray,
                    boundingBoxVertexArray: boundingBoxArray,

                    mainDrawCall: app.createDrawCall(drawProgram, sphereArray)
                        .uniformBlock("SceneUniforms", sceneUniformBuffer)
                        .texture("tex", texture),
                    boundingBoxDrawCall: app.createDrawCall(boundingBoxProgram, boundingBoxArray)
                        .uniformBlock("SceneUniforms", sceneUniformBuffer),
                    hudDrawCall: app.createDrawCall(hudProgram, sphereArray)
                        .uniform("uViewProj", hudViewProjMatrix),
                    query: app.createQuery(PicoGL.ANY_SAMPLES_PASSED_CONSERVATIVE),
                    occluded: false,

                };
                
                utils.xformMatrix(spheres[i].modelMatrix, spheres[i].translate);
            }

            sphereCountElement.innerHTML = spheres.length;

            var rotationMatrix = mat4.create();
            var sphere, boundingBox;
            var samplesPassed;
            
            var i;

            function draw() {
                occludedSpheres = 0;

                // Note: Sort based on previous frame's transformations
                if (occlusionCullingEnabled) {
                    spheres.sort(depthSort);
                }

                app.viewport(0, 0, app.width, app.height)
                .clearColor(0, 0, 0, 1)
                .depthTest()
                .colorMask(true, true, true, true)
                .depthMask(true)
                .clear();

                for (i = 0; i < NUM_SPHERES; ++i) {
                    sphere = spheres[i];
                    boundingBox = sphere.boundingBox;

                    // Update transforms
                    sphere.rotate[1] += 0.003;

                    utils.xformMatrix(sphere.modelMatrix, sphere.translate, null, sphere.scale);
                    mat4.fromYRotation(rotationMatrix, sphere.rotate[1]);
                    mat4.multiply(sphere.modelMatrix, rotationMatrix, sphere.modelMatrix);
                    
                    //////////////////
                    // OCCLUSION TEST
                    //////////////////
                    
                    if (occlusionCullingEnabled) {

                        // Check query results here (will be from previous frame or earlier)
                        if (sphere.query.ready()) {
                            sphere.occluded = sphere.query.result === 0;
                            if (sphere.occluded) {
                                occludedSpheres++;
                            }
                        }
    
                        // Query is initiated here by drawing the bounding box of the sphere
                        if (!sphere.query.active) {
                            app.colorMask(false, false, false, false)
                            .depthMask(false);

                            sphere.query.begin();
                            
                            sphere.boundingBoxDrawCall
                            .uniform("uModel", sphere.modelMatrix)
                            .draw();
                            
                            sphere.query.end();
                        }
                        
                    } else {
                        sphere.occluded = false;
                    }

                    
                    if (!sphere.occluded) {
                        app.colorMask(true, true, true, true)
                        .depthMask(true);

                        sphere.mainDrawCall
                        .uniform("uModel", sphere.modelMatrix)
                        .draw();
                    }
                }

                // Draw HUD (visualize occlusion results)
                if (showHUD) {
                    app.viewport(hudViewport[0], hudViewport[1], hudViewport[2], hudViewport[3])
                    .blend()
                    .noDepthTest()
                    .scissorTest()
                    .colorMask(true, true, true, true)
                    .depthMask(true)
                    .clearColor(0.3, 0.3, 0.3, 1)
                    .clear();

                    for (i = 0; i < NUM_SPHERES; ++i) {
                        sphere = spheres[i];
                        if (!sphere.occluded) {
                            sphere.hudDrawCall.uniform("uModel", sphere.modelMatrix).draw();
                        }
                    }

                    app.noBlend()
                    .noScissorTest();
                }

                occludedSpheresElement.innerHTML = occludedSpheres;

                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
            
        }

        image.src = "img/khronos_webgl.png";

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>

{'fraction_non_alphanumeric': 0.11469297616657584, 'fraction_numerical': 0.02366134166977371, 'mean_word_length': 1.6686055410990357, 'pattern_counts': {'":': 0, '<': 129, '<?xml version=': 0, '>': 123, 'https://': 12, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5594701', 'n_tokens_mistral': 10353, 'n_tokens_neox': 9407, 'n_words': 2146}