Introduction to Computer Graphics with WebGL

Similar documents
CS452/552; EE465/505. Image Processing Frame Buffer Objects

Picking (In WebGL) Picking idea

CS452/552; EE465/505. Shadow Mapping in WebGL

CISC 3620 Lecture 7 Lighting and shading. Topics: Exam results Buffers Texture mapping intro Texture mapping basics WebGL texture mapping

Buffers. Angel and Shreiner: Interactive Computer Graphics 7E Addison-Wesley 2015

WebGL A quick introduction. J. Madeira V. 0.2 September 2017

Programming with OpenGL Complete Programs Objectives Build a complete first program

CS452/552; EE465/505. Texture Mapping in WebGL

CS452/552; EE465/505. Image Formation

CS452/552; EE465/505. Review & Examples

CS 179 GPU Programming

Models and Architectures. Angel and Shreiner: Interactive Computer Graphics 7E Addison-Wesley 2015

Texture Mapping. CS 537 Interactive Computer Graphics Prof. David E. Breen Department of Computer Science

CS 432 Interactive Computer Graphics

CS 432 Interactive Computer Graphics

WebGL. Creating Interactive Content with WebGL. Media #WWDC14. Session 509 Dean Jackson and Brady Eidson WebKit Engineers

Lecture 19: OpenGL Texture Mapping. CITS3003 Graphics & Animation

Building Models. CS 537 Interactive Computer Graphics Prof. David E. Breen Department of Computer Science

CS452/552; EE465/505. Models & Viewing

Programming with WebGL Part 1: Background. CS 432 Interactive Computer Graphics Prof. David E. Breen Department of Computer Science

OpenGL pipeline Evolution and OpenGL Shading Language (GLSL) Part 2/3 Vertex and Fragment Shaders

CS4621/5621 Fall Basics of OpenGL/GLSL Textures Basics

Objectives. Programming with WebGL Part 1: Background. Retained vs. Immediate Mode Graphics. Early History of APIs. PHIGS and X.

CS452/552; EE465/505. Overview of Computer Graphics

Discussion 3. PPM loading Texture rendering in OpenGL

Computer Graphics CS 543 Lecture 4 (Part 2) Building 3D Models (Part 2)

Fog example. Fog is atmospheric effect. Better realism, helps determine distances

We assume that you are familiar with the following:

CS475/CS675 - Computer Graphics. OpenGL Drawing

Building Models. Prof. George Wolberg Dept. of Computer Science City College of New York

CS452/552; EE465/505. Transformations

CPSC 436D Video Game Programming

2D graphics with WebGL

C P S C 314 S H A D E R S, O P E N G L, & J S RENDERING PIPELINE. Mikhail Bessmeltsev

Introduction to Computer Graphics with WebGL

Programming with OpenGL Part 3: Shaders. Ed Angel Professor of Emeritus of Computer Science University of New Mexico

Comp 410/510 Computer Graphics Spring Programming with OpenGL Part 2: First Program

Texturing. Slides done bytomas Akenine-Möller and Ulf Assarsson Department of Computer Engineering Chalmers University of Technology

Shaders. Slide credit to Prof. Zwicker

Introduction to Computer Graphics with WebGL

Texturing. Slides done by Tomas Akenine-Möller and Ulf Assarsson Department of Computer Engineering Chalmers University of Technology

Best practices for effective OpenGL programming. Dan Omachi OpenGL Development Engineer

Rendering Objects. Need to transform all geometry then

Comp 410/510 Computer Graphics Spring Programming with OpenGL Part 3: Shaders

Comp 410/510 Computer Graphics Spring Programming with OpenGL Part 4: Three Dimensions

Mobile Application Programing: Android. OpenGL Operation

We will use WebGL 1.0. WebGL 2.0 is now being supported by most browsers but requires a better GPU so may not run on older computers or on most cell

Lecture 5 Vertex and Fragment Shaders-1. CITS3003 Graphics & Animation

WebGL: Hands On. DevCon5 NYC Kenneth Russell Software Engineer, Google, Inc. Chair, WebGL Working Group

OPENGL RENDERING PIPELINE

Introduction to Computer Graphics with WebGL

