Movatterモバイル変換


[0]ホーム

URL:


PDF, PPTX651 views

Computer Graphics - Lecture 01 - 3D Programming I

Here are a few key points about adding vertex colors to the example:- Storing the color data in a separate buffer is cleaner than concatenating or interleaving it with the position data. This keeps the data layout simple.- The vertex shader now has inputs for both the position (vp) and color (vc) attributes. - The color is passed through as an output (fcolour) to the fragment shader. - The position is still used to set gl_Position for transformation.- The color input has to start in the vertex shader because that is where per-vertex attributes like color are interpolated across the primitive before being sampled in the fragment shader. The vertex shader interpolates the color value

Related topics:

Embed presentation

Download as PDF, PPTX
3d Programming IDr Anton Gerdelangerdela@scss.tcd.ie
3d Programming●3d programming is very difficult●3d programming is very time consuming
3d Programming●Practical knowledge of the latest, low-levelgraphics APIs is very valuable (CV)●Good grasp of basic concepts in this semester●Caveat - You must keep API knowledge up-to-date or it becomes redundant
Essential Checklist✔always have a pencil and paper✔solve your problem before you start coding✔know how to compile and link against libraries✔know how to use memory, pointers, addresses✔understand the hardware pipeline✔make a 3d maths cheat sheet✔do debugging (visual and programmatic)✔print the Quick Reference Card for OpenGL✔start assignments ASAP
Quick Background●What is a vertex?●Modern graphics hardware is able to draw:– triangles– points– lines (unofficially deprecated)●How do we define these?●What is a normal?
OpenGL●Open Grapics Library - originally the IrisGL by SGI●Managed by Khronos Group{lots of big hw and sw companies}●Vector graphics●Only the spec. is sort-of open●Various implementations, lots of platforms●C API + driver + GLSL shaders●All the APIs do the same jobs on hardware, but presentdifferent interfaces
OpenGL Caveats●OpenGL has a very clunky old-fashioned C interface thatwill definitely confuse●OpenGL has been modernised but there is a lot of left-over “cruft” that you shouldn't use●Print the Quick Reference Card and double-checkeverything that you use.http://www.opengl.org/sdk/docs/●The naming conventions are very confusing●OpenGL is currently being completely re-written toaddress these problems●I'll try to help steer around these issues - use thediscussion boards if unsure!
OpenGL Global State Machine●The OpenGL interface uses an architecture called a“global state machine”●Instead of doing this sort of thing:Mesh myMesh;myMesh.setData (some_array);opengl.drawMesh (myMesh);●in a G.S.M. we do this sort of thing [pseudo-code]:unsigned int mesh_handle;glGenMesh (&mesh_handle); // okay so far, just C styleglBindMesh (mesh_handle); // my mesh is now “the” mesh// affects most recently “bound” meshglMeshData (some_array);●How this might cause a problem later?
OpenGL Global State Machine●Operations affect the currently “bound” object●Be very careful. Write long functions.●Can sometimes “unbind” by binding to 0 (no object)●Operations “enable” states likeblending/transparency●They affect all subsequently drawn things●Don't forget to “disable” things●Can get messy in larger programmes●Write long functions.
Graphics API Architecture●Set-up and rendering loop runon CPU●Copy mesh data to buffers ingraphics hardware memory●Write shaders to draw on GPU(graphics processing unit)●CPU command queuesdrawing on GPU with thisshader, and that mesh data●CPU and GPU then runasychronously
Before We Look at Code●OpenGL functions precededby “gl...()”●OpenGL data types precededby “GL...”●OpenGL constants preceededby “GL_...”●Find each feature used in manpageshttp://www.opengl.org/sdk/docs/man/●Parameters, related functions
Walk-Through “Hello Triangle”●Upgrade graphics drivers to download latest OpenGLlibraries●GLEW or GL3W - extensions and newest GL.h●GLFW or FreeGLUT or SDL or Qt - OS window/context
Start GLFW (or FreeGLUT)●Start GLFW●We use GLFW to start an OpenGL context●Can use FreeGLUT, SDL, Qt, etc. Instead●Can also do manually, but ugly
Hint to Use a Specific OpenGL Version●Leave commented the first time, it will try to run latest v.●We can print this out to see what you have on the machine●Uncomment and specify to force a specific version (good,safe practice)●CORE and FORWARD mean “don't allow any old, deprecatedstuff”●Apple only has 3.2 and 4.1? core, forward implemented
Create a Window on the OS●GLFW/FreeGLUT etc. do this in a platform-independent way●Tie OpenGL context to the window●Refer to GLFW docs for each function
Start GLEW (or GL3W)●Windows has a 1992? Microsoft gl.h in the system folder●Makes sure you are using the latest gl.h●Makes extensions available (experimental/new featureplug-ins)●Ask OpenGL to print the version running (check in console)●3.2+ is fine for this course
Create Vertex Points
Create Vertex Buffer Object (VBO)●We copy our array of points from RAM tographics memory●Note “binding” idea●The vbo variable is just an unsigned integer thatGL will give an unique ID to
Create Vertex Array Object (VAO)●“What” to draw●Meta-data with “attribute” pointer that sayswhat data from a VBO to use for a shader inputvariable
Vertex Shader and Fragment Shader Strings●“How” to draw (style)●Set vertex positions in range -1 to 1 on X,Y,Z●gl_Position is the built-in variable to use for final position●Colour in RGBA (red blue green alpha) range 0.0 to 1.0●Like C but more data types.
Compile and Link Shaders●Compile each shader●Attach to shader program (another bad naming convention)●Link the program●Should check compile and linking logs for errors
Drawing Loop●Clear drawing buffer {colour, depth}●“Use” our shader program●“Bind” our VAO●Draw triangles. Start at point 0. Use 3 points. How many triangles?●Swap buffers. Why?
Terminate●Makes sure window closes if your loop finishes first●Compile, link against GLEW and GLFW and OpenGL●VS Template on Blackboard●Makefiles for Linux/Mac/Windowshttps://github.com/capnramses/antons_opengl_tutorials_book/●Don't get stuck on linking/projects - start fiddling now!
“Hello Triangle”●Getting GL started is alot of work●“If you can draw 1triangle, you can draw1000000”●Go through sometutorials
Pause and Review●What are the main components of a modern 3dgraphics programme?●Where do we store mesh data (vertex points)?●In what?●How do we define the format of the data?●What do we need to do before we tell OpenGLto draw with glDrawArrays() etc.?
Things to Think About or Try●Can we change the colour of the triangle drawn?●How can we extend the triangle into a square?●Could we load mesh data from a file rather thanan array?●Shaders can be loaded from files. If you changea shader in an external file, do you need to re-compile?●How would you draw a second, separate shape?
3d Programming IPart B
Graphics System Architecture●move data to graphics hardware before drawing●minimise use of the bus
Asynchronous Processing●Minimise CPU-GPU bus comm. Overhead●Maximise parallel processing to reduce overall GPU time●“Client” gl commands queue up and wait to be run on GPU●Can glFlush() to say “hurry up, I'm waiting” and glFinish() toactually wait – don't normally need to use these
Closer Look at Shaders
GPU Parallelism●1 vertex = 1 shader = 1 core●1 fragment = 1 shader = 1 core●but drawing operations serialise●.: 1 big mesh draw is faster than many small drawsGPU Uniform Shader CoresGeForce 605 48Radeon HD 7350 80GeForce GTX 580 512Radeon HD 8750 768GeForce GTX 690 1536Radeon HD 8990 2304
●minimum:– vertex shader– fragment shader●also have GPGPU“compute” shadersnow●note: Direct3D hwpipeline is the same,but different names
Difference Between Fragment and Pixels●Pixel = “picture element”●Fragment = pixel-sized area of a surface●Each triangle is divided into fragments onrasterisation●All fragments are drawn, even the obscured ones*●If depth testing is enabled closer fragments aredrawn over farther-away fragments●.: Huge #s of redundant FS may be executed
Shader LanguageOpenGL Version GLSL Version Tag1.2 none none2.0 1.10.59 #version 1102.1 1.20.8 #version 1203.0 1.30.10 #version 1303.1 1.40.08 #version 1403.2 1.50.11 #version 1503.3 3.30.6 #version 3304.0 4.00.9 #version 4004.1 4.10.6 #version 4104.2 4.20.6 #version 4204.3 4.30.6 #version 4304.4 ... #version 440... ... ...
GLSL Operators and Data Types●Same operators as C●no pointers●bit-wise operators since v 1.30data type detail common usevoid same as C functions that do notreturn a valuebool, int, float same as Cvec2, vec3, vec4 2d, 3d, 4d floating point points and direction vectorsmat2, mat3, mat4 2x2, 3x3, 4x4 f.p. matrices transforming points,vectorssampler2D 2d texture texture mappingsamplerCube 6-sided texture sky boxessampler2DShadow shadow projected textureivec3 etc. integer versions
File Naming Convention●Upgarde the template – load shader strings from text files●post-fix with– .vert - vetex shader– .frag - fragment shader– .geom - geometry shader– .comp - compute shader– .tesc - tessellation control shader– .tese - tessellation evaluation shader●allows you to use a tool like Glslang reference compiler tocheck for [obvious] errors
Example Vertex Shader#version 400in vec3 vertex_position;void main() {gl_Position = vec4 (vertex_position, 1.0);}●Macro to explicitly set GLSL version required. Can also use #defines●in keyword – variable from previous stage in pipeline.Q. What is the stage before the vertex shader?●vec3 - 3d vector. Store positions, directions, or colours.●Every shader has a main() entry point as in C.... contd.
Example Vertex Shader#version 400in vec3 vertex_position;void main() {gl_Position = vec4 (vertex_position, 1.0);}●vec4 - has 4th component. gl_Position uses it to determineperspective. Set by virtual cameras. For now leave at 1.0 - "don'tcalculate any perspective".●Can also use out keyword to send variable to next stage.Q. What is the next stage?●Every VS positions one vertex between -1:1,-1:1,-1:1.Q. How does every vertex end up in a different positionthen?
●minimum:– vertex shader– fragment shader●also have GPGPU“compute” shadersnow●note: Direct3D hwpipeline is the same,but different names
Example Fragment Shader#version 400uniform vec4 inputColour;out vec4 fragColour;void main() {fragColour = inputColour;}●What important pipeline process happens first?●A uniform variable is a way to communicate to shaders from the mainapplication in C●For each fragment set a vec4 to RGBA (range 0.0 to 1.0)Q. What is the next stage? Where does out go?Q. What can the alpha channel do?
Uniforms// do this once, after linking the shader p. not in the main loopint inputColour_loc = glGetUniformLocation (my_shader_program, “inputColour”);if (inputColour_loc < 0) {fprintf (stderr, “ERROR inputColour variable not found. Invalid uniformn”);do something rash;}// do this whenever you want to change the colour used by this shader programglUseProgram (my_shader_program);glUniform4f (inputColour_loc, 0.5f, 0.5f, 1.0f, 1.0f);●Uniforms are 0 by default i.e. our colour=black●Unused uniforms are optimised out by shader compiler●Basic uniforms are specific and persistent to one shader programme●Uniforms are available to all shaders in programme●Uniforms are a constant value in all shaders●You can change a uniform once, every frame, or whenever you like●Keep uniform updates to a minimum (don't flood the bus)
Adding Error-Checking Functionality●After calling glCompileShader()– Check GL_COMPILE_STATUS with glGetShaderiv()– If failed, get the log from glGetShaderInfoLog() and print it!●After calling glLinkProgram()– Check GL_LINK_STATUS with glGetProgramiv()– Get the log from glGetProgramInfoLog() and print it!●Check out the man-pages to find out how to use thesefunctions.●Add this to your projects! It gives you basic error checkingwith the line numbers.
Shadertoy●WebGL tool to experiment with shaderson-the-fly●implement entirely in a fragment shaderhttps://www.shadertoy.com/
Example: Adding Vertex Colours
Data Layout Options●We could:– Concatenate colour data onto the end of our pointsbuffer:array = XYZXYZXYZRGBRGBRGB– Interleave colours between points:array = XYZRGBXYZRGBXYZRGB– Just create a new array and new vertex bufferobjectarray1 = XYZXYZXYZ array2 = RGBRGBRGB
Second ArrayGLfloat points[] = {0.0f, 0.5f, 0.0f,0.5f, -0.5f, 0.0f,-0.5f, -0.5f, 0.0f};GLfloat colours[] = {1.0f, 0.0f, 0.0f,0.0f, 1.0f, 0.0f,0.0f, 0.0f, 1.0f};
Second VBOGLuint points_vbo = 0;glGenBuffers (1, &points_vbo);glBindBuffer (GL_ARRAY_BUFFER, points_vbo);glBufferData (GL_ARRAY_BUFFER, sizeof (points),points, GL_STATIC_DRAW);GLuint colours_vbo = 0;glGenBuffers (1, &colours_vbo);glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);glBufferData (GL_ARRAY_BUFFER, sizeof (colours),colours, GL_STATIC_DRAW);
Tell the VAO where to get 2ndvariableGLuint vao;glGenVertexArrays (1, &vao);glBindVertexArray (vao);glEnableVertexAttribArray (0);glBindBuffer (GL_ARRAY_BUFFER, points_vbo);glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);glEnableVertexAttribArray (1);glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);Second shader inputvariableStill a vec3Change these 2variables if interleavedor concatenated inone VBO
Modify Vertex Shader#version 400layout (location=0) in vec3 vp; // pointlayout (location=1) in vec3 vc; // colourout vec3 fcolour;void main () {fcolour = point; // “pass-through” outputgl_Position = vec4 (vp, 1.0);}Q. Why does the colour input have to start in the vertexshader?
Modify the Fragment Shader#version 400in vec3 fcolour;out vec4 frag_colour;void main () {frag_colour = vec4 (fcolour, 1.0);}Q. There are more fragments than vertices. What values willfcolour have in each fragment?
Interpolation
Drawing Modes●Points can be scaled●Lines are deprecatedbut still sort-of work●How would youchange your trianglesto an edgeswireframe?
Winding Order and Back-Face Culling●Easy optimisation – don't waste time drawing theback face or inside-facing parts of a mesh●How do we define the “front” and “back”●= order that points are given●Clock-wise order or Counter clock-wiseglEnable (GL_CULL_FACE); // cull faceglCullFace (GL_BACK); // cull back faceglFrontFace (GL_CW); // usually front is CCW

