Henerial: переводы
OpenGL SuperBible (6th Edition) / OpenGL Супер Книга (6-ое издание)
→All OpenGL functions start with gl and follow a number of naming conventions such as encoding some of their parameter types as suffixes on the end of the function names. This allows a limited form of overloading even in languages that don’t directly support this. In this case, the suffix fv means that the function consumes a vector (v) of floating-point (f) values, where arrays (generally referenced by pointers in languages like C) and vectors are used interchangeably by OpenGL.
The glClearBufferfv() function tells OpenGL to clear the buffer specified by the first parameter (in this case GL_COLOR) to the value specified in its third parameter. The second parameter, drawBuffer, is used when there are multiple output buffers that could be cleared. Because we’re only using one here and drawBuffer is a zero-based index, we’ll just set it to zero in this example. Here, that color is stored in the array red, which contains four floating-point values — one each for red, green, blue, and alpha, in that order. The red, green, and blue terms should be self-explanatory. Alpha is a fourth component that is associated with a color and is often used to encode the opacity of a fragment. When used this way, setting alpha to zero will make the fragment completely transparent, and setting it to one will make it completely opaque. The alpha value can also be stored in the output image and used in some parts of OpenGL’s calculations, even though you can’t see it. You can see that we set both the red and alpha values to one and the others to zero. This specifies an opaque red color. The result of running this application is shown in Figure 2.1.
This initial application isn’t particularly interesting1 as all it does is fill the window with a solid red color. You will notice that our render() function takes a single parameter — currentTime. This contains the number of seconds since the application was started, and we can use it to create a simple animation. In this case, we can use it to change the color that we use to clear the window. Our modified render() function2 is shown in Listing 2.2.
1. This sample is especially uninteresting if you are reading this book in black and white!
2. If you’re copying this code into your own example, you’ll need to include <math.h> in order to get the declarations of sin() and cos().
The glClearBufferfv() function tells OpenGL to clear the buffer specified by the first parameter (in this case GL_COLOR) to the value specified in its third parameter. The second parameter, drawBuffer, is used when there are multiple output buffers that could be cleared. Because we’re only using one here and drawBuffer is a zero-based index, we’ll just set it to zero in this example. Here, that color is stored in the array red, which contains four floating-point values — one each for red, green, blue, and alpha, in that order. The red, green, and blue terms should be self-explanatory. Alpha is a fourth component that is associated with a color and is often used to encode the opacity of a fragment. When used this way, setting alpha to zero will make the fragment completely transparent, and setting it to one will make it completely opaque. The alpha value can also be stored in the output image and used in some parts of OpenGL’s calculations, even though you can’t see it. You can see that we set both the red and alpha values to one and the others to zero. This specifies an opaque red color. The result of running this application is shown in Figure 2.1.
This initial application isn’t particularly interesting1 as all it does is fill the window with a solid red color. You will notice that our render() function takes a single parameter — currentTime. This contains the number of seconds since the application was started, and we can use it to create a simple animation. In this case, we can use it to change the color that we use to clear the window. Our modified render() function2 is shown in Listing 2.2.
1. This sample is especially uninteresting if you are reading this book in black and white!
2. If you’re copying this code into your own example, you’ll need to include <math.h> in order to get the declarations of sin() and cos().
0 Все OpenGL функции начинаются с gl заканчивается набором определенных суффиксов в конце имени функции. Это позволяет реализовать ограниченную форму перегрузки даже если язык программирования прямо этого не поддерживает. В нашел случае суффикс fv означает, что функция принимает вектор (v) флоатов (f), при этом массивы ( массивы в стиле С ) и векторы используются взаимозаменяемо.
→Click here to view code image
void glClearBufferfv(GLenum buffer,
GLint drawBuffer,
const GLfloat * value);
void glClearBufferfv(GLenum buffer,
GLint drawBuffer,
const GLfloat * value);
0 void glClearBufferfv(GLenum buffer,
GLint drawBuffer,
const GLfloat * value);
GLint drawBuffer,
const GLfloat * value);
→The example shown in Listing 2.1 simply clears the whole screen to red. This introduces our first OpenGL function, glClearBufferfv(). The prototype of glClearBufferfv() is
0 Пример, показанный в Исходнике 2.1 просто очищает весь экран в красный (есть понятие цвет очистки - цвет, которым заливается кадр до отрисовки, п.п.). Тут представлена наша первая OpenGL функция - glClearBufferfv().
Прототипом glClearBufferfv() является:
Прототипом glClearBufferfv() является:
→Figure 2.1: The output of our first OpenGL application
0 Фигура 2.1: Вывод нашей первой программы на OpenGL.
→Creating a Simple Application
To introduce the application framework that’ll be used in the remainder of this book, we’ll start with an extremely simple example application. The application framework is brought into your
application by including sb6.h in your source code. This is a C++ header file that defines a namespace called sb6 that includes the declaration of an application class, sb6::application, from which we can derive our examples. The framework also includes a number of utility functions and a simple math library called vmath to help you with some of the number crunching involved in OpenGL.
To create an application, we simply include sb6.h, derive a class v sb6::application, and (in exactly one of our source files) include an instance of the DECLARE_MAIN macro. This defines the main entry point of our application, which creates an instance of our class (the type of which is passed as a parameter to the macro) and calls its run() method, which implements the application’s main loop.
In turn, this performs some initialization by calling the startup() method and then calls the render() method in a loop. In the default implementation, both methods are virtual functions with empty bodies. We override the render() method in our derived class and write our drawing code inside it. The application framework takes care of creating a window, handling input, and displaying the rendered results to the user. The complete source code for our first example is given in Listing 2.1, and its output is shown in Figure 2.1.
To introduce the application framework that’ll be used in the remainder of this book, we’ll start with an extremely simple example application. The application framework is brought into your
application by including sb6.h in your source code. This is a C++ header file that defines a namespace called sb6 that includes the declaration of an application class, sb6::application, from which we can derive our examples. The framework also includes a number of utility functions and a simple math library called vmath to help you with some of the number crunching involved in OpenGL.
To create an application, we simply include sb6.h, derive a class v sb6::application, and (in exactly one of our source files) include an instance of the DECLARE_MAIN macro. This defines the main entry point of our application, which creates an instance of our class (the type of which is passed as a parameter to the macro) and calls its run() method, which implements the application’s main loop.
In turn, this performs some initialization by calling the startup() method and then calls the render() method in a loop. In the default implementation, both methods are virtual functions with empty bodies. We override the render() method in our derived class and write our drawing code inside it. The application framework takes care of creating a window, handling input, and displaying the rendered results to the user. The complete source code for our first example is given in Listing 2.1, and its output is shown in Figure 2.1.
0 Создание простой программы
Чтобы представить фреймворк, используемый в этой книге, мы начнем с простейшей программы. Этот фреймворк подключается к программе путем подключения (includе) sb6.h в исходный код. Это файл оглавления, который определяет пространство имен sb6(Супер Библия 6. п.п.), которое вмещает объявление класса программы, sb6::application, от которого мы можем вывести наши примеры. Во фреймворке так же присутствует множество дополнительных функций, а так же простая математическая библиотека vmath( вы можете вместо нее использовать GLM как более мощную. п.п. ), которая поможет вам в обработке чисел, присущей OpenGL.
Для создания программы мы просто подключаем sb6.h, наследуем класс sb6::application, и (только в одном из наших файлов - main.cpp, к примеру) вызываем макрос DECLARE_MAIN с нашим переопределенным классом в качестве параметра. Это определяет главную точку входа в нашу программу и создает объект нашего класса и вызывает метод run(), который определяет главный цикл нашей программы (по аналогии с GlutMainLoop, п.п.).
В свою очередь, это вызывает ф-ю инициализации - startup(), а так же ф-ю render(), теперь уже в цикле.
В реализации по умолчанию обе эти ф-и является виртуальными и без реализации.
Вы перегружаем ф-ю render() в нашем переопределенном классе и вписываем в нее наш код рисования. Сам фреймворк заботится о создании окна, обработке входных данных ( клавиатура/мышь и подобное, п.п. ), выводе отрисованных результатов в окно.
Пример исходного кода дан в Исходнике 2.1, а вывод этой программы показан в Фигуре 2.1
Чтобы представить фреймворк, используемый в этой книге, мы начнем с простейшей программы. Этот фреймворк подключается к программе путем подключения (includе) sb6.h в исходный код. Это файл оглавления, который определяет пространство имен sb6(Супер Библия 6. п.п.), которое вмещает объявление класса программы, sb6::application, от которого мы можем вывести наши примеры. Во фреймворке так же присутствует множество дополнительных функций, а так же простая математическая библиотека vmath( вы можете вместо нее использовать GLM как более мощную. п.п. ), которая поможет вам в обработке чисел, присущей OpenGL.
Для создания программы мы просто подключаем sb6.h, наследуем класс sb6::application, и (только в одном из наших файлов - main.cpp, к примеру) вызываем макрос DECLARE_MAIN с нашим переопределенным классом в качестве параметра. Это определяет главную точку входа в нашу программу и создает объект нашего класса и вызывает метод run(), который определяет главный цикл нашей программы (по аналогии с GlutMainLoop, п.п.).
В свою очередь, это вызывает ф-ю инициализации - startup(), а так же ф-ю render(), теперь уже в цикле.
В реализации по умолчанию обе эти ф-и является виртуальными и без реализации.
Вы перегружаем ф-ю render() в нашем переопределенном классе и вписываем в нее наш код рисования. Сам фреймворк заботится о создании окна, обработке входных данных ( клавиатура/мышь и подобное, п.п. ), выводе отрисованных результатов в окно.
Пример исходного кода дан в Исходнике 2.1, а вывод этой программы показан в Фигуре 2.1
→Chapter 2. Our First OpenGL Program
What You’ll Learn in This Chapter
• How to create and compile shader code
• How to draw with OpenGL
• How to use the book’s application framework to initialize your programs and clean up afteryourself
In this chapter, we introduce the simple application framework that is used for almost all of the samples in this book. This shows you how to create the main window with the book’s application framework and how to render simple graphics into it. You’ll also see what a very simple GLSL shader looks like, how to compile it, and how to use it to render simple points. The chapter concludes with your very first OpenGL triangle.
What You’ll Learn in This Chapter
• How to create and compile shader code
• How to draw with OpenGL
• How to use the book’s application framework to initialize your programs and clean up afteryourself
In this chapter, we introduce the simple application framework that is used for almost all of the samples in this book. This shows you how to create the main window with the book’s application framework and how to render simple graphics into it. You’ll also see what a very simple GLSL shader looks like, how to compile it, and how to use it to render simple points. The chapter concludes with your very first OpenGL triangle.
0 Глава 2. Наша первая программа на OpenGL.
Что нового вы узнаете в этой главе:
- Как создать и скомпилировать шейдер.
- Как рисовать при помощи OpenGL.
- Как использовать фреймворк, поставляемый с книгой, для инициализации ваших программ и очистки памяти после ее использования.
В этой главе мы представляем простой фреймворк для создания программ, который будет в дальнейшем использоваться почти во всех примерах. Будет показано, как создавать главное окно с нашим фреймворком и как рисовать простую графику в этом окне. Так же вы увидите простые примеры использования: сам GLSL код, его компиляция и использование для отрисовки простых точек. Эта глава закончится вашим самым первым треугольником (на экране. п.п.).
Что нового вы узнаете в этой главе:
- Как создать и скомпилировать шейдер.
- Как рисовать при помощи OpenGL.
- Как использовать фреймворк, поставляемый с книгой, для инициализации ваших программ и очистки памяти после ее использования.
В этой главе мы представляем простой фреймворк для создания программ, который будет в дальнейшем использоваться почти во всех примерах. Будет показано, как создавать главное окно с нашим фреймворком и как рисовать простую графику в этом окне. Так же вы увидите простые примеры использования: сам GLSL код, его компиляция и использование для отрисовки простых точек. Эта глава закончится вашим самым первым треугольником (на экране. п.п.).
Резюме
- Пол:
- мужчина
- Родной язык:
- русский
- С нами:
-
с 11 августа 2014 г.
(4452 дня)
Не является членом клуба. - Деятельность:
-
6 версий перевода
с общим рейтингом 0
2 комментария