Introduction to Computer Graphics with WebGL

Building Models. Objectives Introduce simple data structures for building polygonal models. Vertex lists Edge lists

COMP371 COMPUTER GRAPHICS

WebGL. Mike Bailey. Oregon State University. What is WebGL?

CSE 167: Introduction to Computer Graphics Lecture #7: GLSL. Jürgen P. Schulze, Ph.D. University of California, San Diego Spring Quarter 2016

OpenGL Performances and Flexibility. Visual Computing Laboratory ISTI CNR, Italy

Computação Gráfica. Computer Graphics Engenharia Informática (11569) 3º ano, 2º semestre. Chap. 4 Windows and Viewports

Copyright Khronos Group 2012 Page 1. Teaching GL. Dave Shreiner Director, Graphics and GPU Computing, ARM 1 December 2012

General Purpose computation on GPUs. Liangjun Zhang 2/23/2005

Mobile Application Programing: Android. OpenGL Operation

Lighting and Texturing

Steiner- Wallner- Podaras

Graphics Programming. Computer Graphics, VT 2016 Lecture 2, Chapter 2. Fredrik Nysjö Centre for Image analysis Uppsala University

WebGL and GLSL Basics. CS559 Fall 2015 Lecture 10 October 6, 2015

Computergraphics Exercise 15/ Shading & Texturing

Information Coding / Computer Graphics, ISY, LiTH GLSL. OpenGL Shading Language. Language with syntax similar to C

Introduction to OpenGL/GLSL and WebGL GLSL

Building Models. Angel and Shreiner: Interactive Computer Graphics 7E Addison-Wesley 2015

Programming with OpenGL Shaders I. Adapted From: Ed Angel Professor of Emeritus of Computer Science University of New Mexico

OpenGL ES for iphone Games. Erik M. Buck

Pixels and Buffers. CS 537 Interactive Computer Graphics Prof. David E. Breen Department of Computer Science

Over the past 15 years, OpenGL has become

Computer Graphics (CS 543) Lecture 4a: Linear Algebra for Graphics (Points, Scalars, Vectors)

Overview. By end of the week:

WebGL and GLSL Basics. CS559 Fall 2016 Lecture 14 October

Programming with OpenGL Shaders I. Adapted From: Ed Angel Professor of Emeritus of Computer Science University of New Mexico

三維繪圖程式設計 3D Graphics Programming Design 第七章基礎材質張貼技術嘉大資工系盧天麒

OpenGL shaders and programming models that provide object persistence

Today s Agenda. Basic design of a graphics system. Introduction to OpenGL

From system point of view, a graphics application handles the user input, changes the internal state, called the virtual world by modeling or

Blis: Better Language for Image Stuff Project Proposal Programming Languages and Translators, Spring 2017

Mobile Application Programming: Android. OpenGL Operation

SUMMARY. CS380: Introduction to Computer Graphics Texture Mapping Chapter 15. Min H. Kim KAIST School of Computing 18/05/03.

Geometry Shaders. And how to use them

CS 548: COMPUTER GRAPHICS PORTRAIT OF AN OPENGL PROGRAM SPRING 2015 DR. MICHAEL J. REALE

Tutorial 04. Harshavardhan Kode. September 14, 2015

10/24/2017. WebGL. What is WebGL? What are the Important Things to Know about OpenGL-ES 2.0? What are the Important Things to Know about WebGL?

The Graphics Pipeline

Lecture 11 Shaders and WebGL. October 8, 2015

OpenCL / OpenGL Texture Interoperability: An Image Blurring Case Study

Shader Programs. Lecture 30 Subsections 2.8.2, Robb T. Koether. Hampden-Sydney College. Wed, Nov 16, 2011

TSBK 07! Computer Graphics! Ingemar Ragnemalm, ISY

OUTLINE. Implementing Texturing What Can Go Wrong and How to Fix It Mipmapping Filtering Perspective Correction

Programming with OpenGL Part 5: More GLSL. Ed Angel Professor Emeritus of Computer Science University of New Mexico

Graphics. Texture Mapping 고려대학교컴퓨터그래픽스연구실.

API Background. Prof. George Wolberg Dept. of Computer Science City College of New York