Recommended

PPSX
Vertex Shader Tricks by Bill Bilodeau - AMD at GDC14
PPTX
4K Checkerboard in Battlefield 1 and Mass Effect Andromeda
PDF
Precomputed Voxelized-Shadows for Large-scale Scene and Many lights
PPTX
Terrain in Battlefield 3: A Modern, Complete and Scalable System
PDF
Forward+ (EUROGRAPHICS 2012)
PDF
Siggraph2016 - The Devil is in the Details: idTech 666
PPTX
Shiny PC Graphics in Battlefield 3
PPTX
3D Display Method
PPTX
Approaching zero driver overhead
PPTX
Parallel Futures of a Game Engine (v2.0)
 
PPT
Frostbite Rendering Architecture and Real-time Procedural Shading & Texturing...
 
PDF
Computer Graphics - Lecture 00 - Introduction
PDF
Shaders in Unity
PPTX
Parallel Futures of a Game Engine
 
PDF
Lighting Shading by John Hable
PDF
Bindless Deferred Decals in The Surge 2
PPTX
Yolo
PPTX
Window to Viewport Transformation in Computer Graphics with.pptx
PPT
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
 
PPTX
Mid point line Algorithm - Computer Graphics
PDF
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
PPTX
Input of graphical data
PPTX
Window to viewport transformation&amp;matrix representation of homogeneous co...
PDF
DirectStroage프로그래밍소개
PPT
Introduction to Data Oriented Design
PPTX
The Rendering Technology of Killzone 2
PPTX
Curve clipping
PDF
The Guerrilla Guide to Game Code
PDF
Opengl basics
PPTX
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
byICS
 

