Giter Site home page Giter Site logo

webgl2samples's Introduction

WebGL Samples

A place to host and work on some WebGL sample applications. Feel free to contribute if you want.

Looking for the Google IO Samples? Google I/O 2011 WebGL Techniques and Performance Samples


Aquarium

By Greggman and Human Engines

You can also run the Aquarium synced across multiple machines. See here for more info.


Blob

By Henrik Rydg�rd


Caves

by Jasmine Kent Langridge


Collectibles

By Human Engines


Color Adjust

By Greggman


Dynamic Cubemap

By Greggman


Electricflower

By Henrik Rydg�rd


Field

By Greggman


Fishtank

By Greggman


Halo

By Kenneth Waters


Imagesphere

By Greggman


Lots-O-Images

By Greggman


Lots-O-Objects

By Greggman


Multiple Views

By Greggman


Persistence

By Greggman


Spacerocks

By Greggman


Sprites

By Ken Russell


Flexible Toon Shading

By Greggman


Book (Cloth Simulation Demo)

By Joshua Trask


Video Texture

By Greggman


ROYGBIV Electroshock

By Oguz Eroglu

webgl2samples's People

Contributors

kdashg avatar kenrussell avatar little-csd avatar mrdoob avatar pjcozzi avatar reon90 avatar shrekshao avatar spite avatar trungtle avatar tsherif avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webgl2samples's Issues

Layout qualifier location standard

From Christ ogl sample:
Might follow this later

namespace semantic
{
    namespace buffer
    {
        enum type
        {
            STATIC = 0,
            DYNAMIC = 1
        };
    };

    namespace uniform
    {
        enum type
        {
            MATERIAL = 0,
            TRANSFORM0 = 1,
            TRANSFORM1 = 2,
            INDIRECTION = 3,
            CONSTANT = 0,
            PER_FRAME = 1,
            PER_PASS = 2,
            LIGHT = 3
        };
    };

    namespace sampler
    {
        enum type
        {
            DIFFUSE     = 0,
            POSITION    = 4,
            TEXCOORD    = 5,
            COLOR       = 6
        };
    }//namespace sampler

    namespace image
    {
        enum type
        {
            DIFFUSE = 0,
            PICKING = 1
        };
    }//namesapce image

    namespace attr
    {
        enum type
        {
            POSITION = 0,
            NORMAL   = 1,
            COLOR    = 3,
            TEXCOORD = 4,
            DRAW_ID  = 5
        };
    }//namespace attr

    namespace vert
    {
        enum type
        {
            POSITION = 0,
            COLOR    = 3,
            TEXCOORD = 4,
            INSTANCE = 7
        };
    }//namespace vert

    namespace frag
    {
        enum type
        {
            COLOR   = 0,
            RED     = 0,
            GREEN   = 1,
            BLUE    = 2,
            ALPHA   = 0
        };
    }//namespace frag

    namespace renderbuffer
    {
        enum type
        {
            DEPTH,
            COLOR0
        };
    }//namespace renderbuffer

    namespace storage
    {
        enum type
        {
            VERTEX  = 0
        };
    }//namespace storage
}//namespace semantic

Question about reading pixel from fbo of texture 3d (or 2d array)

@kenrussell There's a question from the community. Since he is working on a gpgpu project for js ( gpu.js ), he would like to read pixels from a fbo with multiple render target, ideally with one call.
I searched the spec and made some experiments. It seems readpixels cannot read data compeletely from a MRT FBO. Tested on Chrome 58 Win10 with this sample, readpixels can only read data of the first layer. It won't generate warning if we set the width or height to 3 times, but the data read is zero for the second and third layer. Seems like the only workaround is to create a separate fbo for each of the three layer, and call readpixels from one by one.
I know the spec is not for gpgpu purpose. But is there a solution for him? (what does the pixel pack buffer do). Thanks!

TransformFeedback still has problems

In chrome canary, sometimes it fails to draw the rect out. No error message is produced. I am now trying to find out the problems by reading OpenGL ES 3.0

Use gl-matrix-min.js of version 2

Use gl-matrix-min.js 2.0. The gl-matrix.js in repo at present is version 1.x. Since there's a issue with the texture-3d sample using the new 2.0 gl-matrix, I will remain the old version gl-matrix there and come back later to fix that.

