WebGL 1.0 API Quick Reference Card Page 1

WebGL® is a sofware interface for accessing graphics hardware The WebGL Context and getContext() [2.5] from within a . Based on OpenGL ES 2.0, WebGL allows a to specify the objects and operatons involved in producing This object manages OpenGL state For example: high-quality graphical images, specifcally color images of 3D objects. and renders to a drawing bufer, which must is also be created at the • [n.n.n] refers to sectons in the WebGL 1.0 specifcaton, available at same tme of as the context creaton. www.khronos.org/webgl Create the WebGLRenderingContext unless otherwise noted. is also created by getContext.

Interfaces WebGLObject [5.3] WebGLRenderingContext [5.13] Interfaces are optonal requests and may be ignored by an This is the parent interface for all WebGL resource objects. This is the prinicpal interface in WebGL. The functons listed on implementaton. See getContextAtributes for actual values. Resource interface objects: this reference card are available within this interface. Atributes: WebGLContextAtributes [5.2] WebGLBufer [5.4] OpenGL Bufer Object. This interface contains requested drawing surface atributes WebGLProgram [5.6] OpenGL Program Object. canvas Type: HTMLCanvasElement and is passed as the second parameter to getContext. WebGLRenderbufer [5.7] OpenGL Renderbufer Object. A reference to the which created this context. Atributes: WebGLShader [5.8] OpenGL Object. drawingBuferWidth Type: GLsizei alpha Default: true WebGLTexture [5.9] OpenGL Texture Object. The actual width of the drawing bufer, which may difer from the If true, requests a drawing bufer with an alpha channel for the width atribute of the HTMLCanvasElement if the implementaton is WebGLUniformLocaton [5.10] Locaton of a uniform variable in a purposes of performing OpenGL destnaton alpha operatons unable to satsfy the requested width or height. shader program. and compositng with the page. drawingBuferHeight Type: GLsizei WebGLActveInfo [5.11] Informaton returned from calls to depth Default: true getActveAtrib and getActveUniform. The actual height of the drawing bufer, which may difer from the If true, requests drawing bufer with a depth bufer of at least Has the following read-only height atribute of the HTMLCanvasElement if the implementaton is 16 bits. propertes: name, size, type. unable to satsfy the requested width or height stencil Default: false If true, requests a stencil bufer of at least 8 bits. antalias Default: true [5.12] ViewType(ArrayBufer bufer, [optonal] ulong byteOfset, If true, requests drawing bufer with antaliasing using its choice ArrayBufer and Typed Arrays [optonal] ulong length) of technique (multsample/supersample) and quality. Data is transferred to WebGL using ArrayBufer and views. Bufers represent unstructured binary data, which can be Create a new view of given bufer, startng at optonal byte premultpliedAlpha Default: true modifed using one or more typed array views. ofset, extending for optonal length elements. If true, requests drawing bufer which contains colors with ArrayBufer bufer: Read-only, bufer backing this view premultplied alpha. (Ignored if Alpha is false.) Bufers ulong byteOfset: Read-only, byte ofset of view start in bufer preserveDrawingBufer Default: false ArrayBufer(ulong byteLength) ulong length: Read-only, number of elements in this view If true, requests that contents of the drawing bufer remain in ulong byteLength: read-only, length of view in bytes. Other Propertes between frames, at potental performance cost. Creates a new bufer. To modify the data, create one or more ulong byteLength: Read-only, length of view in bytes. views referencing it. const ulong BYTES_PER_ELEMENT: element size in bytes. Views Methods Per-Fragment Operatons [5.13.3] In the following, ViewType may be Int8Array, Int16Array, void blendColor(foat red, foat green, foat blue, foat alpha) Int32Array, Uint8Array, Uint16Array, Uint32Array, Float32Array. view[i] = get/set element i void blendEquaton(enum mode) ViewType(ulong length) set(ViewType other, [optonal] ulong ofset) mode: See modeRGB for blendEquatonSeparate Creates a view and a new underlying bufer. set(type[] other, [optonal] ulong ofset) void blendEquatonSeparate(enum modeRGB, ulong length: Read-only, number of elements in this view. Replace elements in this view with those from other, startng enum modeAlpha) ViewType(ViewType other) at optonal ofset. modeRGB, and modeAlpha: FUNC_ADD, FUNC_SUBTRACT, FUNC_REVERSE_SUBTRACT Creates new underlying bufer and copies ‘other’ array. ViewType subset(long begin, [optonal] long end) void blendFunc(enum sfactor, enum dfactor) ViewType(type[] other) Return a subset of this view, referencing the same underlying sfactor: Same as for dfactor, plus SRC_ALPHA_SATURATE Creates new underlying bufer and copies ‘other’ array. bufer. dfactor: ZERO, ONE, [ONE_MINUS_]SRC_COLOR, [ONE_MINUS_]DST_COLOR, [ONE_MINUS_]SRC_ALPHA, [ONE_MINUS_]DST_ALPHA, [ONE_MINUS_]CONSTANT_COLOR, [ONE_MINUS_]CONSTANT_ALPHA Whole Framebufer Operatons [5.13.3] void clearStencil(int s) Note: Src and dst factors may not both reference constant color void clear(ulong mask) [5.13.11] void colorMask(bool red, bool green, bool blue, bool alpha) void blendFuncSeparate(enum srcRGB, enum dstRGB, mask: Bitwise OR of {COLOR, DEPTH, STENCIL}_BUFFER_BIT void depthMask(bool fag) enum srcAlpha, enum dstAlpha) srcRGB, srcAlpha: See sfactor for blendFunc void clearColor(foat red, foat green, foat blue, foat alpha) void stencilMask(uint mask) dstRGB, dstAlpha: See dfactor for blendFunc void clearDepth(foat depth) void stencilMaskSeparate(enum face, uint mask) Note: Src and dst factors may not both reference constant color depth: Clamped to the range 0 to 1. face: FRONT, BACK, FRONT_AND_BACK void depthFunc(enum func) func: NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, NOTEQUAL [5.13.5] void buferSubData(enum target, long ofset, Object data) void sampleCoverage(foat value, bool invert) Bufer Objects target: ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER Once bound, bufers may not be rebound with a diferent Target. void stencilFunc(enum func, int ref, uint mask) void bindBufer(enum target, Object bufer) Object createBufer() func: NEVER, ALWAYS, LESS, LEQUAL, [NOT]EQUAL, GREATER, Note: Corresponding OpenGL ES functon is GenBufers GEQUAL target: ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER void stencilFuncSeparate(enum face, enum func, int ref, void buferData(enum target, long size, enum usage) void deleteBufer(Object bufer) uint mask) target: ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER any getBuferParameter(enum target, enum pname) face: FRONT, BACK, FRONT_AND_BACK usage: STATIC_DRAW, STREAM_DRAW, DYNAMIC_DRAW target: ARRAY_BUFFER, ELEMENT_ ARRAY_BUFFER func: NEVER, ALWAYS, LESS, LEQUAL, [NOT]EQUAL, GREATER, pname: BUFFER_SIZE, BUFFER_USAGE GEQUAL void buferData(enum target, Object data, enum usage) target and usage: Same as for buferData above bool isBufer(Object bufer) void stencilOp(enum fail, enum zfail, enum zpass) fail, zfail, and zpass: KEEP, ZERO, REPLACE, INCR, DECR, INVERT, INCR_WRAP, DECR_WRAP [5.13.3 - 5.13.4] [5.13.3] void frontFace(enum mode) void stencilOpSeparate(enum face, enum fail, enum zfail, View and Clip Rasterizaton mode: CCW, CW enum zpass) The viewport specifes the afne transformaton of x void cullFace(enum mode) face: FRONT, BACK, FRONT_AND_BACK and y from normalized device coordinates to window mode: BACK, FRONT_AND_BACK, void lineWidth(foat width) fail, zfail, and zpass: See fail, zfail, and zpass for stencilOp coordinates. Drawing bufer size is determined by the FRONT void polygonOfset(foat factor, HTMLCanvasElement. foat units) void depthRange(foat zNear, foat zFar) Detect and Enable Extensions [5.13.14] zNear: Clamped to the range 0 to 1 Must be <= zFar zFar: Clamped to the range 0 to 1. string[ ] getSupportedExtensions() void scissor(int x, int y, long width, long height) Detect context lost events [5.13.13] object getExtension(string name) void viewport(int x, int y, long width, long height) bool isContextLost()