More Related Content

PPSX
Vertex Shader Tricks by Bill Bilodeau - AMD at GDC14
PPTX
4K Checkerboard in Battlefield 1 and Mass Effect Andromeda
PDF
Precomputed Voxelized-Shadows for Large-scale Scene and Many lights
PPTX
Terrain in Battlefield 3: A Modern, Complete and Scalable System
PDF
Forward+ (EUROGRAPHICS 2012)
PDF
Siggraph2016 - The Devil is in the Details: idTech 666
PPTX
Shiny PC Graphics in Battlefield 3
PPTX
3D Display Method
Vertex Shader Tricks by Bill Bilodeau - AMD at GDC14
4K Checkerboard in Battlefield 1 and Mass Effect Andromeda
Precomputed Voxelized-Shadows for Large-scale Scene and Many lights
Terrain in Battlefield 3: A Modern, Complete and Scalable System
Forward+ (EUROGRAPHICS 2012)
Siggraph2016 - The Devil is in the Details: idTech 666
Shiny PC Graphics in Battlefield 3
3D Display Method

What's hot

PPTX
Approaching zero driver overhead
PPTX
Parallel Futures of a Game Engine (v2.0)
 
PPT
Frostbite Rendering Architecture and Real-time Procedural Shading & Texturing...
 
