This Lecture. Why OpenGL? Introduction to OpenGL. Programmer s View

Similar documents
To Do. Demo: Surreal (HW 3) This Lecture. Introduction to OpenGL. Outline. Foundations of Computer Graphics (Spring 2012)

This Lecture. Introduction to OpenGL. Outline. Why OpenGL? Programmer s View. Foundations of Computer Graphics

To Do. Computer Graphics (Fall 2008) Course Outline. Course Outline. Methodology for Lecture. Demo: Surreal (HW 3)

To Do. Demo: Surreal (now 15+ years ago) This Lecture. Outline. Computer Graphics. CSE 167 [Win 19], Lecture 6: OpenGL 1 Ravi Ramamoorthi

Methodology for Lecture

To Do. Review of Last Demo. Methodology for Lecture. Geometry Basic Setup. Outline. Foundations of Computer Graphics (Fall 2012)

CS559: Computer Graphics. Lecture 12: OpenGL Li Zhang Spring 2008

Basic Graphics Programming


Lectures OpenGL Introduction

CS Computer Graphics: OpenGL, Continued

CS Computer Graphics: OpenGL, Continued

Introduction to Computer Graphics with OpenGL/GLUT

C++ is Fun Part 13 at Turbine/Warner Bros.! Russell Hanson

GL_COLOR_BUFFER_BIT, GL_PROJECTION, GL_MODELVIEW

Basic Graphics Programming

Precept 2 Aleksey Boyko February 18, 2011

Books, OpenGL, GLUT, GLUI, CUDA, OpenCL, OpenCV, PointClouds, and G3D

OpenGL. Jimmy Johansson Norrköping Visualization and Interaction Studio Linköping University

11/1/13. Basic Graphics Programming. Teaching Assistant. What is OpenGL. Course Producer. Where is OpenGL used. Graphics library (API)

Lecture 4 of 41. Lab 1a: OpenGL Basics

Lecture 3. Understanding of OPenGL programming

ERKELEY DAVIS IRVINE LOS ANGELES RIVERSIDE SAN DIEGO SAN FRANCISCO EECS 104. Fundamentals of Computer Graphics. OpenGL

RECITATION - 1. Ceng477 Fall

// double buffering and RGB glutinitdisplaymode(glut_double GLUT_RGBA); // your own initializations

CS 4731 Lecture 3: Introduction to OpenGL and GLUT: Part II. Emmanuel Agu

VR-programming tools (procedural) More VRML later in this course! (declarative)

CS 4204 Computer Graphics

OpenGL/GLUT Intro. Week 1, Fri Jan 12

Computer graphics MN1

Erik Anchondo cse 520 lab 4

OpenGL refresher. Advanced Computer Graphics 2012

Drawing Primitives. OpenGL basics

Teacher Assistant : Tamir Grossinger Reception hours: by - Building 37 / office -102 Assignments: 4 programing using

An Overview GLUT GLSL GLEW

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

Exercise 1 Introduction to OpenGL

Computer Graphics Course 2005

Computer Graphics. Bing-Yu Chen National Taiwan University

CMSC 425: Lecture 4 More about OpenGL and GLUT Tuesday, Feb 5, 2013

Information Coding / Computer Graphics, ISY, LiTH. OpenGL! ! where it fits!! what it contains!! how you work with it 11(40)

Philip Calderon CSE 520 Lab 3 Color Shader

Display Lists in OpenGL

CS559: Computer Graphics. Lecture 12: OpenGL Transformation Li Zhang Spring 2008

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

Introduction to OpenGL

2/3/16. Interaction. Triangles (Clarification) Choice of Programming Language. Buffer Objects. The CPU-GPU bus. CSCI 420 Computer Graphics Lecture 3

Computer Graphics. OpenGL

Interaction. CSCI 420 Computer Graphics Lecture 3

Interaction Computer Graphics I Lecture 3