©2011 - Rev. 0618 www.khronos.org/webgl WebGL 1.0 API Quick Reference Card - Page 2 Page 2

Programs and [5.13.9] Texture Objects [5.13.8] Special Functons [5.13.3] Rendering with OpenGL ES 2.0 requires the use of shaders. Texture objects provide storage and state for texturing contextStruct getContextAtributes() [5.13.2] Shaders must be loaded with a source string (shaderSource), operatons. WebGL adds an error for operatons relatng to the compiled (compileShader), and atached to a program currently bound texture if no texture is bound. void disable(enum cap) (atachShader) which must be linked (linkProgram) and then cap: BLEND, CULL_FACE, DEPTH_TEST, DITHER, used (useProgram). void actveTexture(enum texture) [5.13.3] POLYGON_OFFSET_FILL, SAMPLE_ALPHA_TO_COVERAGE, texture: [TEXTURE0..TEXTUREi] where i = SAMPLE_COVERAGE, SCISSOR_TEST, STENCIL_TEST void atachShader(Object program, Object shader) MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1 void enable(enum cap) void bindAtribLocaton(Object program, uint index, void bindTexture(enum target, Object texture) cap: See cap for disable string name) target: TEXTURE_2D, TEXTURE_CUBE_MAP void fnish() [5.13.11] void compileShader(Object shader) void copyTexImage2D(enum target, int level, enum internalformat, int x, int y, long width, void fush() [5.13.11] Object createProgram() long height, int border) enum getError() Object createShader(enum type) target: TEXTURE_2D, TEXTURE_CUBE_MAP_POSITIVE_{X,Y,Z} Returns: OUT_OF_MEMORY, INVALID_{ENUM, OPERATION, type: VERTEX_SHADER, FRAGMENT_SHADER TEXTURE_CUBE_MAP_NEGATIVE_{X,Y,Z} FRAMEBUFFER_OPERATION, VALUE}, NO_ERROR, internalformat: ALPHA, LUMINANCE, LUMINANCE_ALPHA, RGB[A] void deleteProgram(Object program) CONTEXT_LOST_WEBGL void copyTexSubImage2D(enum target, int level, any getParameter(enum pname) void deleteShader(Object shader) int xofset, int yofset, int x, int y, long width, pname: {ALPHA, RED, GREEN, BLUE, SUBPIXEL}_BITS, void detachShader(Object program, Object shader) long height) ACTIVE_TEXTURE, ALIASED_{LINE_WIDTH, POINT_SIZE}_RANGE, target: See target for copyTexImage2D ARRAY_BUFFER_BINDING, BLEND_DST_{ALPHA, RGB}, Object[ ] getAtachedShaders(Object program) BLEND_EQUATION_{ALPHA, RGB}, BLEND_SRC_{ALPHA, RGB}, Object createTexture() BLEND[_COLOR], COLOR_{CLEAR_VALUE, WRITEMASK}, any getProgramParameter(Object program, enum pname) Note: Corresponding OpenGL ES functon is GenTextures [NUM_]COMPRESSED_TEXTURE_FORMATS, CULL_FACE[_MODE], Note: Corresponding OpenGL ES functon is GetProgramiv void deleteTexture(Object texture) CURRENT_PROGRAM, DEPTH_{BITS, CLEAR_VALUE, FUNC, pname: DELETE_STATUS, LINK_STATUS, VALIDATE_STATUS, RANGE, TEST, WRITEMASK}, ELEMENT_ARRAY_BUFFER_BINDING, ATTACHED_SHADERS, ACTIVE_{ATTRIBUTES, UNIFORMS} void generateMipmap(enum target) DITHER, FRAMEBUFFER_BINDING, FRONT_FACE, target: TEXTURE_2D, TEXTURE_CUBE_MAP GENERATE_MIPMAP_HINT, LINE_WIDTH, string getProgramInfoLog(Object program) MAX_[COMBINED_]TEXTURE_IMAGE_UNITS, any getTexParameter(enum target, enum pname) any getShaderParameter(Object shader, enum pname) MAX_{CUBE_MAP_TEXTURE, RENDERBUFFER, TEXTURE}_SIZE, target: TEXTURE_2D, TEXTURE_CUBE_MAP MAX_VARYING_VECTORS, MAX_VERTEX_{ATTRIBS, Note: Corresponding OpenGL ES functon is GetShaderiv pname: TEXTURE_WRAP_{S, T}, TEXTURE_{MIN, MAG}_FILTER TEXTURE_IMAGE_UNITS, UNIFORM_VECTORS}, pname: SHADER_TYPE, DELETE_STATUS, COMPILE_STATUS bool isTexture(Object texture) MAX_VIEWPORT_DIMS, PACK_ALIGNMENT, string getShaderInfoLog(Object shader) POLYGON_OFFSET_{FACTOR, FILL, UNITS}, void texImage2D(enum target, int level, RENDERBUFFER_BINDING, RENDERER, SAMPLE_BUFFERS, string getShaderSource(Object shader) enum internalformat, long width, long height, SAMPLE_COVERAGE_{INVERT, VALUE}, SAMPLES, bool isProgram(Object program) int border, enum format, enum type, Object pixels) SCISSOR_{BOX, TEST}, SHADING_LANGUAGE_VERSION, STENCIL_{BITS, CLEAR_VALUE, TEST}, STENCIL_[BACK_]{FAIL, bool isShader(Object shader) void texImage2D(enum target, int level, enum internalformat, enum format, enum type, FUNC, REF,VALUE_MASK, WRITEMASK}, void linkProgram(Object program) STENCIL_[BACK_]PASS_DEPTH_{FAIL, PASS}, Object object) TEXTURE_BINDING_{2D, CUBE_MAP}, UNPACK_ALIGNMENT, void shaderSource(Object shader, string source) Note: The following values apply to all variatons of texImage2D. UNPACK_{COLORSPACE_CONVERSION_WEBGL, FLIP_Y_WEBGL, void useProgram(Object program) target: See target for copyTexImage2D PREMULTIPLY_ALPHA_WEBGL}, VENDOR, VERSION, VIEWPORT void validateProgram(Object program) internalformat: See internalformat for copyTexImage2D void hint(enum target, enum mode) format: ALPHA, RGB, RGBA, LUMINANCE, LUMINANCE_ALPHA target: GENERATE_MIPMAP_HINT type: UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, hint: FASTEST, NICEST, DONT_CARE UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_5_5_5_1 [5.13.10] object: pixels of type ImageData, image of type HTMLImageElement, bool isEnabled(enum cap) Uniforms and Atributes cap: cap: See cap for disable Values used by the shaders are passed in as uniform of vertex canvas of type HTMLCanvasElement, atributes. video of type HTMLVideoElement void pixelStorei(enum pname, int param) pname: UNPACK_ALIGNMENT, PACK_ALIGNMENT, void disableVertexAtribArray(uint index) void texParameterf(enum target, enum pname, foat param) UNPACK_{FLIP_Y_WEBGL, PREMULTIPLY_ALPHA_WEBGL}, index: [0, MAX_VERTEX_ATTRIBS - 1] target: TEXTURE_2D, TEXTURE_CUBE_MAP UNPACK_COLORSPACE_CONVERSION_WEBGL pname: TEXTURE_WRAP_{S, T}, TEXTURE_{MIN, MAG}_FILTER void enableVertexAtribArray(uint index) index: [0, MAX_VERTEX_ATTRIBS - 1] void texParameteri(enum target, enum pname, int param) target: TEXTURE_2D, TEXTURE_CUBE_MAP Object getActveAtrib(Object program, uint index) pname: TEXTURE_WRAP_{S, T}, TEXTURE_{MIN, MAG}_FILTER Renderbufer Objects [5.13.7] Renderbufer objects are used to provide storage for the Object getActveUniform(Object program, uint index) void texSubImage2D(enum target, int level, int xofset, individual bufers used in a framebufer object. int yofset, long width, long height, enum format, ulong getAtribLocaton(Object program, string name) enum type, Object pixels) void bindRenderbufer(enum target, Object renderbufer) target: RENDERBUFFER any getUniform(Object program, uint locaton) void texSubImage2D(enum target, int level, int xofset, int yofset, enum format, enum type, Object object) Object createRenderbufer() uint getUniformLocaton(Object program, string name) Note: Following values apply to all variatons of Note: Corresponding OpenGL ES functon is GenRenderbufers any getVertexAtrib(uint index, enum pname) texSubImage2D. void deleteRenderbufer(Object renderbufer) pname: CURRENT_VERTEX_ATTRIB , VERTEX_ATTRIB_ARRAY_ target: TEXTURE_CUBE_MAP_POSITIVE_{X, Y, Z}, {BUFFER_BINDING, ENABLED, SIZE, STRIDE, TYPE, NORMALIZED} TEXTURE_CUBE_MAP_NEGATIVE_{X, Y, Z} any getRenderbuferParameter(enum target, enum pname) long getVertexAtribOfset(uint index, enum pname) format and type: See format and type for texImage2D target: RENDERBUFFER object: Same as for texImage2D Note: Corres. OpenGL ES functon is GetVertexAtribPointerv pname: RENDERBUFFER_{WIDTH,HEIGHT,INTERNAL_FORMAT}, pname: VERTEX_ATTRIB_ARRAY_POINTER RENDEDRBUFFER_{RED,GREEN,BLUE,ALPHA,DEPTH,STENCIL}_SIZE bool isRenderbufer(Object renderbufer) void uniform[1234][f](uint locaton, ...) void renderbuferStorage(enum target, void uniform[1234][f]v(uint locaton, Array value) Writng to the Draw Bufer [5.13.11] enum internalformat, long width, long height) void uniformMatrix[234]fv(uint locaton, bool transpose, Array) When rendering is directed to drawing bufer, OpenGL ES 2.0 target: RENDERBUFFER transpose: FALSE rendering calls cause the drawing bufer to be presented to the internalformat: DEPTH_COMPONENT16, RGBA4, RGB5_A1, HTML page compositor at start of next compositng operaton. RGB565, STENCIL_INDEX8 void vertexAtrib[1234]f(uint index, ...) void drawArrays(enum mode, int frst, long count) void vertexAtrib[1234]fv(uint index, Array value) mode: POINTS, LINE_STRIP, LINE_LOOP, LINES, TRIANGLE_STRIP, TRIANGLE_FAN, TRIANGLES Read Back Pixels [5.13.12] void vertexAtribPointer(uint index, int size, enum type, frst: May not be a negatve value. Pixels in the current framebufer can be read back into an bool normalized, long stride, long ofset) ArrayBuferView object. type: BYTE, SHORT, UNSIGNED_{BYTE, SHORT}, FIXED, FLOAT void drawElements(enum mode, long count, enum type, index: [0, MAX_VERTEX_ATTRIBS - 1] long ofset) void readPixels(int x, int y, long width, long height, stride: [0, 255] mode: POINTS, LINE_STRIP, LINE_LOOP, LINES, TRIANGLE_STRIP, enum format, enum type, Object pixels) ofset, stride: must be a multple of the type size in WebGL TRIANGLE_FAN, TRIANGLES format: RGBA type: UNSIGNED_BYTE, UNSIGNED_SHORT type: UNSIGNED_BYTE