PDF
Computer Graphics - Lecture 00 - Introduction
PDF
Shaders in Unity
PPTX
Parallel Futures of a Game Engine
 
PDF
Lighting Shading by John Hable
PDF
Bindless Deferred Decals in The Surge 2
PPTX
Yolo
PPTX
Window to Viewport Transformation in Computer Graphics with.pptx
PPT
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
 
PPTX
Mid point line Algorithm - Computer Graphics
PDF
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
PPTX
Input of graphical data
PPTX
Window to viewport transformation&amp;matrix representation of homogeneous co...
PDF
DirectStroage프로그래밍소개
PPT
Introduction to Data Oriented Design
PPTX
The Rendering Technology of Killzone 2
PPTX
Curve clipping
PDF
The Guerrilla Guide to Game Code
Approaching zero driver overhead
Parallel Futures of a Game Engine (v2.0)
 
Frostbite Rendering Architecture and Real-time Procedural Shading & Texturing...
 
Computer Graphics - Lecture 00 - Introduction
Shaders in Unity
Parallel Futures of a Game Engine
 
Lighting Shading by John Hable
Bindless Deferred Decals in The Surge 2
Yolo
Window to Viewport Transformation in Computer Graphics with.pptx
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
 
Mid point line Algorithm - Computer Graphics
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Input of graphical data
Window to viewport transformation&amp;matrix representation of homogeneous co...
DirectStroage프로그래밍소개
Introduction to Data Oriented Design
The Rendering Technology of Killzone 2
Curve clipping
The Guerrilla Guide to Game Code

Similar to Computer Graphics - Lecture 01 - 3D Programming I

PDF
Opengl basics
PPTX
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
byICS
 
PDF
Introduction of openGL
PPTX
Opengl presentation
PPTX
OpenGL basics
PDF
lectureAll-OpenGL-complete-Guide-Tutorial.pdf
PPT
PPT
CS 354 Programmable Shading
PPT
CS 354 Viewing Stuff
PPTX
3 CG_U1_P2_PPT_3 OpenGL.pptx
PPTX
UNIT 1 OPENGL_UPDATED .pptx
PDF
GL Shading Language Document by OpenGL.pdf
PPT
Introduction to OpenGL modern OpenGL program
PDF
Open gl basics
PPT
Advanced Graphics Workshop - GFX2011
PDF
Android open gl2_droidcon_2014
PDF
Open gl
PPT
september11.ppt
PPTX
Opengl lec 3
Opengl basics
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
byICS
 
Introduction of openGL
Opengl presentation
OpenGL basics
lectureAll-OpenGL-complete-Guide-Tutorial.pdf
CS 354 Programmable Shading
CS 354 Viewing Stuff
3 CG_U1_P2_PPT_3 OpenGL.pptx
UNIT 1 OPENGL_UPDATED .pptx
GL Shading Language Document by OpenGL.pdf
Introduction to OpenGL modern OpenGL program
Open gl basics
Advanced Graphics Workshop - GFX2011
Android open gl2_droidcon_2014
Open gl
september11.ppt
Opengl lec 3

