Opengl lec 3


Published on

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • To get a list of all extensions supported by the OpenGL implementation, you must iterate from 0 to NUM_EXTENSIONS – 1 calling glGetStringi() each time with the new index. But how big is NUM_EXTENSIONS? To find out, you need to pass GL_NUM_EXTENSIONS to glGetIntegerv()
  • Note:For a variable to exist between shaders, it must be declared with the correct qualifiers in both shaders (e.g., in and out)
  • Opengl lec 3

    1. 1. OpenGLOpenGL Extensions
    2. 2. What Is an Extension?An OpenGL extension is really just that; anextension to the OpenGL standard. In fact, justlike OpenGL, each extension is recorded in aspecification document. This documentdescribes, in detail, some extra functionality thatallows you to render faster, in better quality ormore easily. Extensions allow graphics cardvendors to quickly provide access to the mostcutting-edge features of their chipsets, withoutwaiting for updates to the OpenGL specification.
    3. 3. Extension NamingPREFIX_extension_name Prefix is the vendor name.Name Strings glGetStringi() the name string for an extension is the extension name prefixed by GL_, WGL_ (for Windows extensions), GLX_ (for X extensions), or GLU_ (for extensions to the GLU library).
    4. 4. Functions and TokensExtensions can add new functions, new tokens each function is prefixed by a lower case ‘‘gl’’ the rest of the function name uses a capital letter at the beginning of each word Ex : glFunctionNameARB()token :is a constant or enumerant such asGL_TEXTURE_2D or GL_FLOAT should be all capital letters, with spaces replaced by underscores and prefixed with GL_ Ex: GL_SOME_NEW_TOKEN_ARB
    5. 5. Insteaddownload the latest glext.hOr platform-specific extension tokens wglext.h and a glxext.h
    6. 6. Obtaining a Function’s Entry PointYou need to link to them dynamically at runtimeQuerying the graphics drivers for a function pointer to thefunction you want to use. This is platform specific, but thegeneral idea is the same on all platforms.
    7. 7. StepsFirst, you must declare a pointer to a function .Next, you call a platform- specific function to find theaddress of the function you want, and assign it to thefunction pointerIf the function pointer is NULL after this call, then theextension that provides the function is not available.
    8. 8. Steps cont.PFNGLGETSTRINGIPROC is the typedef for the functionpointer typeOn Windows, we use the wglGetProcAddress() function for this(on X you would use glXGetProcAd- dress())PROC wglGetProcAddress(LPCSTR lpszProcName);Code ex:glGetStringi=(PFNGLGETSTRINGIPROC)wglGetProcAddress("glGetStringi"); if (glGetStringi != NULL) { //We can use glGetStringi }
    9. 9. Extensions on Windowson the Windows platform, you must useextensions to access any functionalityafter OpenGL 1.1
    10. 10. Finding Supported ExtensionsYou can get available extensions by using glGetStringi()and passing GL_EXTENSIONS as the first parameter.
    11. 11. WGL ExtensionsThere are some extensions that are specific to theWindows system wglGetExtensionsStringARB() const char* wglGetExtensionsStringARB(HDC hdc); This function differs from glGetStringi() in that it returns the extension strings as a space-delimited list.
    12. 12. Defining Tokens#define GL_HALF_FLOAT_NV 0x140BNotice that we prefix the GL_ to the constant defined inthe specification to match the naming convention of theother tokens.
    13. 13. Introduction to Glee
    14. 14. Moving to aProgrammable Pipeline
    15. 15. The main functionality deprecatedColor Index modeOpenGL shading language versions 1.10 and 1.20 (now replaced with 1.30) n ImmediatemodeFixed-function vertex processingMatrix stacksClient vertex arraysRectanglesRaster positionNon-sprite pointsWide lines and line stippleQuadrilateral and polygon primitivesSeparate polygon drawing modePolygon stipplePixel drawingBitmapsTexture wrap mode—GL_CLAMPDisplay listsThe selection bufferThe accumulation bufferAlpha testAttribute stacksEvaluatorsUnified extension string
    16. 16. Most of the above functionality isnow implemented using shaders,and some parts (such as thematrix stack) can beimplemented in separate libraries
    17. 17. What Is GLSL?GLSL or the OpenGL ShadingLanguage is used to writeprograms that run on the GPU
    18. 18. Main types of shadersVertex shaders: which operate on every vertex sent to thegraphics card.Fragment (also known as pixel) shaders: which operateon every pixel to be rasterized.You effectively replace whole sections of the pipeline.
    19. 19. Vertex ShadersVertex shaders are programs that operate on each vertex that issent to the graphics card by a rendering command such asglDrawArrays()The responsibility of this shader to calculate the final position ofthe vertex.Calculate per-vertex attributes such as colorsVertex shader only knows about a single vertex at a timeIt is not possible to extract information on neighboring vertices.The only output that is required by a vertex shader is theposition
    20. 20. You will need to manually handle the following: Vertex transformation (using modelview and projection matrices) Texture coordinate generation Lighting calculations Color application Normal transformation
    21. 21. Fragment ShadersIt is the job of the fragment shader to calculate the finaloutput color of a pixel that will be stored in the framebuffer
    22. 22. With Fragment shader you must handle the followingparts:Computing per-pixel colorsApplying texturesCalculating per-pixel fogApplying per-pixel lighting
    23. 23. The GLSL LanguageThere have been three versions of GLSL since itsintroduction 1.10 1.20 1.30
    24. 24. Shader StructureA GLSL shader must contain at least a single functioncalled main().Any output that the shader generates is passed viavariables which have a qualifier of outVariables that are passed into or out of a shader must bedeclared in global scope
    25. 25. PreprocessorPreprocessor
    26. 26. VariablesGLSL variables obey rules of scopeGlobal scope (at the top of the shader)Variable can exist across more than one shader (programscope)
    27. 27. Data TypesGLSL is a statically typed languageGLSL also has some other base types specific to shaderprogramming (vectors, matrices).
    28. 28. initialize a variable (int i = 0;)vectors and matrices are made up of multiple componentsThese elements can be addressed individually by adding aperiod (.) to the variable name and then using the componentname to select a componentMatrix components are accessed using the array-style notation(mat4[column][row])you can define arrays of variables in GLSL vec3 array[3];The length of an array can be determined later in the shader byusing the built-in length() float array[3]; int arrayLength = array.length();
    29. 29. Structuresstruct Light { vec3 color;vec3 position };Light firstLight;firstLight.color = vec3(0.0, 1.0, 2.0);It is illegal to nest a structure declaration inside another structurestruct B {struct A { //Invalid!int a; };};
    30. 30. perfectly fine for a structure to contain an instance of anotherstructurestruct A { int a; } struct B {A a; // OK.};
    31. 31. OperatorsOn types such as vectors that are made up of severalcomponents the operators work on a component-by-component basisThe one exception is multiplications involving matrices,which work using standard linear algebra rules.
    32. 32. Variable QualifiersVariable qualifiers modify a variable’s behavior in someway
    33. 33. Extra qualifiersAffect the interpolation of the variable
    34. 34. Shader InputsThere are two methods for passing in variable valuesuniforms and attributes
    35. 35. UniformsA variable with a uniform qualifier has its value passedinto the shader from the application and remains constantbetween the shader stagesUniforms cannot be the target of an assignment inside theshaderThey can be accessed by all stages of the shaderprogram if the variable is declared identically in eachshaderglUniform*()
    36. 36. Vertex AttributesA vertex attribute is a regular global variable marked withthe in qualifier in a vertex shader.glVertexAttribPointer()
    37. 37. StatementsGLSL contains the same flow control statements that youfind in C and C++.It is not legal to define a variable inside an if statement
    38. 38. Constructors GLSL data types have built-in constructors that can be used to create new variables initialized with data Not only to initialize new variables, but also to copy data from a variable of one type to anotherout vec4 ourColorOutput; void main(void){vec3 color = vec3(1.0, 0.0, 0.0); //A 3-element vector initialized with aconstructor//A constructor is used to copy the data to a 4-element vectorourColorOutput = vec4(color, 1.0); }
    39. 39. SwizzlingSome constructors allow you to pass in more than one type ofargument to construct an object of the sum of their componentsvec4 fourVec(1.0, 2.0, 3.0, 4.0);vec3 threeVec = vec3(fourVec.y, fourVec.z, fourVec.w);vec4 fourVec(1.0, 2.0, 3.0, 4.0);vec3 threeVec = fourVec.yzw;Swizzling works on all vector types, and you can use anycombination of component names from the same name set(xyzw, rgba, or stpq)
    40. 40. Defining FunctionsFunction declarations differ from C in that each parametermay include one of the following qualifiers: in, out, inout,or const (whereas C only has const).Functions in GLSL can be overloaded.
    41. 41. Built-in FunctionsSome of these functions are simple convenience functionsyou could write yourselfOthers provide access to hardware functionality which isimpossible to recreate manually
    42. 42. Using Shaders To use GLSL programs in your code, you need to use the C API functions that were promoted to core in OpenGL 2.0.1. Create the shader objects—This will normally consist of creatinga program object and two shader objects (fragment and vertex).2. Send the source to OpenGL—The source for each shader isassociated with the corresponding shader objects.3. Compile the shaders.4. Attach the shaders to the program object.5. Link the program.6. Bind the program ready for use.7. Send any uniform variables and vertex attributes. 8. Render theobjects that use the program.
    43. 43. Creating GLSL ObjectsThe first thing to do to prepare our GLSL program for useis to generate the objects that hold the state of theprogram in OpenGLThere are two types of object : shader objects program objects
    44. 44. program objectshold infor- mation relating to the GLSL program as awhole.GLuint glCreateProgram(void); //To create the programobjects
    45. 45. shader objectshold the source code and data belonging to the vertex orfragment shadersglCreateShader() //To create the shader objects.GLuint glCreateShader(GLenum type);Currently, the type parameter can be eitherGL_VERTEX_SHADER or GL_FRAGMENT_SHADER
    46. 46. shader objects To send the shader source code to OpenGLvoid glShaderSource(GLuint shader, GLsizei count, constGLchar **string, const GLint *length); count is the number of strings in this array length is an array that stores the character length of the strings in the string array If length is NULL, all strings in the array are assumed to be null- terminated To compile shadersvoid glCompileShader(GLuint shader);
    47. 47. shader objects To find out whether compilation of the shader was successfulvoid glGetShaderiv(GLuint shader, GLenum pname, GLint*params);EX:GLint result;glGetShaderiv(shaderObject, GL_COMPILE_STATUS,&result);
    48. 48. To attach shadervoid glAttachShader(GLuint program, GLuint shader);//If you attempt to attach the same shader to the programtwice, OpenGL generates a GL_INVALID_OPERATION error To detach shadervoid glDetachShader(GLuint program GLuint shader);
    49. 49. Ready to link the GLSL programLinking may fail for a number of reasons: One of the shader objects hasn’t compiled successfully. The number of active attribute variables has exceeded the number supported by the OpenGL implementation. The number of supported or active uniform variables has been exceeded. The main function is missing from one of the attached shaders. An output variable from the vertex shader is not declared correctly in the fragment shader. A function or variable reference cannot be resolved. A global variable shared between stages is declared with different types or initial values.
    50. 50. You link a program by using the following function:void glLinkProgram(GLuint program);To retrieve infor- mation on a program object, you useglGetProgramiv()void glGetProgramiv(GLuint program, GLenum pname, GLint*params);
    51. 51. To enable a GLSL programvoid glUseProgram(GLuint program);This will bind and enable the programAny primitives sent to OpenGL while the program isenabled will use the attached shaders for renderingIf you pass 0 as the program parameter, then shader willbe disabled.
    52. 52. Sending Data to ShadersPassing Data to UniformsPassing Data to Vertex Attributes
    53. 53. Passing Data to Uniforms Each GLSL implementation has a limited number of locations to store uniform variables The GLSL implementation determines which uniform goes in which location Before you can send data to a uniform, you must first find out its locationGLuint glGetUniformLocation(GLuint program, const GLchar*name);
    54. 54. To send the data to Uniform :void glUniform{1|2|3|4}{f|i}(GLint location, TYPE v); voidglUniform{1|2|3|4}ui(GLint location, TYPE v);void glUniform{1|2|3|4}{f|i}v(GLint location, GLuint count, constTYPE *v); void glUniform{1|2|3|4}uiv(GLint location, GLuint count,const TYPE *v);count is the number of values in the arrayv is a pointer to an array containing the datavoid glUniformMatrix{2|3|4}fv(GLint location, GLuint count,GLboolean trans- pose, const GLfloat *v);void glUniformMatrix{2x3|3x2|2x4|4x2|3x4|4x3}fv(GLint location,GLuint count, GLboolean transpose, const GLfloat *v);Transpose: If you have stored your data in column-major order thenyou need to pass GL_FALSE to transpose; otherwise, passGL_TRUE.
    55. 55. Passing Data to Vertex Attributes Attributes in GLSL are variables that are defined in the vertex shader with the in qualifier You can either let OpenGL determine which location to store the attribute or you can specify it manually OpenGL determine which location :GLint glGetAttribLocation(GLuint program, const GLchar*name); the program needs to have been linked for this function to work.
    56. 56. Specify the location of the attributes yourself :void glBindAttribLocation(GLuint program, GLuint index,const GLchar* name);Calls to glBindAttribLocation() should be made beforelinking the GLSL programAttribute zero is special and should always be used for thevertex position.
    57. 57. send the data to the attribute using glVertexAttribPointer():void glVertexAttribPointer(GLuint index, GLint size,GLenum type, GLboolean normalized, GLsizei stride,const GLvoid *pointer); index is the location of the attribute size indicates the number of components per element (this can be between one and four) Type GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGN ED_INT, GL_FLOAT, or GL_DOUBLE. normalized flag is true then data will be converted to a floating- point value between -1.0 and 1.0 (for signed values) or 0.0 and 1.0 for unsigned values stride specifies the offset in bytes between attributes in the array pointer is a pointer to the array of data to send to the attribute using VBOs (which you should be!), this should be an integer offset in bytes into the currently bound buffer.
    58. 58. Vertex attributes must be enabled before rendering void glEnableVertexAttribArray(GLuint index); The attributes can be disabled with :void glDisableVertexAttribArray(GLuint index);
    59. 59. Calculating Vertex Transformations// First multiply the current vertex by the modelview matrixvec4 pos = modelview_matrix * vec4(a_Vertex, 1.0);// Then multiply the result by the projection matrixgl_Position = projection_matrix * pos;
    60. 60. Applying Colorstwo-step process.vertex shader, you must read the input attribute thatcontains the color for the vertex. You must pass this toyour fragment shader using an out variablethe color will be interpolated before the input to thefragment shaderIn the fragment shader, you can pass this color directly outas the final color, or you can perform some logic tochange the color
    61. 61. Handling Your Own MatricesThe Kazmath LibraryOne feature that the library provides is its own matrixstack