Framebufer Objects [5.13.6] Object createFramebufer() void framebuferTexture2D(enum target, enum atachment, Note: Corresponding OpenGL ES functon is GenFramebufers enum textarget, Object texture, int level) Framebufer objects provide an alternatve rendering target to target and atachment: Same as for framebuferRenderbufer the drawing bufer. void deleteFramebufer(Object bufer) textarget: TEXTURE_2D, TEXTURE_CUBE_MAP_POSITIVE{X, Y, Z}, void bindFramebufer(enum target, Object framebufer) void framebuferRenderbufer(enum target, enum atachment, TEXTURE_CUBE_MAP_NEGATIVE{X, Y, Z}, target: FRAMEBUFFER enum renderbufertarget, Object renderbufer) any getFramebuferAtachmentParameter(enum target, enum checkFramebuferStatus(enum target) target: FRAMEBUFFER enum atachment, enum pname) target: FRAMEBUFFER atachment: COLOR_ATTACHMENT0, {DEPTH, STENCIL}_ATTACHMENT target and atachment: Same as for framebuferRenderbufer Returns: FRAMEBUFFER_{COMPLETE, UNSUPPORTED}, renderbufertarget: RENDERBUFFER pname: FRAMEBUFFER_ATTACHMENT_OBJECT_{TYPE, NAME}, FRAMEBUFFER_INCOMPLETE_{ATTACHMENT, DIMENSIONS, bool isFramebufer(Object framebufer) FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, MISSING_ATTACHMENT} FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE

©2011 Khronos Group - Rev. 06180211 www.khronos.org/webgl WebGL 1.0 API Quick Reference Card Page 3

The OpenGL® ES Shading Language is two closely- Preprocessor [3.4] related languages which are used to create shaders for Preprocessor Directves the vertex and fragment processors contained in the The number sign (#) can be immediately preceded or followed in its line by spaces or horizontal tabs. OpenGL ES processing pipeline. # #defne #undef #if #ifdef #ifndef #else #elif #endif #error #pragma #extension #version #line [n.n.n] refers to sectons in the OpenGL ES Shading Language 1.0 specifcaton at Examples of Preprocessor Directves www.khronos.org/registry/gles • “#version 100” in a shader program specifes that the program is writen in GLSL ES version 1.00. It is optonal. If used, it must occur before anything else in the program other than whitespace or comments. • #extension extension_name : behavior, where behavior can be require, enable, warn, or disable; and where extension_name is the extension supported by the compiler Types [4.1] A shader can aggregate these using arrays and structures to build Predefned Macros more complex types. There are no pointer types. Decimal integer constant that is one more than the number of preceding new-lines in the current __LINE__ source string Basic Types __VERSION__ Decimal integer, e.g.: 100 void no functon return value or empty parameter list GL_ES Defned and set to integer 1 if running on an OpenGL-ES Shading Language. bool Boolean GL_FRAGMENT_PRECISION_HIGH 1 if highp is supported in the fragment language, else undefned [4.5.4] int signed integer foat foatng scalar vec2, vec3, vec4 n-component foatng point vector Qualifers Precision and Precision Qualifers [4.5] bvec2, bvec3, bvec4 Boolean vector Any foatng point, integer, or sampler declaraton can have the Storage Qualifers [4.3] type preceded by one of these precision qualifers: ivec2, ivec3, ivec4 signed integer vector Variable declaratons may be preceded by one storage highp Satsfes minimum requirements for the vertex language. mat2, mat3, mat4 2x2, 3x3, 4x4 foat matrix qualifer. Optonal in the fragment language. none (Default) local read/write memory, or input parameter mediump Satsfes minimum requirements for the fragment sampler2D access a 2D texture language. Its range and precision is between that const Compile-tme constant, or read-only functon provided by lowp and highp. samplerCube access cube mapped texture parameter lowp Range and precision can be less than mediump, but stll represents all color values for any color channel. Structures and Arrays [4.1.8, 4.1.9] atribute Linkage between a vertex shader and OpenGL ES for per-vertex data For example: Structures struct type-name { lowp foat color; members uniform Value does not change across the primitve being } struct-name[]; // optonal variable declaraton, processed, uniforms form the linkage between a varying mediump vec2 Coord; // optonally an array shader, OpenGL ES, and the applicaton lowp ivec2 foo(lowp mat3); Arrays foat foo[3]; highp mat4 m; varying Linkage between a vertex shader and fragment shader * structures and blocks can be arrays Ranges & precisions for precision qualifers (FP=foatng point): * only 1-dimensional arrays supported for interpolated data * structure members can be arrays FP Magnitude Integer Uniform [4.3.4] FP Range Range FP Precision Range Use to declare global variables whose values are the same highp (−262 , 262) (2–62 , 262) Relatve 2–16 (−216 , 216) across the entre primitve being processed. All uniform variables are read-only. Use uniform qualifers with any basic mediump (−214 , 214) (2–14 , 214) Relatve 2–10 (−210 , 210) Operators and Expressions data types, to declare a variable whose type is a structure, or Operators [5.1] Numbered in order of precedence. The an array of any of these. For example: lowp (−2, 2) (2–8 , 2) Absolute 2–8 (−28 , 28) relatonal and equality operators > < <= >= == != evaluate to a uniform vec4 lightPositon; Boolean. To compare vectors component-wise, use functons such as A precision statement establishes a default precision qualifer for subsequent int, foat, and sampler declaratons, e.g.: lessThan(), equal(), etc. Varying [4.3.5] precision highp int; Operator Descripton Associatvity The varying qualifer can be used only with the data types foat, vec2, vec3, vec4, mat2, mat3, mat4, or arrays of these. Invariant Qualifers Examples [4.6] 1. ( ) parenthetcal grouping N/A Structures cannot be varying. Varying variables are required to have global scope. Declaraton is as follows: #pragma STDGL invariant(all) Force all output variables to be [ ] array subscript invariant ( ) functon call & constructor structure varying vec3 normal; 2. L - R invariant gl_Positon; Qualify a previously declared . feld or method selector, swizzler variable ++ -- postix increment and decrement Parameter Qualifers [4.4] Input values are copied in at functon call tme, output values invariant varying mediump Qualify as part of a variable ++ -- prefx increment and decrement 3. R - L are copied out at functon return tme. vec3 Color; declaraton + - ! unary none (Default) same as in 4. * / multplicatve L - R Order of Qualifcaton [4.7] in For functon parameters passed into a functon When multple qualifcatons are present, they must follow a 5. + - additve L - R out For functon parameters passed back out of a functon, but strict order. This order is as follows. not initalized for use when passed in 7. < > <= >= relatonal L - R invariant, storage, precision inout For functon parameters passed both into and out of a storage, parameter, precision 8. == != equality L - R functon 12. && logical and L - R 13. ^^ logical exclusive or L - R 14. | | logical inclusive or L - R Aggregate Operatons and Constructors selecton (Selects one entre operand. Matrix Constructor Examples [5.4] m = m +/- m; // matrix component-wise additon/subtracton 15. ? : Use mix() to select individual components L - R mat2(foat) // init diagonal m = m * m; // linear algebraic multply of vectors.) mat2(vec2, vec2); // column-major order m = v * m; // row vector * matrix linear algebraic multply mat2(foat, foat, foat, foat); // column-major order m = m * v; // matrix * column vector linear algebraic multply = assignment f = dot(v, v); // vector dot product 16. += -= L - R arithmetc assignments Structure Constructor Example [5.4.3] v = cross(v, v); // vector cross product *= /= struct light {foat intensity; vec3 pos; }; m = matrixCompMult(m, m); // component-wise multply light lightVar = light(3.0, vec3(1.0, 2.0, 3.0)); 17. , sequence L - R Structure Operatons [5.7] Matrix Components [5.6] Select structure felds using the period (.) operator. Other Vector Components [5.5] Access components of a matrix with array subscriptng syntax. operators include: In additon to array numeric subscript syntax, names of vector For example: . feld selector components are denoted by a single leter. Components can be mat4 m; // m represents a matrix == != equality swizzled and replicated, e.g.: pos.xx, pos.zy m[1] = vec4(2.0); // sets second column to all 2.0 = assignment {x, y, z, w} Use when accessing vectors that represent points or m[0][0] = 1.0; // sets upper lef element to 1.0 normals m[2][3] = 2.0; // sets 4th element of 3rd column to 2.0 Array Operatons [4.1.9] {r, g, b, a} Use when accessing vectors that represent colors Examples of operatons on matrices and vectors: Array elements are accessed using the array subscript {s, t, p, q} Use when accessing vectors that represent texture m = f * m; // scalar * matrix component-wise operator “[ ]”. For example: v = f * v; // scalar * vector component-wise coordinates difuseColor += lightIntensity[3] * NdotL; v = v * v; // vector * vector component-wise

©2011 Khronos Group - Rev. 0618 www.khronos.org/webgl WebGL 1.0 API Quick Reference Card Page 4

Built-In Inputs, Outputs, and Constants [7] Built-In Constants With Minimum Values [7.4] Shader programs use Special Variables to communicate with fxed-functon parts of the pipeline. Output Special Variables Built-in Constant Minimum value may be read back afer writng. Input Special Variables are read-only. All Special Variables have global scope. const mediump int gl_MaxVertexAtribs 8 Vertex Shader Special Variables [7.1] const mediump int gl_MaxVertexUniformVectors 128 Outputs: const mediump int gl_MaxVaryingVectors 8 Variable Descripton Units or coordinate system const mediump int gl_MaxVertexTextureImageUnits 0 highp vec4 gl_Positon; transformed vertex positon clip coordinates const mediump int gl_MaxCombinedTextureImageUnits 8 mediump foat gl_PointSize; transformed point size (point rasterizaton only) pixels const mediump int gl_MaxTextureImageUnits 8 Fragment Shader Special Variables [7.2] const mediump int gl_MaxFragmentUniformVectors 16 Fragment shaders may write to gl_FragColor or to one or more elements of gl_FragData[], but not both. const mediump int gl_MaxDrawBufers 1 The size of the gl_FragData array is given by the built-in constant gl_MaxDrawBufers. Inputs: Built-In Uniform State [7.5] Variable Descripton Units or coordinate system Specifes depth range in window coordinates. If an implementaton does not support highp precision in the fragment language, and state is listed as mediump vec4 gl_FragCoord; fragment positon within bufer window coordinates highp, then that state will only be available as mediump in the fragment bool gl_FrontFacing; fragment belongs to a front-facing primitve Boolean language. mediump vec2 gl_PointCoord; fragment positon within a point (point rasterizaton only) 0.0 to 1.0 for each component struct gl_DepthRangeParameters { Outputs: highp foat near; // n Variable Descripton Units or coordinate system highp foat far; // f highp foat dif; // f - n mediump vec4 gl_FragColor; fragment color RGBA color }; mediump vec4 gl_FragData[n] fragment color for color atachment n RGBA color uniform gl_DepthRangeParameters gl_DepthRange;

Built-In Functons Statements and Structure Angle & Trigonometry Functons [8.1] Geometric Functons [8.4] Iteraton and Jumps [6] Component-wise operaton. Parameters specifed as are These functons operate on vectors as vectors, not assumed to be in units of radians. T is foat, vec2, vec3, vec4. component-wise. T is foat, vec2, vec3, vec4. Functon Call call by value-return foat length(T x) length of vector Iteraton for (;;) { break, contnue } T radians(T degrees) degrees to radians while ( ) { break, contnue } T degrees(T radians) radians to degrees foat distance(T p0, T p1) distance between points do { break, contnue } while ( ); T sin(T angle) sine foat dot(T x, T y) dot product Selecton if ( ) { } vec3 cross(vec3 x, vec3 y) cross product T cos(T angle) cosine if ( ) { } else { } T normalize(T x) normalize vector to length 1 T tan(T angle) tangent Jump break, contnue, return T faceforward(T N, T I, T Nref) returns N if dot(Nref, I) < 0, else -N discard // Fragment shader only T asin(T x) arc sine T refect(T I, T N) refecton directon I - 2 * dot(N,I) * N Entry void main() T acos(T x) arc cosine T refract(T I, T N, foat eta) refracton vector T atan(T y, T x) arc tangent T atan(T y_over_x) Matrix Functons [8.5] Type mat is any matrix type. Sample Program A shader pair that applies difuse and ambient lightng to a Exponental Functons [8.2] mat matrixCompMult(mat x, mat y) multply x by y component-wise textured object. Component-wise operaton. T is foat, vec2, vec3, vec4. T pow(T x, T y) xy Vector Relatonal Functons [8.6] Compare x and y component-wise. Sizes of input and return vectors Vertex Shader T exp(T x) ex for a partcular call must match. Type bvec is bvecn; vec is vecn; ivec uniform mat4 mvp_matrix; // model-view-projecton matrix T log(T x) ln is ivecn (where n is 2, 3, or 4). T is the union of vec and ivec. uniform mat3 normal_matrix; // normal matrix bvec lessThan(T x, T y) x < y uniform vec3 ec_light_dir; // light directon in eye coords T exp2(T x) 2x bvec lessThanEqual(T x, T y) x <= y atribute vec4 a_vertex; // vertex positon T log2(T x) log 2 bvec greaterThan(T x, T y) x > y atribute vec3 a_normal; // vertex normal T sqrt(T x) square root bvec greaterThanEqual(T x, T y) x >= y atribute vec2 a_texcoord; // texture coordinates T inversesqrt(T x) inverse square root bvec equal(T x, T y) x == y varying foat v_difuse; bvec equal(bvec x, bvec y) varying vec2 v_texcoord; Common Functons [8.3] bvec notEqual(T x, T y) x!= y Component-wise operaton. T is foat, vec2, vec3, vec4. bvec notEqual(bvec x, bvec y) void main(void) T abs(T x) absolute value bool any(bvec x) true if any component of x is true { T sign(T x) returns -1.0, 0.0, or 1.0 bool all(bvec x) true if all components of x are true // put vertex normal into eye coords vec3 ec_normal = normalize(normal_matrix * a_normal); T foor(T x) nearest integer <= x bvec not(bvec x) logical complement of x T ceil(T x) nearest integer >= x Texture Lookup Functons [8.7] // emit difuse scale factor, texcoord, and positon T fract(T x) x - foor(x) Available only in vertex shaders. v_difuse = max(dot(ec_light_dir, ec_normal), 0.0); v_texcoord = a_texcoord; T mod(T x, T y) vec4 texture2DLod(sampler2D sampler, vec2 coord, foat lod) modulus gl_Positon = mvp_matrix * a_vertex; T mod(T x, foat y) vec4 texture2DProjLod(sampler2D sampler, vec3 coord, foat lod) } T min(T x, T y) minimum value vec4 texture2DProjLod(sampler2D sampler, vec4 coord, foat lod) T min(T x, foat y) vec4 textureCubeLod(samplerCube sampler, vec3 coord, foat lod) Fragment Shader T max(T x, T y) maximum value T max(T x, foat y) Available only in fragment shaders. precision mediump foat; vec4 texture2D(sampler2D sampler, vec2 coord, foat bias) T clamp(T x, T minVal, T maxVal) uniform sampler2D t_refectance; T clamp(T x, foat minVal, min(max(x, minVal), maxVal) vec4 texture2DProj(sampler2D sampler, vec3 coord, foat bias) uniform vec4 i_ambient; foat maxVal) vec4 texture2DProj(sampler2D sampler, vec4 coord, foat bias) varying foat v_difuse; T mix(T x, T y, T a) linear blend of x and y vec4 textureCube(samplerCube sampler, vec3 coord, foat bias) varying vec2 v_texcoord; T mix(T x, T y, foat a) Available in vertex and fragment shaders. void main (void) T step(T edge, T x) 0.0 if x < edge, else 1.0 vec4 texture2D(sampler2D sampler, vec2 coord) T step(foat edge, T x) { vec4 texture2DProj(sampler2D sampler, vec3 coord) vec4 color = texture2D(t_refectance, v_texcoord); T smoothstep(T edge0, T edge1, T x) T smoothstep(foat edge0, clip and smooth vec4 texture2DProj(sampler2D sampler, vec4 coord) gl_FragColor = color * (vec4(v_difuse) + i_ambient); foat edge1, T x) vec4 textureCube(samplerCube sampler, vec3 coord) }

WebGL and OpenGL ES are registered trademarks of Khronos Group. The Khronos Group is an industry consortum creatng open standards for the authoring and acceleraton of parallel computng, graphics and dynamic media on a wide variety of platorms and devices. See www.khronos.org to learn about the Khronos Group. See www.khronos.org/webgl to learn about WebGL. See www.khronos.org/opengles to learn about OpenGL ES.

©2011 Khronos Group - Rev. 0618 Reference card producton by Miller & Mattson www.millermatson.com www.khronos.org/webgl