1 / 34

OpenGL

OpenGL. Лекция 6 (14.11.2013 ). OpenGL 3.0 и 4.0. Новая библиотека #include " glew.h “ http://glew.sourceforge.net/ Подключается перед #include " gl.h ” В версии 3.0 2 вида шейдеров: Вершинный, фрагментный В версии 4.0 5 видов шейдеров:

hedda
Download Presentation

OpenGL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. OpenGL Лекция 6 (14.11.2013)

  2. OpenGL 3.0 и 4.0 • Новая библиотека #include "glew.h“ • http://glew.sourceforge.net/ • Подключается перед #include "gl.h” • В версии 3.0 2 вида шейдеров: • Вершинный, фрагментный • В версии 4.0 5 видов шейдеров: • Вершинный, фрагментный, геометрический, мозаичный контрольный, мозаичный исполнительный

  3. Структура EXE • Заголовок • Секция кода • Секция данных • Таблица импорта • Таблица экспорта (для dll) • Секция ресурсов • Таблица реллокаций • Дополнительные секции (от упаковщиков…)

  4. Шейдеры вершинные шейдеры и фрагментные шейдеры Обработка вершин включает в себя операции, выполняемые над каждой вершиной, — в основном это преобразование и настройка освещения. Фрагменты — это структуры данных для каждого пиксела,­ которые создаются в результате растеризации графических примитивов.

  5. OpenGL Shading Language (GLSL) • ·         Язык шейдеров OpenGL — высокоуровневый процедурный язык. • ·         Такой же язык, с небольшими изменениями, используется для вершинных ­и фрагментных шейдеров. • ·         Он базируется на синтаксисе и управлении C и С++. • ·         Изначально в нем поддерживаются векторные и матричные операции, так как они являются неотъемлемой частью многих графических алгоритмов. • ·         Язык более жестко проверяет типы, чем C и C++, и функции могут вызываться по возвращаемому значению. • ·         Он использует квалификаторы типов чаще, чем управление вводом-выводом. • ·         У него нет ни ограничений на длину шейдера, ни необходимости ее запрашивать.

  6. Возможности шейдеров •      увеличенная реалистичность отображения материалов — металла, камня, дерева, краски и т. д.; • ·         увеличенная реалистичность эффектов освещения — освещенных областей, мягких теней и т. д.; • ·         изображение природных явлений — огня, дыма, воды, облаков и т. д.; • ·         создание не фотографически точных изображений — имитация живописи, рисунка пером, воспроизведение техники иллюстрации и т. д.; • ·         использование текстур для хранения нормалей, блеска, полиномных коэффициентов и т. д. — новые возможности использования текстурной памяти; • ·         меньшее количество способов доступа к текстурам — текстуры могут быть созданы с помощью процедур, а не посредством доступа к текстурным картам, хранящимся в текстурной памяти; • ·         использование новых способов обработки изображений — искривления, нечеткой обработки маски, сложного сглаживания и т. д.; • ·         создание эффектов анимации — интерполяции ключевого кадра, процедурно определенных движений; • ·         использование программируемых методов антиалиасинга.

  7. Логическая диаграмма операций в OpenGL

  8. Вершинный процессор программируемый модуль, который выполняет операции над входными значениями вершин и другими связанными с ними данными. Вершинный процессор предназначен для выполнения следующих традиционных операций с графикой: • ·         преобразования вершин; • ·         преобразования нормали, нормализации; • ·         генерирования текстурных координат; • ·         преобразования текстурных координат; • ·         настройки освещения; • ·         наложения цвета материала.

  9. Фрагментный процессор программируемый модуль, который выполняет операции над фрагментами и другими связанными с ними данными. Фрагментный процессор может выполнять следующие стандартные графические операции: • ·         операции над интерполированными значениями; • ·         доступ к текстурам; • ·         наложение текстур; • ·         создание эффекта дымки; • ·         наложение цветов.

  10. Компиляция шейдера

  11. Инициализация glew • #include "glew.h" • #include "glut.h" • #include "GL/gl.h" • #include "GL/glu.h" • #include "glaux.h" • int main() • { • // Инициализация OpenGL • glewInit(); • // Инициализация шейдеров • glutMainLoop(); • }

  12. Создание объекта шейдера • GLuintglCreateShader(GLenum type); • Allocates a shader object, type must be either GL_VERTEX_SHADER or GL_FRAGMENT_SHADER. The return value is eitner a non-zero integer or zero, if an error occurred.

  13. Задание исходного кода шейдера • void glShaderSource(GLuintshader, GLsizei count, constGLchar **string, constGLint * lengthy. • Associates the source of a shader with a shader object shader, string is an array of count GLchar strings that compose the shader’s source. The character strings in string may be optionally null-terminated, length can be one of three values. If length is NULL, then it’s assumed that each string provided in string is null-terminated. Otherwise, length has count elements, each of which specifies the length of the corresponding entry in string. If the value of an element in the array length is a positive integer, the value represents the number of characters in the corresponding string element. If the value is negative for particular elements, then that entry in string is assumed to be null-terminated.

  14. Компилирование шейдера • void glCompileShader(GLuintshader); • Compiles the source code for shader. The results of the compilation can be queried by calling glGetShaderiv() with an argument of GL_COMPILE_ STATUS.

  15. Получение ошибок компиляции • void glGetShaderInfoLog(GL uintshader, GLsizeibufSize, GLsizei *length, char *infoLog); • Returns the log associated with the last compilation of a shader object. shader specifies which shader object to query The log is returned as a null-terminated character string of length characters in the buffer infoLog. The maximum return size of the log is specified in bufSize. • If length is NULL, then no string was returned.

  16. Создание шейдерной программы • GLuintglCreateProgram(); • Allocates a shader program. • void glAttachShader(GLuintprogram, GLuintshader); • Associates the shader object, shader, with the shader program, program. A shader object can be attached to a shader program at any time, although its functionality will only be available after a successful link of the shader program. A shader object can be attached to multiple shader programs simultaneously.

  17. Открепление шейдера • void glDetachShader(GLuint program, GLuintshader); • Removes the association of a shader object, shader, from the shader program, program. If shader is detached from program and has been marked for deletion (by calling glDeleteShaderQ), it is deleted at that time.

  18. Линковка шейдерной программы • void glLinkProgram(GLuint program); • Processes all shader objects attached to program to generate a completed shader program. The result of the linking operation can be queried by calling glGetProgramiv() with GL_LINK_STATUS. GL_TRUE is returned for a successful link; GL_FALSE is returned otherwise. • As with shader objects, there’s a chance that the linking phase may fail due to errors in the attached shader objects. You can query the result of the link operation’s success by calling glGetProgramiv() with an argument of GL_ LINK_STATUS. If GL_TRUE was returned, the link was successful, and you’re able to specify the shader program for use in processing vertices or fragments. If the link failed, represented by GL_FALSE being returned, then you can determine the cause of the failure by retrieving the program link information log by calling glGetProgramLog().

  19. Запуск шейдерной программы • void glUseProgram(GLuint program); • Uses program for either vertex or fragment processing, depending upon the type of shader created with glCreateShader(). If program is zero, no shader is used for processing and OpenGL reverts to fixed-function operation.

  20. Удаление шейдера и программы • void glDeleteShader(GLuintshader); • Deletes shader. If shader is currently linked to one or more active shader programs, the object is tagged for deletion and deleted once the shader program is no longer being used by any shaderpiogram. • void glDeleteProgram( GLuint program); • Deletes program immediately if not currently in use in any context, or tagged for deletion when the program is no longer in use by any contexts.

  21. Определение типа объекта • GLbooleanglIsProgram(GLuint program); • Returns GL_TRUE if program is the name of a shader program. If program is zero, or non-zero and not the name of a shader object, GL_FALSE is returned. • GLbooleanglIsShader(GLuintshader); • Returns GL_TRUE if shader is the name of a shader object. If shader is zero, or non-zero and not the name of a shader object, GL_FALSF is returned.

  22. Валидация программы • void gl Validate Program(GLuint program); • Validates program against the current OpenGL state settings. After validation, the value of GL_VALIDATE_STATUS will be set to either GL_ TRUE, indicating that the program will execute in the current OpenGL environment, or GL_FALSE otherwise. The value of GL._VALIDATE_ STATUS status can be queried by calling glGetProgramiv().

  23. Типы данных в шейдерах • vec2, vec3, vec4 - 2D, 3D and 4D floating point vector • ivec2, ivec3, ivec4 - 2D, 3D and 4D integer vector • bvec2, bvec3, bvec4 - 2D, 3D and 4D boolean vectors For floats here are also matrix types: • mat2, mat3, mat4 - 2x2, 3x3, 4x4 floating point matrix • sampler1D, sampler2D, sampler3D - 1D, 2D and 3D texture • samplerCube- Cube Map texture • sampler1Dshadow, sampler2Dshadow - 1D and 2D depth-component texture

  24. Аттрибуты вершинного шейдера • gl_Vertex 4D vector representing the vertex position • gl_Normal3D vector representing the vertex normal • gl_Color4D vector representing the vertex color • gl_MultiTexCoordX4D vector representing the texture coordinate of texture unit X

  25. Константы преобразований • gl_ModelViewMatrix 4x4 Matrix representing the model-view matrix. • gl_ModelViewProjectionMatrix 4x4 Matrix representing the model-view-projection matrix. • gl_NormalMatrix3x3 Matrix representing the inverse transpose model-view matrix. This matrix is used for normal transformation.

  26. Шейдерные переменные • gl_FrontColor 4D vector representing the primitives front color • gl_BackColor4D vector representing the primitives back color • gl_TexCoord[X] 4D vector representing the Xth texture coordinate • gl_Position 4D vector representing the final processed vertex position. Only available in vertex shader. • gl_FragColor4D vector representing the final color which is written in the frame buffer. Only available in fragment shader. • gl_FragDepthfloat representing the depth which is written in the depth buffer. Only available in fragment shader.

  27. Пример вершинного шейдера • void main() • { • gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; • }

  28. Пример фрагментного шейдера • void main() • { • gl_FragColor= vec4(0.0, 0.5, 0.0, 1.0); • }

  29. Области видимости переменных в шейдерах • uniform sampler2D my_color_texture; • uniform mat4 my_texture_matrix; • varying vec3 vertex_to_light_vector; • varying vec3 vertex_to_eye_vector; • attribute vec3 tangent; • attribute vec3 binormal;

  30. Передача значений в шейдер • GLintglGetUniformLocationARB(GLhandleARB program, constGLcharARB * name) • void glUniform{1|2|3|4}{f|i}ARB(GLint location, TYPE val) • void glUniform{1|2|3|4}{f|i}vARB(GLint location, GLuint count, const TYPE * vals) • void glUniformMatrix{2|3|4|}fvARB(GLint location, GLuint count, GLboolean transpose, constGLfloat * vals)

  31. Передача аттрибутов в шейдер • GLintglGetAttribLocationARB(GLhandleARB program, constGLcharARB* name) • void glVertexAttrib{1|2|3|4}{s|f|d}ARB(GLuint index, TYPE val) • void glVertexAttrib{1|2|3|4}{s|f|d}vARB(GLuint index, const TYPE * vals)

  32. Работа с ресурсами • HRSRC WINAPI FindResource( • _In_opt_  HMODULE hModule, • _In_      LPCTSTR lpName, • _In_      LPCTSTR lpType • ); • Типы ресурсов: • http://msdn.microsoft.com/en-us/library/windows/desktop/ms648009%28v=vs.85%29.aspx

  33. Работа с ресурсами • HGLOBAL WINAPI LoadResource( • _In_opt_  HMODULE hModule, • _In_      HRSRC hResInfo • ); • LPVOID WINAPI LockResource( • _In_  HGLOBAL hResData • ); • DWORD WINAPI SizeofResource( • _In_opt_  HMODULE hModule, • _In_      HRSRC hResInfo • );

  34. Просмотр и Добавление ресурсов • Microsoft Visual Studio • Вид – Ресурсы – Щелчок правой кнопкой мыши – Добавить – Ресурс – HTML • Узнать номер ресурса: • Вид – Ресурсы – Щелчок правой кнопкой мыши –Символы ресурсов

More Related