Recently uploaded

PDF
DEFINITION OF COMMUNITY Sociology. .pdf
PDF
Digital Electronics – Registers and Their Applications
PDF
বাংলাদেশ অর্থনৈতিক সমীক্ষা - ২০২৫ with Bookmark.pdf
PPTX
Finals - History and Geography Quiz - Around the World in 80 Questions - IITK
PDF
Past Memories and a New World: Photographs of Stoke Newington from the 70s, 8...
PDF
AI Chatbots and Prompt Engineering - by Ms. Oceana Wong
PPTX
Chapter 3. Pharmaceutical Aids (pharmaceutics)
PDF
1. Doing Academic Research: Problems and Issues, 2. Academic Research Writing...
PDF
ASRB NET 2025 Paper GENETICS AND PLANT BREEDING ARS, SMS & STODiscussion | Co...
PDF
CXC-AD Associate Degree Handbook (Revised)
PPT
n-1-PMES-Guidelines-for-SY-2025-2026.ppt
PPTX
Time Series Analysis - Method of Simple Moving Average 3 Year and 4 Year Movi...
PDF
UGC NET Paper 1 Syllabus | 10 Units Complete Guide for NTA JRF
PPTX
Elderly in India: The Changing Scenario.pptx
 
PDF
Rigor, ethics, wellbeing and resilience in the biomedical doctoral journey
 
PPTX
Declaration of Helsinki Basic principles in medical research ppt.pptx
PPTX
Masterclass on Cybercrime, Scams & Safety Hacks.pptx
PPTX
Organize order into course in Odoo 18.2 _ Odoo 19
PPTX
Session 5 Overview of the PPST and Its Indicators (COI and NCOI).pptx
PDF
Photoperiod Classification of Vegetable Plants.pdf
DEFINITION OF COMMUNITY Sociology. .pdf
Digital Electronics – Registers and Their Applications
বাংলাদেশ অর্থনৈতিক সমীক্ষা - ২০২৫ with Bookmark.pdf
Finals - History and Geography Quiz - Around the World in 80 Questions - IITK
Past Memories and a New World: Photographs of Stoke Newington from the 70s, 8...
AI Chatbots and Prompt Engineering - by Ms. Oceana Wong
Chapter 3. Pharmaceutical Aids (pharmaceutics)
1. Doing Academic Research: Problems and Issues, 2. Academic Research Writing...
ASRB NET 2025 Paper GENETICS AND PLANT BREEDING ARS, SMS & STODiscussion | Co...
CXC-AD Associate Degree Handbook (Revised)
n-1-PMES-Guidelines-for-SY-2025-2026.ppt
Time Series Analysis - Method of Simple Moving Average 3 Year and 4 Year Movi...
UGC NET Paper 1 Syllabus | 10 Units Complete Guide for NTA JRF
Elderly in India: The Changing Scenario.pptx
 
Rigor, ethics, wellbeing and resilience in the biomedical doctoral journey
 
Declaration of Helsinki Basic principles in medical research ppt.pptx
Masterclass on Cybercrime, Scams & Safety Hacks.pptx
Organize order into course in Odoo 18.2 _ Odoo 19
Session 5 Overview of the PPST and Its Indicators (COI and NCOI).pptx
Photoperiod Classification of Vegetable Plants.pdf
In this document
Powered by AI

Dr. Anton Gerdelan introduces 3D programming, emphasizing its difficulty and time requirements. Knowledge of graphics APIs and basic concepts is essential to prevent obsolescence.

Key practices include problem-solving before coding, understanding memory management, debugging, and knowing the hardware graphics pipeline.

Covers vertices in modern graphics hardware, detailing OpenGL's management, its C interface limitations, and the need for up-to-date practices.

Explains the global state machine architecture, cautioning on how binding and unbinding can complicate functions affecting drawn objects.

Discussion on CPU/GPU interactions, rendering loops, and OpenGL function naming conventions for programming.

Describes the use of GLFW and GLEW for creating OpenGL contexts, hinting at proper version usage for compatibility.

Steps for creating vertex points, vertex buffer objects (VBOs), and vertex array objects (VAOs), instrumental for drawing operations.

Introduces vertex and fragment shaders, their functions, and the importance of the drawing loop in OpenGL applications.

Discusses program termination protocols, how to start projects with templates, and the effort involved in basic shapes like triangles.

Explores main components of a 3D graphics program, including data storage and definition, crucial prior to utilizing drawing functions.

Encourages experimentation with colors, geometry, load methods, and reviews graphics system architecture and asynchronous processing.

Analyzes GPU parallelism, the difference between fragments and pixels, shader languages, and GLSL versions with operators.

Establishes file naming conventions for shaders and presents examples of vertex shaders with explanations about their components.

Presents a fragment shader example with discussions on uniforms, their importance, and error-checking functionality in shader programming.