Programmable GPUs. Real Time Graphics 11/13/2013. Nalu 2004 (NVIDIA Corporation) GeForce 6. Virtua Fighter 1995 (SEGA Corporation) NV1

CS4621/5621 Fall Computer Graphics Practicum Intro to OpenGL/GLSL

Yazhuo Liu Homework 3

Transcription:

Introduction to Computer Graphics with WebGL Ed Angel The Mandelbrot Set Fractals Fractal (fractional geometry) objects generate some of the most complex and beautiful graphics - The mathematics describing them is also complex and beautiful - Examples include the Sierpinski Gasket we used for our first examples The most famous fractal object is the Mandelbrot Set We will use generation and display of the Mandelbrot set to demonstrate the power of GPU computation 2 Complex Arithmetic Complex number defined by two scalars z = x + jy j 2 = - Addition and Subtraction z +z 2 = x + x 2 +j(y +y 2 ) z *z 2 = x *x 2 -y *y 2 + j(x *y 2 +x 2 *y ) Magnitude z 2 = x 2 + y 2 3

4 Iteration in the Complex Plane y z 3 = F(z 2 ) z 2 = F(z ) x z 0 z = F(z 0 ) Mandelbrot Set iterate on z k+ =z k2 +c with z 0 = 0 + j0 Two cases as k z k z k remains finite If for a given c, z k remains finite, then c belongs to the Mandelbrot set 5 Computing the Mandelbrot Set Pick a rectangular region Map each pixel to a value in this region Do an iterative calculation for each pixel - If magnitude is greater than 2, we know sequence will diverge and point does not belong to the set - Stop after a fixed number of iterations - Points with small magnitudes should be in set - Color each point based on its magnitude 6

7 Mandelbrot Set Exploring the Mandelbrot Set Most interesting parts are centered near (-0.5, 0.0) Really interesting parts are where we are uncertain if points are in or out of the set Repeated magnification of these regions reveals complex and beautiful patterns We use color maps to enhance the detail 8 Mandelbrot Set 9

Introduction to Computer Graphics with WebGL Ed Angel Computing the Mandelbrot Set Computing in the JS File I Form a texture map of the set and map to a rectangle var height = 0.5; // size of window in complex plane var width = 0.5; var cx = -0.5; var cy = 0.5; // center of window in complex plane var max = 00; // max number of interations per point var n = 52; var m =52; var teximage = new Uint8Array(4*n*m); 2 Computing in JS File II for ( var i = 0; i < n; i++ ) for ( var j = 0; j < m; j++ ) { var x = i * ( width / (n - ) ) + cx - width / 2; var y = j * ( height / ( m - ) ) + cy - height / 2; var c = [ 0.0, 0.0 ]; var p = [ x, y ]; for ( var k = 0; k < max; k++ ) { // compute c = c^2 + p } c = [c[0]*c[0]-c[]*c[], 2*c[0]*c[]]; c = [c[0]+p[0], c[]+p[]]; v = c[0]*c[0]+c[]*c[]; if ( v > 4.0 ) break; // not in set if mag > 2 3

Computing in JS File III // assign gray level to point based on its magnitude if ( v >.0 ) v =.0; // clamp if > teximage[4*i*m+4*j] = 255*v; teximage[4*i*m+4*j+] = 255*( 0.5* (Math.sin( v*math.pi/80 ) +.0)); teximage[4*i*m+4*j+2] = 255*(.0 - v); teximage[4*i*m+4*j+3] = 255; } Set up two triangles to define a rectangle Set up texture object with the set as data Render the triangles 4 Example 5 Fragment Shader Our first implementation is incredibly inefficient and makes no use of the power of the fragment shader Note the calculation is embarrassingly parallel - computation for the color of each fragment is completely independent - Why not have each fragment compute membership for itself? - Each fragment would then determine its own color 6