Books, OpenGL, GLUT, CUDA, OpenCL, OpenCV, PointClouds, G3D, and Qt

Lecture 2 CISC440/640 Spring Department of Computer and Information Science

Graphics Programming

Computer Graphics (Basic OpenGL)

Announcement. Homework 1 has been posted in dropbox and course website. Due: 1:15 pm, Monday, September 12

2a. The triangles scale increases (expands) when the 'e' key is pressed and decreases (contracts) when the 'c' key is pressed.

Graphics Programming. August 31, Programming of the Sierpinski gasket. Programming with OpenGL and C/C++

CS 543 Lecture 1 (Part 3) Prof Emmanuel Agu. Computer Science Dept. Worcester Polytechnic Institute (WPI)

Introduction to OpenGL: Part 2

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

Interaction. CSCI 480 Computer Graphics Lecture 3

Programming using OpenGL: A first Introduction

Lecture 2 2D transformations Introduction to OpenGL

CS 432 Interactive Computer Graphics

Computer Graphics 1 Computer Graphics 1

1.2 Basic Graphics Programming

Lecture 3 Advanced Computer Graphics (CS & SE )

Computer Graphics. Making Pictures. Computer Graphics CSC470 1

Announcements OpenGL. Computer Graphics. Autumn 2009 CS4815

COMPUTER GRAPHICS LAB # 3

Rendering. Part 1 An introduction to OpenGL

Announcements OpenGL. Computer Graphics. Spring CS4815

CS418 OpenGL & GLUT Programming Tutorial (I) Presented by : Wei-Wen Feng 1/30/2008

Computer Graphics Introduction to OpenGL

Programming with OpenGL Part 2: Complete Programs Computer Graphics I, Fall

to OpenGL Introduction Pipeline Graphics pipeline OpenGL pipeline OpenGL syntax Modeling Arrays Conclusion 1 Introduction Introduction to OpenGL

C OMPUTER G RAPHICS Thursday

Computer Graphics, Chapt 08

Cameras (and eye) Ideal Pinhole. Real Pinhole. Real + lens. Depth of field

Using OpenGL with CUDA

API for creating a display window and using keyboard/mouse interations. See RayWindow.cpp to see how these are used for Assignment3

Computer Graphics (CS 4731) OpenGL/GLUT(Part 1)

Image Processing. Geometry Processing. Reading: (Not really covered in our text. See Sects 18.1, 18.2.) Overview: Display

LECTURE 02 OPENGL API

1. Write a shader program that animates the morphing of Figure 'A' to Figure 'B' and back.

2. OpenGL -I. 2.1 What is OpenGL? Things OpenGL can do: -23-

cs123 Lab 3 OpenGL Part One 1 Introduction 2 OpenGL Basics 2.2 The Rendering Pipeline 2.1 The CPU and the GPU 2.3 Basic Syntax of OpenGL commands

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

Computer Graphics Primitive Attributes

Programming with OpenGL Part 3: Three Dimensions

Rendering Pipeline/ OpenGL

Programming with OpenGL Part 1: Background

Graphics Pipeline & APIs

SHADER PROGRAMMING. Based on Jian Huang s lecture on Shader Programming

Computer Graphics (CS 543) Lecture 3b: Shader Setup & GLSL Introduction

An Introduction to 3D Computer Graphics, Stereoscopic Image, and Animation in OpenGL and C/C++ Fore June

Duc Nguyen CSE 420 Computer Graphics 10/10/2018 Homework 1

Programming shaders & GPUs Christian Miller CS Fall 2011

Introduction to OpenGL Week 1

Objectives. Image Formation Revisited. Physical Approaches. The Programmer s Interface. Practical Approach. Introduction to OpenGL Week 1

Transcription:

Foundations of Computer Graphics Overview and Motivation This Lecture Introduction to OpenGL and simple demo code mytest1.cpp ; you compiled mytest3.cpp for HW 0 I am going to show (and write) actual code Code helps you understand HW 2 better Simple demo of mytest1 This lecture deals with very basic OpenGL setup. Next 2 lectures will likely be more interesting Introduction to OpenGL OpenGL is a graphics API Portable software library (platform-independent) Layer between programmer and graphics hardware Uniform instruction set (hides different capabilities) OpenGL can fit in many places Between application and graphics system Between higher level API and graphics system Why OpenGL? Why do we need OpenGL or an API? Encapsulates many basic functions of 2D/3D graphics Think of it as high-level language (C++) for graphics History: Introduced SGI in 92, maintained by Khronos Precursor for DirectX, WebGL, Java3D etc. Programmer s View Application Application Graphics Package OpenGL Application Programming Interface Hardware and software (graphics card) Output Device Input Device Input Device Slide inspired by Greg Humphreys Vertices Images OpenGL Rendering Pipeline Programmable in Modern GPUs (Vertex Shader) Geometry Primitive Pixel Scan Conversion (Rasterize) Texture Memory Programmable in Modern GPUs (Fragment Shader) Fragment Traditional Approach: Fixed function pipeline (state machine) New Development (2003-): Programmable pipeline Framebuffer 1

GPUs and Programmability Since 2003, can write vertex/pixel shaders Fixed function pipeline special type of shader Like writing C programs (see GLSL book) Performance >> CPU (even used for non-graphics) Operate in parallel on all vertices or fragments Outline Basic idea about OpenGL Basic setup and buffers Matrix modes Window system interaction and callbacks Drawing basic OpenGL primitives Initializing Shaders Foundations of Computer Graphics Basic Setup and Buffers, Matrix Modes Buffers and Window Interactions Buffers: Color (front, back, left, right), depth (z), accumulation, stencil. When you draw, you write to some buffer (most simply, front and depth) No window system interactions (for portability) But can use GLUT (or Motif, GLX, Tcl/Tk) Callbacks to implement mouse, keyboard interaction Basic setup code (you will likely copy) int main(int argc, char** argv) glutinit(&argc, argv); // Requests the type of buffers (Single, RGB). // Think about what buffers you would need... glutinitdisplaymode (GLUT_SINGLE GLUT_RGB); glutinitwindowsize (500, 500); glutinitwindowposition (100, 100); glutcreatewindow ("Simple Demo with Shaders"); glewinit(); init (); // Always initialize first // Now, we define callbacks and functions for various tasks.... Basic setup code (you will likely copy) int main(int argc, char** argv)... // Now, we define callbacks and functions for various tasks. glutdisplayfunc(display); glutreshapefunc(reshape) ; glutkeyboardfunc(keyboard); glutmousefunc(mouse) ; glutmotionfunc(mousedrag) ; glutmainloop(); // Start the main code return 0; /* ANSI C requires main to return int. */ 2

Outline Basic idea about OpenGL Basic setup and buffers Matrix modes Window system interaction and callbacks Drawing basic OpenGL primitives Viewing in OpenGL Viewing consists of two parts Object positioning: model view transformation matrix View projection: projection transformation matrix Old OpenGL (still supported), two matrix stacks GL_MODELVIEW_MATRIX, GL_PROJECTION_MATRIX Can push and pop matrices onto stacks New OpenGL: Use C++ STL templates to make stacks as needed e.g. stack <mat4> modelview ; modelview.push(mat4(1.0)) ; GLM libraries replace many deprecated commands. Include mat4 Initializing Shaders Viewing in OpenGL OpenGL s camera is always at the origin, pointing in the z direction Transformations move objects relative to the camera In old OpenGL, Matrices are column-major and right-multiply top of stack. (Last transform in code is first actually applied). In new GLM, it s confusing since matrices are row-order but still right-multiply (read the assignment notes and documentation). Basic initialization code for viewing #include <GL/glut.h> #include <stdlib.h> int mouseoldx, mouseoldy ; // For mouse motion GLdouble eyeloc = 2.0 ; // Where to look from; initially 0-2, 2 void init (void) /* select clearing color */ glclearcolor (0.0, 0.0, 0.0, 0.0); /* initialize viewing values */ glmatrixmode(gl_projection); glloadidentity(); // Think about this. Why is the up vector not normalized? glmatrixmode(gl_modelview) ; glloadidentity() ; glulookat(0,-eyeloc,eyeloc,0,0,0,0,1,1) ; // (To be cont d). Geometry and shader set up later... Foundations of Computer Graphics Window System Interaction and Callbacks Window System Interaction Not part of OpenGL Toolkits (GLUT) available Callback functions for events (similar to X, Java,) Keyboard, Mouse, etc. Open, initialize, resize window Our main func included glutdisplayfunc(display); glutreshapefunc(reshape) ; glutkeyboardfunc(keyboard); glutmousefunc(mouse) ; glutmotionfunc(mousedrag) ; 3