Notes for ETC2/EAC sample

  • etc2/eac compressed image can be in different file extension (ktx, pkm), each has a different "header data". For example, ktx file format has a header data of 68 bytes details.
  • To properly handle this, we may need a so-called "texture utils". Extract the data correctly from images in different format, which can be another project.
  • In this sample, I hard-coded an offset of 68 to drag the image data from the arraybuffer. Improvement can be made later.

Sample `texture_vertex` depth "dissolving"

In sample texture_vertex, when enabling DEPTH_TEST, part of the geometry is "dissolving" to darkness. When disabling DEPTH_TEST the geometry is complete. So it might be the issue within this sample html. Yet I can't find it. Some fresh eyes might be helpful.

Outreach Plan

Time most of this with the release of WebGL 2 or when it is easier to enable in browsers...

WebGL2 Browser experiment setup

The webgl-2 experiment setup goes like this (I've tested on Windows only) (tested on Windows and OSX 10.10.5).
The Mozilla Wiki WebGL2 Link seems to miss one config flag in my case. So I post my methods here FYI.

  • FireFox:
    set the following config flags value to true in about:config
    webgl.disable-angle
    webgl.enable-prototype-webgl2
    webgl.force-enabled

  • Chrome:
    launch chrome through command line with an additional flag

    .\chrome.exe --enable-unsafe-es3-apis

How to Get WebGL 2 implementation

OpenGL ES 3 Shading Language new built in function comparing to ES 2

  • Angle & Trigonometry Functions
    T sinh (T x); hyperbolic sine
    T cosh (T x); hyperbolic cosine
    T tanh (T x); hyperbolic tangent
    T asinh (T x); arc hyperbolic sine; inverse of sinh
    T acosh (T x); arc hyperbolic cosine; non-negative inverse of cosh
    T atanh (T x); arc hyperbolic tangent; inverse of tanh
  • Common Functions
    full integer/uint and integer/uint vector support
    TB isnan(T x); true if x is a NaN
    TB isinf(T x); true if x is positive or negative infinity
    TI floatBitsToInt(T value);
    TU floatBitsToUint(T value); highp integer, preserving float bit level representation
    T intBitsToFloat(TI value);
    T uintBitsToFloat(TU value);highp float, preserving integer bit level representation
  • Floating-Point Pack and Unpack Functions
    uint packSnorm2x16(vec2 v);
    uint packUnorm2x16(vec2 v); convert two floats to fixed point and pack into an integer
    vec2 unpackSnorm2x16(uint p);
    vec2 unpackUnorm2x16(uint p); unpack fixed point value pair into floats
    uint packHalf2x16(vec2 v); convert two floats into half-precision floats and pack into an integer
    vec2 unpackHalf2x16(uint v); unpack half value pair into full floats
  • Matrix Functions
    mat2 outerProduct(vec2 c, vec2 r);
    mat3 outerProduct(vec3 c, vec3 r);
    mat4 outerProduct(vec4 c, vec4 r); linear algebraic column vector * row vector
    mat2x3 outerProduct(vec3 c, vec2 r);
    mat3x2 outerProduct(vec2 c, vec3 r);
    mat2x4 outerProduct(vec4 c, vec2 r);
    mat4x2 outerProduct(vec2 c, vec4 r);
    mat3x4 outerProduct(vec4 c, vec3 r);
    mat4x3 outerProduct(vec3 c, vec4 r); linear algebraic column vector * row vector
    mat2 transpose(mat2 m);
    mat3 transpose(mat3 m);
    mat4 transpose(mat4 m);
    mat2x3 transpose(mat3x2 m);
    mat3x2 transpose(mat2x3 m);
    mat2x4 transpose(mat4x2 m);
    mat4x2 transpose(mat2x4 m);
    mat3x4 transpose(mat4x3 m);
    mat4x3 transpose(mat3x4 m); transpose of matrix m
    float determinant(mat2 m);
    float determinant(mat3 m);
    float determinant(mat4 m); determinant of matrix m
    mat2 inverse(mat2 m);
    mat3 inverse(mat3 m);
    mat4 inverse(mat4 m); inverse of matrix m
  • Fragment Processing Functions _texture_derivative_
    T dFdx(T p); Derivative in x
    T dFdy(T p); Derivative in y
    T fwidth(T p); abs (dFdx (p)) + abs (dFdy (p));
  • Texture Lookup Functions
    3D texture support, vertex/fragment shader support _texture_2d_array, _texture_3d
    textureOffset _texture_offset_
    texelFetch _texture_fetch_
    texelFetchOffset
    textureProjOffset
    textureGrad _texture_grad_
    textureProjGrad
    textureGradOffset
    textureProjGrad
    textureProjGradOffset

Add screenshot to README.md

To supplement the "WebGL 2 Samples Pack" link at the top of the README.md, add a choice screenshot of the examples that also links to the live version.

Let's do this before GDC (I added a GDC label).

Roadmap

OpenGL ES 3 Feature Lists

Texturing

  • sRGB textures and framebuffers: gamma-correction
  • 2D texture arrays: texture animation
  • 3D textures: 3D voxel data, medical imaging
  • Depth textures and shadow comparison: Shrek ❌ supported in webgl1
  • Seamless cubemaps: ❌ no need for a sample
  • Floating-point textures
  • ETC2/EAC texture compression : Shrek
  • Integer textures
  • Additional texture formats
  • Non-power-of-2 textures: ❌ no need for a sample, texture-2d-array is already using non-power of two texture
  • Texture level of detail (LOD) features
  • Texture swizzles: independent control of each RGBA channel: ❌ Not supported
  • Immutable textures: Trung
  • Increased minimum sizes : ❌ no need for a sample

Shaders

  • Program binaries: Trung ❌ Skipping this (http://blog.tojicode.com/2013/09/whats-coming-in-webgl-20.html)
  • Mandatory online compiler : Shrek ❔ no need for a sample?
  • Non-sqaure matrices: Trung ❔ no need for a sample? matCxR simply just use it in the shader?
  • Full integer support : Shrek : already has a texture_integer
  • Centroid sampling: Shrek
  • Flat/smooth interpolators: Shrek
  • Uniform blocks: Shrek : 💤 Pending Having trouble doing this one, also this fails the conformance test
  • Layout qualifers: ❌ no need for a sample: Trung
  • Instance and vertexID
  • Fragment depth: Trung : ❌ webgl 1 supported
  • New built-in functions : Shrek
  • Relaxed limitations: ❌ no need for a sample: Trung

Geometry

  • Transform feedback
  • Boolean occlusion queries : Shrek
  • Instanced rendering: Trung
  • Primitive restart : Shrek 💤Pending, the conformance test fail on this
  • New vertex formats: Trung

Buffer Objects

  • Uniform buffer objects : Shrek The same as Uniform blocks
  • Vertex array objects: Trung
  • Sampler objects : Shrek
  • Sync objects: Trung
  • Pixel buffer objects: asynchronous transfer of data : Shrek 💤Pending, the conformance test fail on this
  • Buffer subrange mapping: Not available on WebGL 2. Replaced by getBufferSubData. Trung
  • Buffer object to buffer object copies : Shrek

Framebuffer

  • Multiple render targets (MRTs)
  • Multisample renderbuffer : Shrek
  • Framebuffer invalidation hints : Trung
  • New blend equations : Shrek

Background

WebGL 2.0 Spec
SIGGRAPH Asia 2015

Feature set new in OpenGL ES 3.0:

  • Many sized texture formats (including integer and float textures), 3D textures, 2D texture arrays, immutable textures, more compressed texture formats
    • Full non-power-of-two texture support
  • Instanced drawing*
  • Multiple render targets*
  • Transform feedback
  • True integer vertex attributes
  • Multisampled renderbuffers
  • Shading language upgrades
    • texture level-of-detail sampling control (important for physically based rendering pipelines)
    • uniform blocks
    • in/out variables instead of “attribute”, etc.
    • control over layout in the shader
  • Seamless cubemaps
    • Important for physically based rendering pipelines; can finally use mipmap generation effectively
  • More GPU to GPU paths
    • Upload textures from pixel unpack buffers, read pixels into pixel pack buffers, copying between buffers
    • Transform feedback
    • When used in conjunction with 3D textures and 2D texture arrays, have much more computation ability than WebGL 1.0
  • Features for performance optimization:
    • Uniform buffers
    • Vertex array objects*
  • Convenience features:
    • Sampler objects
  • Query objects
  • Sync objects

Samples

Our current plan is to base of a subset of Christophe's OpenGL Samples Pack

Current planning google sheet in details. If you have comments and inputs, please add to this doc. Lots more to come!

Schedule and Task

  • Dec 14 Set up the framework for the samples
  • Dec 22 Test with first sample, figure out what ten samples to implement
  • Dec 31 Implement the first 10 samples
  • Jan 7 Implement samples labeled WIP in google sheet (8 in total)
  • Jan 12 Implement samples labeled WIP in google sheet (6 in total)
  • Jan 20 Implement samples according to OpenGL ES 3 feature list (4 in total), clean issues.
  • Jan 27 Implement samples according to OpenGL ES 3 feature list (4 in total), clean issues
  • Jan 31 code sprint, Implement samples according to OpenGL ES 3 feature list (4 in total), clean issues
  • Feb 7 Implement samples according to OpenGL ES 3 feature list (4 in total), clean issues
  • Feb 15 glsl-New built-in functions, New vertex formats, Finish WebGL 2 Sample Pack, start glTF work.

GLTF loader

Reposted @pjcozzi's comment to here:

For glTF support before GDC:

Reading and Tools

  • To test a glTF model, drag and drop it here
  • For an overview of glTF, see here
  • For the full details, the spec is a short read (ignoring the properties reference)
  • There are several JavaScript glTF, review the Cesium loader or others. Recall that the goal of our loader is to be as simple as possible and fully spec compliant so it can serve as a reference loader for everyone.

Implementation

  • Convert OBJs in this repo to glTF using OBJ2GLTF
  • Remove the third-party WebGL loader (remove the file and reference in the LICENSE.md)
  • Create a geometry-only glTF loader as a single.js file in the samples/third-party directory for now (we'll give it its own repo after GDC)
  • Do not worry about loading shaders/texture/techniques/materials, animations/skins, cameras, etc. Instead, focus on walking the node hierarchy and loading the geometry.
  • Research how well modern web browsers support data URIs. If support is still poor, use https://github.com/AnalyticalGraphicsInc/gltf-utilities

I dont know what any of these samples mean

I'm just not proficient enough about OpenGL to know what all this stuff is helping me with.
Can you add more explanations of where I would want to use these techniques, and how this improves on the old way of doing things and what that old way was?

[qu] draw_instanced.html question

Thanks, I'm trying to understand why do you need to call

    `gl.bindVertexArray(vertexArray);`

twice? I see that if you don't do the initial call you get a black screen.

Descriptions for each sample

From the name alone, it's not always clear what the output for a sample is supposed to be or even exactly what WebGL 2 feature the sample is demonstrating. Let's provide a short description (screenshot, tooltip, etc.) for each. We'll have to figure out the form factor.

draw image space example

In the draw image space example
in fragment shader:
color = texture(diffuse, vec2(gl_FragCoord.x,1.0 - gl_FragCoord.y) / u_imageSize);
shoule replace 1.0 by u_imageSize.y.
Am I right?

Code consistency improvements

  • Use v_ for GLSL varyings (some examples do, some don't)
  • Consistently always use a constant or a literal for layout locations, e.g., currently some examples use layout(location = 0) in vec2 position; and others us layout(location = POSITION) in vec2 position;.
  • Change
if(!isWebGL2)
{

to

if(!isWebGL2) {

sample: primitive-restart problem

  • primitive restart fails the conformance test
  • seems that it is the problem of TRIANGLES_STRIP. Even without the degenerate-triangle, the TRIANGLE_STRIP doesn't work
  • try to test TRIANGLES_STRIP in webgl 1 context

Transform feedback without rendering sample request

Hi!
Would be nice to have some super simple example of transform feedback with vertex shader like this:

#version 300 es
        precision highp float;
        precision highp int;

        flat out int vertexId;

        void main() {
          vertexId = gl_VertexID + 1;
        }

My (finally) working example:

interface GLShaderInfo {
  name?: string,
  src: string,
  type: number 
}

const createGLShader = (gl: WebGL2RenderingContext, shaderInfo: GLShaderInfo) => {
  const shader = gl.createShader(shaderInfo.type);
  if (shader) {
    const shaderSource = shaderInfo.src.trim();
    gl.shaderSource(shader, shaderSource);
    gl.compileShader(shader);
    const compileStatus = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (!compileStatus) {
      const error_message = gl.getShaderInfoLog(shader);
      throw "Could not compile shader \"" +
          shaderInfo.name +
          "\" \n" +
          error_message;
    }
  }
  return shader;
}
  

const createGLProgram = (
  gl: WebGL2RenderingContext, shaderInfos: GLShaderInfo[], transformFeedbackVaryings?: string[]
) => {
  const program = gl.createProgram();
  if (program) {
    for (let i = 0; i < shaderInfos.length; i++) {
      const shaderInfo = shaderInfos[i];
      const shader = createGLShader(gl, shaderInfo);
      if (shader) {
        gl.attachShader(program, shader);
      }
    }
  

    if (transformFeedbackVaryings != null) {
      gl.transformFeedbackVaryings(program,
        transformFeedbackVaryings,
        gl.INTERLEAVED_ATTRIBS);
    }
    gl.linkProgram(program);
    var link_status = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (!link_status) {
      var error_message = gl.getProgramInfoLog(program);
      throw "Could not link program.\n" + error_message;
    }
  }
  return program;
}


const createGL = (width?: number, height?: number, canvas = document.createElement("canvas")) => {
  if (width) canvas.width = width;
  if (height) canvas.height = height;
  return canvas.getContext("webgl2");
}


function main() {
  const gl = createGL()
  if (gl != null) {
    document.body.appendChild(<HTMLCanvasElement>gl.canvas);



    
    const vs = {
      type: gl.VERTEX_SHADER,
      src: `#version 300 es
        precision highp float;
        precision highp int;

        flat out int vertexId;

        void main() {
          vertexId = gl_VertexID + 1;
        }
        `
      }
    
    const fs = {
      type: gl.FRAGMENT_SHADER,
      src: `#version 300 es
      precision mediump float;
      
      out vec4 outColor;
      
      void main() {
        outColor = vec4(1, 0, 0, 1);
      }
      `
    }

    // setup GLSL program
    const program = createGLProgram(gl, [vs, fs], ['vertexId']);
    if (program) {
      const totalLoops = 20;      
      gl.useProgram(program);

      // https://open.gl/feedback

      const vertexArray = gl.createVertexArray();
      gl.bindVertexArray(vertexArray);

      const glTransformOutputBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, glTransformOutputBuffer);
      gl.bufferData(gl.ARRAY_BUFFER, totalLoops * 16, gl.STATIC_READ);
      
      gl.enable(gl.RASTERIZER_DISCARD); // don't use fragment shader

      gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, glTransformOutputBuffer);


      gl.bindBuffer(gl.ARRAY_BUFFER, null);


      gl.beginTransformFeedback(gl.POINTS);

      const offset = 0;
      gl.drawArrays(gl.POINTS, offset, totalLoops);

      gl.endTransformFeedback();
      gl.flush();

      const transformOutputBuffer = new Uint32Array(totalLoops);
      
      gl.getBufferSubData(gl.TRANSFORM_FEEDBACK_BUFFER, 0, transformOutputBuffer);

      console.log(transformOutputBuffer);
    }
  } else {
    document.write("WebGL2 is not supported by your browser");
  }
}
  

UBO issue

When I trying to implement UBO, things don't turn out quite as expected.

  • I think the browser support is no problem, since I got ubo working correctly in draw_instance_ubo
  • Yet with almost the same code (simply copying and delete one of the two ubo), in draw_range_arrays when I use the transform.MVP (identiy matrix), the polygons just go away, no error is reported.
  • My first UBO try can be found here buffer_uniform, which is a direct port from Christ's ogl sample and is quite complex comparing to the last two. There's an error 1282 (GL_INVALID_OPERATION) at the draw calls. Since this is more complex, I just paused this and let's focus the first two for debugging first and later turn to this one.

So I'd like to learn if there's some good way to test the ubo.

Use explicit VAO in all examples

WebGL 2 has a default Vertex Array Object that we are implicitly using in some of the examples.

I think it would be a better practice if we use an explicit VAO like the sampler_wrap example:

            var vertexArray = gl.createVertexArray();
            gl.bindVertexArray(vertexArray);

            gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
            gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
            gl.enableVertexAttribArray(positionLocation);
            gl.bindBuffer(gl.ARRAY_BUFFER, null);

            gl.bindBuffer(gl.ARRAY_BUFFER, textureBuffer);
            gl.vertexAttribPointer(texcoordLocation, 2, gl.FLOAT, false, 0, 0);
            gl.enableVertexAttribArray(texcoordLocation);
            gl.bindBuffer(gl.ARRAY_BUFFER, null);

            gl.bindVertexArray(null);

Then when rendering:

gl.bindVertexArray(vertexArray);
gl.drawArrays(/* ... */);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.