Introduction to Computer Graphics with WebGL Ed Angel Interactive Mandelbrot Set Interactive Program JS file sends window parameters obtained from sliders to the fragment shader as uniforms Only geometry is a rectangle No need for a texture map since shader can work on individual fragments (pixels) 2 Fragment Shader I precision mediump float; uniform float cx; uniform float cy; uniform float scale; float height; float width; void main() { const int max = 00;// number of iterations per point const float PI = 3.459; float n = 000.0; float m = 000.0; 3

Fragment Shader II float v; float x = gl_fragcoord.x/(n*scale)+cx-.0/(2.0*scale); float y = gl_fragcoord.y/(m*scale)+cy-.0/(2.0*scale); float ax=0.0, ay=0.0; float bx, by; for ( int k = 0; k < max; k++ ) { // compute c = c^2 + p } bx = ax*ax-ay*ay; by = 2.0*ax*ay; ax = bx+x; ay = by+y; v = ax*ax+ay*ay; if ( v > 4.0 ) break;// assume not in set if mag > 2 4 Fragment Shader // assign gray level to point based on its magnitude // clamp if > } v = min(v,.0); gl_fragcolor.r = v; gl_fragcolor.g = 0.5* sin( 3.0*PI*v) +.0; gl_fragcolor.b = 0.5* cos( 9.0*PI*v) +.0; gl_fragcolor.a =.0; 5 Analysis This implementation will use as many fragment processors as are available concurrently Note that if an iteration ends early, the GPU will use that processor to work on another fragment Note also the absence of loops over x and y Still not using the full parallelism since we are really computing a luminance image 6

Introduction to Computer Graphics with WebGL Ed Angel Picking by Color Picking Use mouse to indicate an object on the display - object is defined in the application Selection-feedback method supported by desktop OpenGL has been deprecated Basic problem is how do we go from a position of the mouse to an object - Easy to get mouse position with an event listener - Hard to associate color at mouse location with a unique object - Would be easy if each object had a unique color - Solution: use off-screen rendering 2 Picking Example Example: rotating cube with shading - return which face is clicked on with mouse - normal rendering uses vertex colors that are interpolated across each face - Vertex colors could be determined by lighting calculation or just assigned 3

Algorithm Assign a unique color to each object When the mouse is clicked: - Do an off-screen render using these colors and no lighting - use gl.readpixels to obtain the color of the pixel where the mouse is located - map the color to the object id - do a normal render to the display 4 Shaders Only need one program object Vertex shader: same as in previous cube examples - includes rotation matrices - gets angle as uniform variable Fragment shader - Stores face colors for picking - Gets vertex color for normal render from rasterizer Send uniform integer to fragment shader as index for desired color 5 Fragment Shader precision mediump float; uniform int i; varying vec4 fcolor; void main() { vec4 c[7]; c[0] = fcolor; c[] = vec4(.0, 0.0, 0.0,.0); c[2] = vec4(0.0,.0, 0.0,.0); c[3] = vec4(0.0, 0.0,.0,.0); c[4] = vec4(.0,.0, 0.0,.0); c[5] = vec4(0.0,.0,.0,.0); c[6] = vec4(.0, 0.0,.0,.0); 6

Fragment Shader // no case statement in GLSL } if(i==0) gl_fragcolor = c[0]; else if(i==) gl_fragcolor = c[]; else if(i==2) gl_fragcolor = c[2]; else if(i==3) gl_fragcolor = c[3]; else if(i==4) gl_fragcolor = c[4]; else if(i==5) gl_fragcolor = c[5]; else if(i==6) gl_fragcolor = c[6]; 7 Setup Allocate a frame buffer object framebuffer = gl.createframebuffer(); gl.bindframebuffer( gl.framebuffer, framebuffer); Attach a color buffer gl.framebuffertexture2d(gl.framebuffer, gl.color_attachment0, gl.texture_2d, texture, 0); Allow for normal render gl.bindframebuffer(gl.framebuffer, null); 8 Event Listener canvas.addeventlistener("mousedown", function(){ gl.bindframebuffer(gl.framebuffer, framebuffer); gl.clear( gl.color_buffer_bit); gl.uniform3fv(thetaloc, theta); for(var i=0; i<6; i++) { gl.uniformi(gl.getuniformlocation(program, "i"), i+); gl.drawarrays( gl.triangles, 6*i, 6 ); } var x = event.clientx; var y = canvas.height -event.clienty; gl.readpixels(x, y,,, gl.rgba, gl.unsigned_byte, color); 9

Event Listener if(color[0]==255) if(color[]==255) console.log("yellow"); else if(color[2]==255) console.log("magenta"); else console.log("red"); else if(color[]==255) if(color[2]==255) console.log("cyan"); else console.log("green"); else if(color[2]==255) console.log("blue"); else console.log("background"); 0 Event Listener // return to default framebuffer gl.bindframebuffer(gl.framebuffer, null); //send index 0 to fragment shader gl.uniformi(gl.getuniformlocation(program, "i"), 0); //normal render gl.clear( gl.color_buffer_bit ); gl.uniform3fv(thetaloc, theta); gl.drawarrays(gl.triangles, 0, 36); }); Writing to the Display In HTML file: <div id = "test">face</div> In JS file: var elt = document.getelementbyid("test"); In listener: gl.readpixels(x,y,,, gl.rgba, gl.unsigned_byte,color); if(color[0]==255) if(color[]==255) elt.innerhtml = "<div> front </div>"; else if(color[2]==255) elt.innerhtml="<div>back</div>"; else elt.innerhtml = "<div> right </div>"; else if(color[]==255) if(color[2]==255) elt.innerhtml = "<div> left </div>"; else elt.innerhtml = "<div> top </div> ; else if(color[2]==255)elt.innerhtml="<div>bottom</div> ; else elt.innerhtml = "<div> background </div>"; 2

Picking by Selection Possible with render-to-texture When mouse clicked do a off screen rendering with new viewing conditions that render only a small area around mouse Keep track of what gets rendered to this off screen buffer 3

Introduction to Computer Graphics with WebGL Ed Angel Framebuffer Objects Discrete Processing in WebGL Recent GPUs contain large amounts of memory - Texture memory - Framebuffer - Floating point Fragment shaders support discrete operations at the pixel level Separate pixel (texel) pipeline 2 Accessing the Framebuffer Pre 3. OpenGL had functions that allowed access to the framebuffer and other OpenGL buffers - Draw Pixels - Read Pixels - Copy Pixels - BitBlt - Accumulation Buffer functions All deprecated 3

Going between CPU and GPU We have already seen that we can write pixels as texels to texture memory Texture objects reduce transfers between CPU and GPU Transfer of pixel data back to CPU slow Want to manipulate pixels without going back to CPU - Image processing - GPGPU 4 Framebuffer Objects Framebuffer Objects (FBOs) are buffers that are created by the application on the GPU - Not under control of window system - Cannot be displayed - Can attach a renderbuffer to a FBO and can render off screen into the attached buffer - Attached buffer can then be detached and used as a texture map for an on-screen render to the default frame buffer 5 Render to Texture Textures are shared by all instances of the fragment shade If we render to a texture attachment we can create a new texture image that can be used in subsequent renderings We can use a double buffering strategy (buffer pingponging) for operations such as convolution 6

Steps Create an Empty Texture Object Create a FBO Attach renderbuffer for texture image Bind FBO Render scene Detach renderbuffer Bind texture Render with new texture 7 Empty Texture Object texture = gl.createtexture(); gl.activetexture( gl.texture0 ); gl.bindtexture( gl.texture_2d, texture ); gl.teximage2d(gl.texture_2d, 0, gl.rgba, 52, 52, 0, gl.rgba, gl.unsigned_byte, null); gl.generatemipmap(gl.texture_2d); gl.texparameteri( gl.texture_2d, gl.texture_min_filter, gl.nearest_mipmap_linear ); gl.texparameteri( gl.texture_2d, gl.texture_mag_filter, gl.nearest ); 8 Creating a FBO We create a framebuffer object in a similar manner to other objects Creating an FBO creates an empty FBO Must add needed resources - Can add a renderbuffer to render into - Can add a texture which can also be rendered into - For hidden surface removal we must add a depth buffer attachment to the renderbuffer 9

Frame Buffer Object var framebuffer = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, framebuffer); framebuffer.width = 52; framebuffer.height = 52; // Don t need renderer buffer if we are rendering to // texture and we don t need HSR //renderbuffer = gl.createrenderbuffer(); //gl.bindrenderbuffer(gl.renderbuffer, renderbuffer); //gl.renderbufferstorage(gl.renderbuffer, // gl.depth_component6, 52, 52); 0 Frame Buffer Object (cont) // Attach color buffer gl.framebuffertexture2d(gl.framebuffer, gl.color_attachment0, gl.texture_2d, texture, 0); // Attach depth buffer if needed for HSR //gl.framebufferrenderbuffer(gl.framebuffer, gl.depth_attachment, gl.renderbuffer, renderbuffer); // check for completeness var status = gl.checkframebufferstatus(gl.framebuffer); if(status!= gl.framebuffer_complete) alert('frame Buffer Not Complete'); Rest of Initialization Same as previous examples - Allocate VAO - Fill VAO with data for render to texture Initialize two program objects with different shaders - First for render to texture - Second for rendering with created texture 2

Introduction to Computer Graphics with WebGL Ed Angel Render to Texture Program Objects and Shaders For most applications of render-to-texture we need multiple program objects and shaders - One set for creating a texture - Second set for rendering with that texture Applications that we consider later such as buffer pingponging may require additional program objects 2 Example Second rendering: rectangle on blue background with first rendering as texture map First rendering: red triangle on a gray background 3

Program Object Shaders pass through vertex shader: attribute vec4 vposition; void main() { gl_position = vposition; } fragment shader to get a red triangle: precision mediump float; void main() { gl_fragcolor = vec4(.0, 0.0, 0.0,.0); } 4 Program Object 2 Shaders // vertex shader attribute vec4 vposition; attribute vec2 vtexcoord; varying vec2 ftexcoord; void main() { gl_position = vposition; ftexcoord = vtexcoord; } 5 Program Object 2 Shaders // fragment shader precision mediump float; varying vec2 ftexcoord; uniform sampler2d texture; void main() { gl_fragcolor = texture2d( texture, ftexcoord); } 6

First Render (to Texture) gl.useprogram( program ); var buffer = gl.createbuffer(); gl.bindbuffer( gl.array_buffer, buffer ); gl.bufferdata( gl.array_buffer, flatten(pointsarray), gl.static_draw ); // Initialize the vertex position attribute from the vertex shader var vposition = gl.getattriblocation(program, "vposition ); gl.vertexattribpointer( vposition, 2, gl.float, false, 0, 0 ); gl.enablevertexattribarray( vposition ); 7 First Render (to Texture) // Render one triangle gl.viewport(0, 0, 64, 64); gl.clearcolor(0.5, 0.5, 0.5,.0); gl.clear(gl.color_buffer_bit ); gl.drawarrays(gl.triangles, 0, 3); 8 Set Up Second Render Bind to default window system framebuffer gl.bindframebuffer(gl.framebuffer, null); gl.disablevertexattribarray(vposition); gl.useprogram(program2); Assume we have already set up a texture object with null texture image gl.activetexture(gl.texture0); gl.bindtexture(gl.texture_2d, texture); set up vertex attribute arrays for texture coordinates and rectangle as usual 9

Data for Second Render var buffer2 = gl.createbuffer(); gl.bindbuffer( gl.array_buffer, buffer2); gl.bufferdata(gl.array_buffer, flatten(vertices), gl.static_draw); var vposition = gl.getattriblocation( program2, "vposition" ); gl.vertexattribpointer( vposition, 2, gl.float, false, 0, 0 ); gl.enablevertexattribarray( vposition ); 0 Data for Second Render var buffer3 = gl.createbuffer(); gl.bindbuffer( gl.array_buffer, buffer3); gl.bufferdata( gl.array_buffer, flatten(texcoord), gl.static_draw); var vtexcoord = gl.getattriblocation( program2, "vtexcoord"); gl.vertexattribpointer( vtexcoord, 2, gl.float, false, 0, 0 ); gl.enablevertexattribarray( vtexcoord ); Render a Quad with Texture gl.uniformi( gl.getuniformlocation(program2, "texture"), 0); gl.viewport(0, 0, 52, 52); gl.clearcolor(0.0, 0.0,.0,.0); gl.clear( gl.color_buffer_bit ); gl.drawarrays(gl.triangles, 0, 6); 2

Dynamic 3D Example 3