Basic window interaction code /* Defines what to do when various keys are pressed */ void keyboard (unsigned char key, int x, int y) switch (key) case 27: // Escape to quit exit(0) ; break ; default: break ; Basic window interaction code /* Reshapes the window appropriately */ void reshape(int w, int h) glviewport (0, 0, (GLsizei) w, (GLsizei) h); glmatrixmode(gl_projection); glloadidentity(); gluperspective(30.0, (GLdouble)w/(GLdouble)h, 1.0, 10.0) ; Mouse motion (demo) void mouse(int button, int state, int x, int y) if (button == GLUT_LEFT_BUTTON) if (state == GLUT_UP) // Do Nothing ; else if (state == GLUT_DOWN) mouseoldx = x ; mouseoldy = y ; // so we can move wrt x, y else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) // Reset glulookat eyeloc = 2.0 ; glmatrixmode(gl_modelview) ; glloadidentity() ; glulookat(0,-eyeloc,eyeloc,0,0,0,0,1,1) ; glutpostredisplay() ; Mouse drag (demo) void mousedrag(int x, int y) int yloc = y - mouseoldy ; // We will use the y coord to zoom in/out eyeloc += 0.005*yloc ; // Where do we look from if (eyeloc < 0) eyeloc = 0.0 ; mouseoldy = y ; /* Set the eye location */ glmatrixmode(gl_modelview) ; glloadidentity() ; glulookat(0,-eyeloc,eyeloc,0,0,0,0,1,1) ; glutpostredisplay() ; Foundations of Computer Graphics Drawing Basic OpenGL Primitives OpenGL Primitives Points Lines Polygon Triangle Quad Quad Strip Triangle Strip Triangle Fan 4