Introduces Shadertoy for shader experimentation and various data layout options for managing vertex and color data.

Covers creating second VBOs for color data, establishing relationships in VAOs for multi-variable handling in shaders.

Details modifications in vertex and fragment shaders, interpolation in graphics rendering, and techniques for optimizing mesh drawing.

Computer Graphics - Lecture 01 - 3D Programming I

  • 1.
    3d Programming IDrAnton Gerdelangerdela@scss.tcd.ie
  • 2.
    3d Programming●3d programmingis very difficult●3d programming is very time consuming
  • 3.
    3d Programming●Practical knowledgeof the latest, low-levelgraphics APIs is very valuable (CV)●Good grasp of basic concepts in this semester●Caveat - You must keep API knowledge up-to-date or it becomes redundant
  • 4.
    Essential Checklist✔always havea pencil and paper✔solve your problem before you start coding✔know how to compile and link against libraries✔know how to use memory, pointers, addresses✔understand the hardware pipeline✔make a 3d maths cheat sheet✔do debugging (visual and programmatic)✔print the Quick Reference Card for OpenGL✔start assignments ASAP
  • 5.
    Quick Background●What isa vertex?●Modern graphics hardware is able to draw:– triangles– points– lines (unofficially deprecated)●How do we define these?●What is a normal?
  • 10.
    OpenGL●Open Grapics Library- originally the IrisGL by SGI●Managed by Khronos Group{lots of big hw and sw companies}●Vector graphics●Only the spec. is sort-of open●Various implementations, lots of platforms●C API + driver + GLSL shaders●All the APIs do the same jobs on hardware, but presentdifferent interfaces
  • 11.
    OpenGL Caveats●OpenGL hasa very clunky old-fashioned C interface thatwill definitely confuse●OpenGL has been modernised but there is a lot of left-over “cruft” that you shouldn't use●Print the Quick Reference Card and double-checkeverything that you use.http://www.opengl.org/sdk/docs/●The naming conventions are very confusing●OpenGL is currently being completely re-written toaddress these problems●I'll try to help steer around these issues - use thediscussion boards if unsure!
  • 12.
    OpenGL Global StateMachine●The OpenGL interface uses an architecture called a“global state machine”●Instead of doing this sort of thing:Mesh myMesh;myMesh.setData (some_array);opengl.drawMesh (myMesh);●in a G.S.M. we do this sort of thing [pseudo-code]:unsigned int mesh_handle;glGenMesh (&mesh_handle); // okay so far, just C styleglBindMesh (mesh_handle); // my mesh is now “the” mesh// affects most recently “bound” meshglMeshData (some_array);●How this might cause a problem later?
  • 13.
    OpenGL Global StateMachine●Operations affect the currently “bound” object●Be very careful. Write long functions.●Can sometimes “unbind” by binding to 0 (no object)●Operations “enable” states likeblending/transparency●They affect all subsequently drawn things●Don't forget to “disable” things●Can get messy in larger programmes●Write long functions.
  • 14.
    Graphics API Architecture●Set-upand rendering loop runon CPU●Copy mesh data to buffers ingraphics hardware memory●Write shaders to draw on GPU(graphics processing unit)●CPU command queuesdrawing on GPU with thisshader, and that mesh data●CPU and GPU then runasychronously
  • 15.
    Before We Lookat Code●OpenGL functions precededby “gl...()”●OpenGL data types precededby “GL...”●OpenGL constants preceededby “GL_...”●Find each feature used in manpageshttp://www.opengl.org/sdk/docs/man/●Parameters, related functions
  • 16.
    Walk-Through “Hello Triangle”●Upgradegraphics drivers to download latest OpenGLlibraries●GLEW or GL3W - extensions and newest GL.h●GLFW or FreeGLUT or SDL or Qt - OS window/context
  • 17.
    Start GLFW (orFreeGLUT)●Start GLFW●We use GLFW to start an OpenGL context●Can use FreeGLUT, SDL, Qt, etc. Instead●Can also do manually, but ugly
  • 18.
    Hint to Usea Specific OpenGL Version●Leave commented the first time, it will try to run latest v.●We can print this out to see what you have on the machine●Uncomment and specify to force a specific version (good,safe practice)●CORE and FORWARD mean “don't allow any old, deprecatedstuff”●Apple only has 3.2 and 4.1? core, forward implemented
  • 19.
    Create a Windowon the OS●GLFW/FreeGLUT etc. do this in a platform-independent way●Tie OpenGL context to the window●Refer to GLFW docs for each function
  • 20.
    Start GLEW (orGL3W)●Windows has a 1992? Microsoft gl.h in the system folder●Makes sure you are using the latest gl.h●Makes extensions available (experimental/new featureplug-ins)●Ask OpenGL to print the version running (check in console)●3.2+ is fine for this course
  • 21.
  • 22.
    Create Vertex BufferObject (VBO)●We copy our array of points from RAM tographics memory●Note “binding” idea●The vbo variable is just an unsigned integer thatGL will give an unique ID to
  • 23.
    Create Vertex ArrayObject (VAO)●“What” to draw●Meta-data with “attribute” pointer that sayswhat data from a VBO to use for a shader inputvariable
  • 24.
    Vertex Shader andFragment Shader Strings●“How” to draw (style)●Set vertex positions in range -1 to 1 on X,Y,Z●gl_Position is the built-in variable to use for final position●Colour in RGBA (red blue green alpha) range 0.0 to 1.0●Like C but more data types.
  • 25.
    Compile and LinkShaders●Compile each shader●Attach to shader program (another bad naming convention)●Link the program●Should check compile and linking logs for errors
  • 26.
    Drawing Loop●Clear drawingbuffer {colour, depth}●“Use” our shader program●“Bind” our VAO●Draw triangles. Start at point 0. Use 3 points. How many triangles?●Swap buffers. Why?
  • 27.
    Terminate●Makes sure windowcloses if your loop finishes first●Compile, link against GLEW and GLFW and OpenGL●VS Template on Blackboard●Makefiles for Linux/Mac/Windowshttps://github.com/capnramses/antons_opengl_tutorials_book/●Don't get stuck on linking/projects - start fiddling now!
  • 28.
    “Hello Triangle”●Getting GLstarted is alot of work●“If you can draw 1triangle, you can draw1000000”●Go through sometutorials
  • 29.
    Pause and Review●Whatare the main components of a modern 3dgraphics programme?●Where do we store mesh data (vertex points)?●In what?●How do we define the format of the data?●What do we need to do before we tell OpenGLto draw with glDrawArrays() etc.?
  • 30.
    Things to ThinkAbout or Try●Can we change the colour of the triangle drawn?●How can we extend the triangle into a square?●Could we load mesh data from a file rather thanan array?●Shaders can be loaded from files. If you changea shader in an external file, do you need to re-compile?●How would you draw a second, separate shape?
  • 31.
  • 32.
    Graphics System Architecture●movedata to graphics hardware before drawing●minimise use of the bus
  • 33.
    Asynchronous Processing●Minimise CPU-GPUbus comm. Overhead●Maximise parallel processing to reduce overall GPU time●“Client” gl commands queue up and wait to be run on GPU●Can glFlush() to say “hurry up, I'm waiting” and glFinish() toactually wait – don't normally need to use these
  • 34.
  • 35.
    GPU Parallelism●1 vertex= 1 shader = 1 core●1 fragment = 1 shader = 1 core●but drawing operations serialise●.: 1 big mesh draw is faster than many small drawsGPU Uniform Shader CoresGeForce 605 48Radeon HD 7350 80GeForce GTX 580 512Radeon HD 8750 768GeForce GTX 690 1536Radeon HD 8990 2304
  • 36.
    ●minimum:– vertex shader–fragment shader●also have GPGPU“compute” shadersnow●note: Direct3D hwpipeline is the same,but different names
  • 37.
    Difference Between Fragmentand Pixels●Pixel = “picture element”●Fragment = pixel-sized area of a surface●Each triangle is divided into fragments onrasterisation●All fragments are drawn, even the obscured ones*●If depth testing is enabled closer fragments aredrawn over farther-away fragments●.: Huge #s of redundant FS may be executed
  • 38.
    Shader LanguageOpenGL VersionGLSL Version Tag1.2 none none2.0 1.10.59 #version 1102.1 1.20.8 #version 1203.0 1.30.10 #version 1303.1 1.40.08 #version 1403.2 1.50.11 #version 1503.3 3.30.6 #version 3304.0 4.00.9 #version 4004.1 4.10.6 #version 4104.2 4.20.6 #version 4204.3 4.30.6 #version 4304.4 ... #version 440... ... ...
  • 39.
    GLSL Operators andData Types●Same operators as C●no pointers●bit-wise operators since v 1.30data type detail common usevoid same as C functions that do notreturn a valuebool, int, float same as Cvec2, vec3, vec4 2d, 3d, 4d floating point points and direction vectorsmat2, mat3, mat4 2x2, 3x3, 4x4 f.p. matrices transforming points,vectorssampler2D 2d texture texture mappingsamplerCube 6-sided texture sky boxessampler2DShadow shadow projected textureivec3 etc. integer versions
  • 40.
    File Naming Convention●Upgardethe template – load shader strings from text files●post-fix with– .vert - vetex shader– .frag - fragment shader– .geom - geometry shader– .comp - compute shader– .tesc - tessellation control shader– .tese - tessellation evaluation shader●allows you to use a tool like Glslang reference compiler tocheck for [obvious] errors
  • 41.
    Example Vertex Shader#version400in vec3 vertex_position;void main() {gl_Position = vec4 (vertex_position, 1.0);}●Macro to explicitly set GLSL version required. Can also use #defines●in keyword – variable from previous stage in pipeline.Q. What is the stage before the vertex shader?●vec3 - 3d vector. Store positions, directions, or colours.●Every shader has a main() entry point as in C.... contd.
  • 42.
    Example Vertex Shader#version400in vec3 vertex_position;void main() {gl_Position = vec4 (vertex_position, 1.0);}●vec4 - has 4th component. gl_Position uses it to determineperspective. Set by virtual cameras. For now leave at 1.0 - "don'tcalculate any perspective".●Can also use out keyword to send variable to next stage.Q. What is the next stage?●Every VS positions one vertex between -1:1,-1:1,-1:1.Q. How does every vertex end up in a different positionthen?
  • 43.
    ●minimum:– vertex shader–fragment shader●also have GPGPU“compute” shadersnow●note: Direct3D hwpipeline is the same,but different names
  • 44.
    Example Fragment Shader#version400uniform vec4 inputColour;out vec4 fragColour;void main() {fragColour = inputColour;}●What important pipeline process happens first?●A uniform variable is a way to communicate to shaders from the mainapplication in C●For each fragment set a vec4 to RGBA (range 0.0 to 1.0)Q. What is the next stage? Where does out go?Q. What can the alpha channel do?
  • 45.
    Uniforms// do thisonce, after linking the shader p. not in the main loopint inputColour_loc = glGetUniformLocation (my_shader_program, “inputColour”);if (inputColour_loc < 0) {fprintf (stderr, “ERROR inputColour variable not found. Invalid uniformn”);do something rash;}// do this whenever you want to change the colour used by this shader programglUseProgram (my_shader_program);glUniform4f (inputColour_loc, 0.5f, 0.5f, 1.0f, 1.0f);●Uniforms are 0 by default i.e. our colour=black●Unused uniforms are optimised out by shader compiler●Basic uniforms are specific and persistent to one shader programme●Uniforms are available to all shaders in programme●Uniforms are a constant value in all shaders●You can change a uniform once, every frame, or whenever you like●Keep uniform updates to a minimum (don't flood the bus)
  • 46.
    Adding Error-Checking Functionality●Aftercalling glCompileShader()– Check GL_COMPILE_STATUS with glGetShaderiv()– If failed, get the log from glGetShaderInfoLog() and print it!●After calling glLinkProgram()– Check GL_LINK_STATUS with glGetProgramiv()– Get the log from glGetProgramInfoLog() and print it!●Check out the man-pages to find out how to use thesefunctions.●Add this to your projects! It gives you basic error checkingwith the line numbers.
  • 47.
    Shadertoy●WebGL tool toexperiment with shaderson-the-fly●implement entirely in a fragment shaderhttps://www.shadertoy.com/
  • 48.
  • 49.
    Data Layout Options●Wecould:– Concatenate colour data onto the end of our pointsbuffer:array = XYZXYZXYZRGBRGBRGB– Interleave colours between points:array = XYZRGBXYZRGBXYZRGB– Just create a new array and new vertex bufferobjectarray1 = XYZXYZXYZ array2 = RGBRGBRGB
  • 50.
    Second ArrayGLfloat points[]= {0.0f, 0.5f, 0.0f,0.5f, -0.5f, 0.0f,-0.5f, -0.5f, 0.0f};GLfloat colours[] = {1.0f, 0.0f, 0.0f,0.0f, 1.0f, 0.0f,0.0f, 0.0f, 1.0f};
  • 51.
    Second VBOGLuint points_vbo= 0;glGenBuffers (1, &points_vbo);glBindBuffer (GL_ARRAY_BUFFER, points_vbo);glBufferData (GL_ARRAY_BUFFER, sizeof (points),points, GL_STATIC_DRAW);GLuint colours_vbo = 0;glGenBuffers (1, &colours_vbo);glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);glBufferData (GL_ARRAY_BUFFER, sizeof (colours),colours, GL_STATIC_DRAW);
  • 52.
    Tell the VAOwhere to get 2ndvariableGLuint vao;glGenVertexArrays (1, &vao);glBindVertexArray (vao);glEnableVertexAttribArray (0);glBindBuffer (GL_ARRAY_BUFFER, points_vbo);glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);glEnableVertexAttribArray (1);glBindBuffer (GL_ARRAY_BUFFER, colours_vbo);glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);Second shader inputvariableStill a vec3Change these 2variables if interleavedor concatenated inone VBO
  • 53.
    Modify Vertex Shader#version400layout (location=0) in vec3 vp; // pointlayout (location=1) in vec3 vc; // colourout vec3 fcolour;void main () {fcolour = point; // “pass-through” outputgl_Position = vec4 (vp, 1.0);}Q. Why does the colour input have to start in the vertexshader?
  • 54.
    Modify the FragmentShader#version 400in vec3 fcolour;out vec4 frag_colour;void main () {frag_colour = vec4 (fcolour, 1.0);}Q. There are more fragments than vertices. What values willfcolour have in each fragment?
  • 55.
  • 56.
    Drawing Modes●Points canbe scaled●Lines are deprecatedbut still sort-of work●How would youchange your trianglesto an edgeswireframe?
  • 57.
    Winding Order andBack-Face Culling●Easy optimisation – don't waste time drawing theback face or inside-facing parts of a mesh●How do we define the “front” and “back”●= order that points are given●Clock-wise order or Counter clock-wiseglEnable (GL_CULL_FACE); // cull faceglCullFace (GL_BACK); // cull back faceglFrontFace (GL_CW); // usually front is CCW

[8]ページ先頭

©2009-2025 Movatter.jp