Geometry GLUT 3D Primitives Points (GL_POINTS) Stored in Homogeneous coordinates Line segments (GL_LINES) Polygons Simple, convex (take your chances with concave) Tessellate, GLU for complex shapes Rectangles: glrect Special cases (strips, loops, triangles, fans, quads) Cube Sphere More complex primitives (GLUT): Sphere, teapot, cube, Teapot Old OpenGL: Drawing Enclose vertices between glbegin() glend() pair Can include normal C code and attributes like the colors Inside are commands like glvertex3f, glcolor3f Attributes must be set before the vertex Assembly line (pass vertices, transform, shade) These are vertex, fragment shaders on current GPUs Immediate Mode: Sent to server and drawn Old OpenGL: Drawing in Display void display(void) glclear (GL_COLOR_BUFFER_BIT); // draw polygon (square) of unit length centered at the origin // This code draws each vertex in a different color. glbegin(gl_polygon); glcolor3f (1.0, 0.0, 0.0); glvertex3f (0.5, 0.5, 0.0); glcolor3f (0.0, 1.0, 0.0); glvertex3f (-0.5, 0.5, 0.0); glcolor3f (0.0, 0.0, 1.0); glvertex3f (-0.5, -0.5, 0.0); glcolor3f (1.0, 1.0, 1.0); glvertex3f (0.5, -0.5, 0.0); glend(); glflush () ; (-.5,.5) GREEN (-.5, -.5) BLUE (.5,.5) RED (.5, -.5) WHITE Old OpenGL: Drawing Client-Server model (client generates vertices, server draws) even if on same machine glflush() forces client to send network packet glfinish() waits for ack, sparingly use synchronization New OpenGL: Vertex Buffer Objects (next) Modern OpenGL: Floor Specification const GLfloat floorverts[4][3] = 0.5, 0.5, 0.0,-0.5, 0.5, 0.0,-0.5, -0.5, 0.0, 0.5, -0.5, 0.0 ; const GLfloat floorcol[4][3] = 1.0, 0.0, 0.0,0.0, 1.0, 0.0,0.0, 0.0, 1.0,1.0, 1.0, 1.0 ; const GLubyte floorinds[1][4] = 0, 1, 2, 3 ; const GLfloat floorverts2[4][3] = 0.5, 0.5, 1.0,-0.5, 0.5, 1.0,-0.5, -0.5, 1.0,0.5, -0.5, 1.0 ; const GLfloat floorcol2[4][3] = 1.0, 0.0, 0.0,1.0, 0.0, 0.0,1.0, 0.0, 0.0,1.0, 0.0, 0.0 ; const GLubyte floorinds2[1][4] = 0, 1, 2, 3 ; 5

Modern OpenGL: Vertex Buffer Objects const int numobjects = 2 ; // number of objects for buffer const int numperobj = 3 ; // Vertices, colors, indices GLuint buffers[numperobj] ; // List of buffers for geometric data GLuint objects[numobjects]; // For each object GLenum PrimType[numobjects];// Primitive Type (quads, polygons) GLsizei NumElems[numobjects] ; // Number of geometric elements // Floor Geometry is specified with a vertex array // The Buffer Offset Macro is from Red Book, page 103, 106 // Note for more complex objects the indices must be integers, not bytes. #define BUFFER_OFFSET(bytes) ((GLubyte *) NULL + (bytes)) #define NumberOf(array) (sizeof(array)/sizeof(array[0])) enum Vertices, Colors, Elements ; // For arrays for object enum FLOOR, FLOOR2 ; // For objects, for the floor Modern OpenGL: Initialize Buffers void initobject (GLuint object, GLfloat * vert, GLint sizevert, GLfloat * col, GLint sizecol, GLubyte * inds, GLint sizeind, GLenum type) int offset = object * numperobj ; glbindbuffer(gl_array_buffer, buffers[vertices+offset]) ; glbufferdata(gl_array_buffer, sizevert, vert,gl_static_draw); glvertexpointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)) ; glenableclientstate(gl_vertex_array) ; glbindbuffer(gl_array_buffer, buffers[colors+offset]) ; glbufferdata(gl_array_buffer, sizecol, col,gl_static_draw); glcolorpointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)) ; glenableclientstate(gl_color_array) ; glbindbuffer(gl_element_array_buffer, buffers[elements+offset]) ; glbufferdata(gl_element_array_buffer, sizeind, inds,gl_static_draw); PrimType[object] = type ; NumElems[object] = sizeind ; Modern OpenGL: Draw Vertex Object void drawobject(gluint object) int offset = object * numperobj ; glbindbuffer(gl_array_buffer, buffers[vertices+offset]) ; glvertexpointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)) ; glenableclientstate(gl_vertex_array) ; glbindbuffer(gl_array_buffer, buffers[colors+offset]) ; glcolorpointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0)) ; glenableclientstate(gl_color_array) ; glbindbuffer(gl_element_array_buffer, buffers[elements+offset]) ; gldrawelements(primtype[object], NumElems[object], GL_UNSIGNED_BYTE, BUFFER_OFFSET(0)) ; void display(void) glclear (GL_COLOR_BUFFER_BIT); drawobject(floor) ; drawobject(floor2) glflush (); Initialization for Drawing, Shading #include "shaders.h" GLuint vertexshader, fragmentshader, shaderprogram ; // shaders // Initialization in init() for Drawing glgenbuffers(numperobj*numobjects, buffers) ; initobject(floor, (GLfloat *) floorverts, sizeof(floorverts), (GLfloat *) floorcol, sizeof (floorcol), (GLubyte *) floorinds, sizeof (floorinds), GL_POLYGON) ; initobject(floor2, (GLfloat *) floorverts2, sizeof(floorverts2), (GLfloat *) floorcol2, sizeof (floorcol2), (GLubyte *) floorinds2, sizeof (floorinds2), GL_POLYGON) ; // In init() for Shaders, discussed next vertexshader = initshaders(gl_vertex_shader, "shaders/nop.vert") ; fragmentshader = initshaders(gl_fragment_shader, "shaders/nop.frag") ; shaderprogram = initprogram(vertexshader, fragmentshader) ; Demo (change colors) Foundations of Computer Graphics Initializing Shaders 6

Vertices Images OpenGL Rendering Pipeline Programmable in Modern GPUs (Vertex Shader) Geometry Primitive Pixel Scan Conversion (Rasterize) Texture Memory Programmable in Modern GPUs (Fragment Shader) Fragment Traditional Approach: Fixed function pipeline (state machine) New Development (2003-): Programmable pipeline Framebuffer Simplified OpenGL Pipeline User specifies vertices (vertex buffer object) For each vertex in parallel OpenGL calls user-specified vertex shader: Transform vertex (ModelView, Projection), other ops For each primitive, OpenGL rasterizes Generates a fragment for each pixel the fragment covers For each fragment in parallel OpenGL calls user-specified fragment shader: Shading and lighting calculations OpenGL handles z-buffer depth test unless overwritten Shader Setup Initializing (shader itself discussed later) 1. Create shader (Vertex and Fragment) 2. Compile shader 3. Attach shader to program 4. Link program 5. Use program Shader Setup Shader source is just sequence of strings Similar steps to compile a normal program Shader Initialization Code GLuint initshaders (GLenum type, const char *filename) // Using GLSL shaders, OpenGL book, page 679 GLuint shader = glcreateshader(type) ; GLint compiled ; string str = textfileread (filename) ; GLchar * cstr = new GLchar[str.size()+1] ; const GLchar * cstr2 = cstr ; // Weirdness to get a const char strcpy(cstr,str.c_str()) ; glshadersource (shader, 1, &cstr2, NULL) ; glcompileshader (shader) ; glgetshaderiv (shader, GL_COMPILE_STATUS, &compiled) ; if (!compiled) shadererrors (shader) ; throw 3 ; return shader ; Linking Shader Program GLuint initprogram (GLuint vertexshader, GLuint fragmentshader) GLuint program = glcreateprogram() ; GLint linked ; glattachshader(program, vertexshader) ; glattachshader(program, fragmentshader) ; gllinkprogram(program) ; glgetprogramiv(program, GL_LINK_STATUS, &linked) ; if (linked) gluseprogram(program) ; else programerrors(program) ; throw 4 ; return program ; 7

Basic (nop) vertex shader In shaders/ nop.vert.glsl nop.frag.glsl Written in GLSL (GL Shading Language) Vertex Shader (out values interpolated to fragment) # version 120 // Mine is an old machine. For version 130 or higher, do // out vec4 color ; // That is certainly more modern varying vec4 color ; void main() gl_position = gl_projectionmatrix * gl_modelviewmatrix * gl_vertex ; color = gl_color ; Basic (nop) fragment shader # version 120 // Mine is an old machine. For version 130 or higher, do // in vec4 color ; // That is certainly more modern attribute vec4 color ; void main (void) gl_fragcolor = color ; 8