Russian Qt Forum
Апрель 20, 2024, 05:40 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: [1] 2   Вниз
  Печать  
Автор Тема: Примеры из SuperBible (3-го издания) на Qt  (Прочитано 28494 раз)
8Observer8
Гость
« : Сентябрь 05, 2014, 17:19 »

Привет!

Буду потихоньку переписывать примеры из SuperBible (3-го издания) на Qt и выкладывать здесь. Внизу этого сообщения прикрепил проект, в котором (грубо говоря) будет изменяться только содержимое файлов: Scene.h, Scene.cpp и название проекта.

Диск к книге (кроме исходников есть дополнительные материалы для самостоятельного разбора): http://rutracker.org/forum/viewtopic.php?t=742207

Отдельно исходники (внизу страницы) http://www.openglsuperbible.com/previous-editions/

Вот здесь переписывают уроки из SuperBible 6-ого издания: http://www.prog.org.ru/topic_27475_0.html

Инструменты
- Qt 5.3.2 for Windows 32-bit (MinGW 4.8.2, OpenGL, 737 MB)
- OS Win7

Содержание

Подготовка к разработке и создание нового проекта
- Установка Qt
- Переключение Qt Creator'a на английский
- Создание нового проекта

Глава 2. Используя OpenGL
- Simple. Пустое окно
- GLRect. Квадрат
- Bounce. Анимированный квадрат

Глава 3. Рисование в пространстве: геометрические примитивы и буферы
- Points. Вращение с помощью стрелок 3D-спирали из точек
- Pointsz. Спираль, точки которой увеличиваются от минимально возможной по размеру до максимально возможной
- Lines. Отображает набор линий, веером расходящихся по окружности
- LStrips. Аппроксимация кривых прямолинейными отрезками
- Linesw. Рисует линии переменной ширины
- LStipple. Пунктирные линии
- Triangle. Конус, составленный из вееров треугольников
- PStipple (Polygin Stippling). Наложение на многоугольник монохромного растрового изображения 32x32 (фактура)
- Star. Активизация и диактивизация отображения сторон многоугольников с помощью функции glEdgeFlag( GLboolean flag )
- Scissor. Вырезание прямоугольника, в котором выполняется визуализация

Глава 4. Геометрические преобразования: конвейер
« Последнее редактирование: Октябрь 15, 2014, 09:32 от 8Observer8 » Записан
8Observer8
Гость
« Ответ #1 : Сентябрь 05, 2014, 17:24 »

Установка Qt

- Скачайте и установите: "Qt 5.3.1 for Windows 32-bit (MinGW 4.8.2, OpenGL, 735 MB)" отсюда: http://qt-project.org/downloads

Примечание. Когда перейдёте по ссылке выше, то там надо будет нажать "Show downloads"
« Последнее редактирование: Сентябрь 15, 2014, 10:41 от 8Observer8 » Записан
8Observer8
Гость
« Ответ #2 : Сентябрь 05, 2014, 18:05 »

Переключение Qt Creator'a на английский

- Если у Вас Qt Creator на русском, то переключите на английский. Для этого выбираем в меню "Инструменты" -> "Параметры..."

- В окне "Параметры" слева выбираем "Среда" -> открываем вкладку "Основные" -> выбираем в выпадающем списке "English" -> нажимаем кнопку "OK" -> перезапускаем Qt Creator
« Последнее редактирование: Сентябрь 15, 2014, 10:42 от 8Observer8 » Записан
8Observer8
Гость
« Ответ #3 : Сентябрь 05, 2014, 18:36 »

Создание нового проекта

- В меню Qt Creator'а выбираем "File" -> "New File or Project..."

- В разделе "Projects" выбираем "Applications" -> во второй колонке выбираем "Qt Widgets Application" -> нажимаем кнопку "Choose..."

- В поле "Name" пишем: Simple -> нажимаем кнопку "Browse..." и указываем путь, где будет создан наш проект -> нажимаем два раза кнопку "Next" и выбираем в списке "Base class" значение "QDialog" -> нажимаем последовательно: два раза "Next", "Finish"

- В разделе "Projects" кликаем правой кнопкой мыши по имени проекта и выбираем "Add new..." -> выбираем "C++" -> выбираем "C++ Class" -> нажимаем кнопку "Choose..."

- Вводим имя класса Scene ( соответствующие файлы должны называться: Scene.h и Scene.cpp ) -> нажимаем кнопку "Finish"

- Копируем содержимое файлов (лучше стараться набирать самому, так легче понять)

Scene.h
Код
C++ (Qt)
#ifndef SCENE_H
#define SCENE_H
 
#include <QGLWidget>
 
class Scene : public QGLWidget
{
public:
   Scene( QWidget *parent = 0 );
 
private:
   void initializeGL();
   void paintGL();
};
 
#endif // SCENE_H
 

Scene.cpp
Код
C++ (Qt)
#include "Scene.h"
 
Scene::Scene( QWidget *parent ) :
   QGLWidget( parent )
{
}
 
void Scene::initializeGL()
{
   glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
}
 
void Scene::paintGL()
{
   // Clear the window with current clearing color
   glClear( GL_COLOR_BUFFER_BIT );
}
 

- Дважды кликаем по файлу "Simple.pro" и дописываем opengl, вот так:
Код
C++ (Qt)
QT       += core gui opengl
 

- Дважды кликаем по файлу "Dialog.ui" -> с левой панели перетаскиваем элемент "Widget" на форму

- Один раз кликаем на форму, чтобы выделить -> на панели инструментов (сверху) нажимаем кнопку с тремя горизонтальными голубыми чертами "Lay Out Vertically" (или Ctrl+L)

- Кликаем правой кнопкой мыши по элементу "Widget" -> выбираем "Promote to ..."

- В поле "Promoted class name" пишем: Scene -> нажимаем кнопку "Add" -> нажимаем кнопку "Promote"

- Запускаем приложение, для этого нажимаем зелёный треугольник слева внизу
« Последнее редактирование: Сентябрь 07, 2014, 09:38 от 8Observer8 » Записан
8Observer8
Гость
« Ответ #4 : Сентябрь 06, 2014, 09:20 »

02. Simple. Пустое окно



Simple.h
Код
C++ (Qt)
#ifndef SCENE_H
#define SCENE_H
 
#include <QGLWidget>
 
class Scene : public QGLWidget
{
public:
   Scene( QWidget *parent = 0 );
 
private:
   void initializeGL();
   void paintGL();
};
 
#endif // SCENE_H
 

Simple.cpp
Код
C++ (Qt)
#include "Scene.h"
 
Scene::Scene( QWidget *parent ) :
   QGLWidget( parent )
{
}
 
void Scene::initializeGL()
{
   glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
}
 
void Scene::paintGL()
{
   // Clear the window with current clearing color
   glClear( GL_COLOR_BUFFER_BIT );
}
 
« Последнее редактирование: Сентябрь 06, 2014, 14:56 от 8Observer8 » Записан
Igors
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 11445


Просмотр профиля
« Ответ #5 : Сентябрь 06, 2014, 12:00 »

Резкий переход от синего к красному - один из самых неприятных для человеческого глаза. Вообще использование красной заливки называется
Цитировать
дурачок красненькое любит
Улыбающийся
Записан
8Observer8
Гость
« Ответ #6 : Сентябрь 06, 2014, 13:40 »

02. GLRect. Квадрат



Scene.h
Код
C++ (Qt)
#ifndef SCENE_H
#define SCENE_H
 
#include <QGLWidget>
 
class Scene : public QGLWidget
{
public:
   Scene( QWidget *parent = 0 );
 
private:
   void initializeGL();
   void paintGL();
   void resizeGL( int w, int h );
};
 
#endif // SCENE_H
 

Scene.cpp
Код
C++ (Qt)
#include "Scene.h"
 
Scene::Scene( QWidget *parent ) :
   QGLWidget( parent )
{
}
 
void Scene::initializeGL()
{
   glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
}
 
void Scene::paintGL()
{
   // Clear the window with current clearing color
   glClear( GL_COLOR_BUFFER_BIT );
 
   // Set current drawing color to red
   //   R G   B
   glColor3f( 1.0f, 0.0f, 0.0f );
 
   // Draw a filled rectangle with current color
   glRectf( -25.0f, 25.0f, 25.0f, -25.0f );
}
 
void Scene::resizeGL( int w, int h )
{
   // Prevent a divide by zero
   if( h == 0 ) {
       h = 1;
   }
 
   // Set Viewport to window dimensions
   glViewport( 0, 0, w, h );
 
   // Reset coordinate system
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
 
   // Establish clipping volume (left, right, bottom, top, near, far)
   GLfloat aspectRatio = ( GLfloat )w / ( GLfloat )h;
   if ( w <= h ) {
       glOrtho( -100.0, 100.0, -100 / aspectRatio, 100.0 / aspectRatio,
                 1.0, -1.0);
   } else {
       glOrtho( -100.0 * aspectRatio, 100.0 * aspectRatio, -100.0, 100.0,
                1.0, -1.0 );
   }
 
   glMatrixMode( GL_MODELVIEW );
   glLoadIdentity();
}
 
« Последнее редактирование: Сентябрь 06, 2014, 14:56 от 8Observer8 » Записан
8Observer8
Гость
« Ответ #7 : Сентябрь 06, 2014, 13:41 »

02. Bounce. Анимированный квадрат



Scene.h
Код
C++ (Qt)
#ifndef SCENE_H
#define SCENE_H
 
#include <QGLWidget>
#include <QTimer>
 
class Scene : public QGLWidget
{
   Q_OBJECT
 
public:
   Scene( QWidget *parent = 0 );
 
private slots:
   void slotMoveRect();
 
private:
   void initializeGL();
   void paintGL();
   void resizeGL( int w, int h );
 
private:
   // Square position and size
   GLfloat x;
   GLfloat y;
   GLfloat rsize;
 
   // Step size in x and y directions
   // (number of pixels to move each time)
   GLfloat xstep;
   GLfloat ystep;
 
   // Keep track of windows changing width and height
   GLfloat windowWidth;
   GLfloat windowHeight;
 
   // Timer
   QTimer *timer;
};
 
#endif // SCENE_H
 

Scene.cpp
Код
C++ (Qt)
 
#include "Scene.h"
 
Scene::Scene( QWidget *parent ) :
   QGLWidget( parent ),
   x( 0.0f ),
   y( 0.0f ),
   rsize( 25.0f ),
   xstep( 1.0f ),
   ystep( 1.0f )
{
   timer = new QTimer( this );
   connect( timer, SIGNAL( timeout() ),
            this, SLOT( slotMoveRect() ) );
   timer->start( 33 );
}
 
void Scene::slotMoveRect()
{
   // Reverse direction when you reach left or right edge
   if( x > windowWidth - rsize || x < -windowWidth ) {
       xstep = -xstep;
   }
 
   // Reverse direction when you reach top or bottom edge
   if( y > windowHeight || y < -windowHeight + rsize ) {
       ystep = -ystep;
   }
 
   // Actually move the square
   x += xstep;
   y += ystep;
 
   // Check bounds. This is in case the window is made
   // smaller while the rectangle is bouncing and the
   // rectangle suddenly finds itself outside the new
   // clipping volume
   if( x > ( windowWidth-rsize + xstep ) ) {
       x = windowWidth - rsize - 1;
   } else if( x < -( windowWidth + xstep ) ) {
       x = -windowWidth - 1;
   }
 
   if( y > ( windowHeight + ystep ) ) {
       y = windowHeight - 1;
   } else if( y < -( windowHeight - rsize + ystep ) ) {
       y = -windowHeight + rsize - 1;
   }
 
   updateGL();
}
 
void Scene::initializeGL()
{
   glClearColor( 0.0f, 0.0f, 1.0f, 1.0f );
}
 
void Scene::paintGL()
{
   // Clear the window with current clearing color
   glClear( GL_COLOR_BUFFER_BIT );
 
   // Set current drawing color to red
   glColor3f( 1.0f, 0.0f, 0.0f );
 
   // Draw a filled rectangle with current color
   glRectf( x, y, x + rsize, y - rsize );
}
 
void Scene::resizeGL( int w, int h )
{
   // Prevent a divide by zero
   if ( h == 0 ) {
       h = 1;
   }
 
   // Set Viewport to window dimensions
   glViewport( 0, 0, w, h );
 
   // Reset coordinate system
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
 
   // Establish clipping volume (left, right, bottom, top, near, far)
   GLfloat aspectRatio = ( GLfloat ) w / ( GLfloat ) h;
 
   if ( w <= h ) {
       windowWidth = 100.0f;
       windowHeight = 100.0f / aspectRatio;
       glOrtho( -100.0, 100.0, -windowHeight, windowHeight,
                1.0, -1.0 );
   } else {
       windowWidth = 100.0 * aspectRatio;
       windowHeight = 100.0;
       glOrtho( -windowWidth, windowWidth, -100.0, 100.0,
                1.0, -1.0 );
   }
 
   glMatrixMode( GL_MODELVIEW );
   glLoadIdentity();
}
 
« Последнее редактирование: Сентябрь 12, 2014, 22:02 от 8Observer8 » Записан
8Observer8
Гость
« Ответ #8 : Сентябрь 06, 2014, 13:41 »

03. Points. Вращение с помощью стрелок 3D-спирали из точек



Scene.h
Код
C++ (Qt)
#ifndef SCENE_H
#define SCENE_H
 
#include <QGLWidget>
#include <QKeyEvent>
 
class Scene : public QGLWidget
{
public:
   Scene( QWidget *parent = 0 );
 
private:
   void initializeGL();
   void paintGL();
   void resizeGL( int w, int h );
 
   void keyPressEvent( QKeyEvent *event );
 
private:
   // Rotation amounts
   GLfloat xRot;
   GLfloat yRot;
};
 
#endif // SCENE_H
 

Scene.cpp
Код
C++ (Qt)
 
#include <math.h>
#include "Scene.h"
 
// Define a constant for the value of PI
#define GL_PI 3.1415f
 
Scene::Scene( QWidget *parent ) :
   QGLWidget( parent ),
   xRot( 0.0f ),
   yRot( 0.0f )
{
   this->setFocusPolicy( Qt::StrongFocus );
}
 
void Scene::initializeGL()
{
   // Black background
   glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
 
   // Set drawing color to green
   glColor3f( 0.0f, 1.0f, 0.0f );
}
 
void Scene::paintGL()
{
   // Storeage for coordinates and angles
   GLfloat x, y, z, angle;
 
   // Clear the window with current clearing color
   glClear( GL_COLOR_BUFFER_BIT );
 
   // Save matrix state and do the rotation
   glPushMatrix();
   glRotatef( xRot, 1.0f, 0.0f, 0.0f );
   glRotatef( yRot, 0.0f, 1.0f, 0.0f );
 
   // Call only once for all remaining points
   glBegin( GL_POINTS );
 
   z = -50.0f;
   for( angle = 0.0f; angle <= ( 2.0f * GL_PI ) * 3.0f; angle += 0.1f )
   {
       x = 50.0f * sin( angle );
       y = 50.0f * cos( angle  );
 
       // Specify the point and move the Z value up a little
       glVertex3f( x, y, z );
       z += 0.5f;
   }
 
   // Done drawing points
   glEnd();
 
   // Restore transformations
   glPopMatrix();
}
 
void Scene::resizeGL( int w, int h )
{
   // Prevent a divide by zero
   if( h == 0 ) {
       h = 1;
   }
 
   // Set Viewport to window dimensions
   glViewport( 0, 0, w, h );
 
   // Reset projection matrix stack
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
 
   GLfloat nRange = 100.0f;
 
   // Establish clipping volume (left, right, bottom, top, near, far)
   if ( w <= h ) {
       glOrtho ( -nRange, nRange, -nRange*h/w, nRange*h/w,
                 -nRange, nRange );
   } else {
       glOrtho ( -nRange*w/h, nRange*w/h, -nRange, nRange,
                 -nRange, nRange );
   }
 
   // Reset Model view matrix stack
   glMatrixMode( GL_MODELVIEW );
   glLoadIdentity();
}
 
void Scene::keyPressEvent( QKeyEvent *event )
{
   switch ( event->key() ) {
   case Qt::Key_Up:
       xRot -= 5.0f;
       break;
   case Qt::Key_Down:
       xRot += 5.0f;
       break;
   case Qt::Key_Left:
       yRot -= 5.0f;
       break;
   case Qt::Key_Right:
       yRot += 5.0f;
       break;
   }
 
   if( xRot > 356.0f ) {
       xRot = 0.0f;
   }
 
   if( xRot < -1.0f ) {
       xRot = 355.0f;
   }
 
   if( yRot > 356.0f) {
       yRot = 0.0f;
   }
 
   if( yRot < -1.0f) {
       yRot = 355.0f;
   }
 
   updateGL();
}
 
« Последнее редактирование: Сентябрь 06, 2014, 15:41 от 8Observer8 » Записан
8Observer8
Гость
« Ответ #9 : Сентябрь 06, 2014, 15:51 »

Pointsz. Спираль, точки которой увеличиваются от минимально возможной по размеру до максимально возможной



Scene.h
Код
C++ (Qt)
#ifndef SCENE_H
#define SCENE_H
 
#include <QGLWidget>
#include <QKeyEvent>
 
class Scene : public QGLWidget
{
public:
   Scene( QWidget *parent = 0 );
 
private:
   void initializeGL();
   void paintGL();
   void resizeGL( int w, int h );
 
   void keyPressEvent( QKeyEvent *event );
 
private:
   // Rotation amounts
   GLfloat xRot;
   GLfloat yRot;
};
 
#endif // SCENE_H
 

Scene.cpp
Код
C++ (Qt)
 
#include <math.h>
#include "Scene.h"
 
// Define a constant for the value of PI
#define GL_PI 3.1415f
 
Scene::Scene( QWidget *parent ) :
   QGLWidget( parent ),
   xRot( 0.0f ),
   yRot( 0.0f )
{
   this->setFocusPolicy( Qt::StrongFocus );
}
 
void Scene::initializeGL()
{
   // Black background
   glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
 
   // Set drawing color to green
   glColor3f( 0.0f, 1.0f, 0.0f );
}
 
void Scene::paintGL()
{
   GLfloat x, y, z, angle;    // Storeage for coordinates and angles
   GLfloat sizes[2];          // Store supported point size range
   GLfloat step;              // Store supported point size increments
   GLfloat curSize;           // Store current size
 
   // Clear the window with current clearing color
   glClear( GL_COLOR_BUFFER_BIT );
 
   // Save matrix state and do the rotation
   glPushMatrix();
   glRotatef( xRot, 1.0f, 0.0f, 0.0f );
   glRotatef( yRot, 0.0f, 1.0f, 0.0f );
 
   // Get supported point size range and step size
   glGetFloatv( GL_POINT_SIZE_RANGE, sizes );
   glGetFloatv( GL_POINT_SIZE_GRANULARITY, &step );
 
   // Set the initial point size
   curSize = sizes[0];
 
   // Set beginning z coordinate
   z = -50.0f;
 
   // Loop around in a circle three times
   for( angle = 0.0f; angle <= ( 2.0f * 3.1415f ) * 3.0f; angle += 0.1f ) {
       // Calculate x and y values on the circle
       x = 50.0f * sin( angle );
       y = 50.0f * cos( angle );
 
       // Specify the point size before the primative is specified
       glPointSize( curSize );
 
       // Draw the point
       glBegin( GL_POINTS );
       glVertex3f( x, y, z );
       glEnd();
 
       // Bump up the z value and the point size
       z += 0.5f;
       curSize += step;
   }
 
   // Restore matrix state
   glPopMatrix();
}
 
void Scene::resizeGL( int w, int h )
{
   // Prevent a divide by zero
   if( h == 0 ) {
       h = 1;
   }
 
   // Set Viewport to window dimensions
   glViewport( 0, 0, w, h );
 
   // Reset projection matrix stack
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
 
   GLfloat nRange = 100.0f;
 
   // Establish clipping volume (left, right, bottom, top, near, far)
   if ( w <= h ) {
       glOrtho ( -nRange, nRange, -nRange*h/w, nRange*h/w,
                 -nRange, nRange );
   } else {
       glOrtho ( -nRange*w/h, nRange*w/h, -nRange, nRange,
                 -nRange, nRange );
   }
 
   // Reset Model view matrix stack
   glMatrixMode( GL_MODELVIEW );
   glLoadIdentity();
}
 
void Scene::keyPressEvent( QKeyEvent *event )
{
   switch ( event->key() ) {
   case Qt::Key_Up:
       xRot -= 5.0f;
       break;
   case Qt::Key_Down:
       xRot += 5.0f;
       break;
   case Qt::Key_Left:
       yRot -= 5.0f;
       break;
   case Qt::Key_Right:
       yRot += 5.0f;
       break;
   }
 
   if( xRot > 356.0f ) {
       xRot = 0.0f;
   }
 
   if( xRot < -1.0f ) {
       xRot = 355.0f;
   }
 
   if( yRot > 356.0f) {
       yRot = 0.0f;
   }
 
   if( yRot < -1.0f) {
       yRot = 355.0f;
   }
 
   updateGL();
}
 
Записан
Igors
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 11445


Просмотр профиля
« Ответ #10 : Сентябрь 06, 2014, 16:49 »

Pointsz. Спираль, точки которой увеличиваются от минимально возможной по размеру до максимально возможной
Браво, первое проявление хоть какого-то творчества. Только вот что ее ось растет так уныло - по прямой снизу вверх? Гораздо интереснее по кривой - ну или хотя бы по кругу. Радиус самой спирали уменьшить и использовать GL_LINES (вместо GL_POINTS).

[off]Безнадюга конечно - зубрилки таких задач не решают. Ну а вдруг?[/off]
Записан
8Observer8
Гость
« Ответ #11 : Сентябрь 06, 2014, 17:16 »

Igors, если у вас ещё возникнут задачи, то пишите! Как у меня накопятся мысли, то я создам дополнительную побочную тему с примерами. Не хочется в этой дискутировать Улыбающийся
Записан
8Observer8
Гость
« Ответ #12 : Сентябрь 06, 2014, 20:00 »

03. Lines. Отображает набор линий, веером расходящихся по окружности



Scene.h
Код
C++ (Qt)
#ifndef SCENE_H
#define SCENE_H
 
#include <QGLWidget>
#include <QKeyEvent>
 
class Scene : public QGLWidget
{
public:
   Scene( QWidget *parent = 0 );
 
private:
   void initializeGL();
   void paintGL();
   void resizeGL( int w, int h );
 
   void keyPressEvent( QKeyEvent *event );
 
private:
   // Rotation amounts
   GLfloat xRot;
   GLfloat yRot;
};
 
#endif // SCENE_H
 

Scene.cpp
Код
C++ (Qt)
 
#include <math.h>
#include "Scene.h"
 
// Define a constant for the value of PI
#define GL_PI 3.1415f
 
Scene::Scene( QWidget *parent ) :
   QGLWidget( parent ),
   xRot( 0.0f ),
   yRot( 0.0f )
{
   this->setFocusPolicy( Qt::StrongFocus );
}
 
void Scene::initializeGL()
{
   // Black background
   glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
 
   // Set drawing color to green
   glColor3f( 0.0f, 1.0f, 0.0f );
}
 
void Scene::paintGL()
{
   // Storeage for coordinates and angles
   GLfloat x, y, z, angle;
 
   // Clear the window with current clearing color
   glClear( GL_COLOR_BUFFER_BIT );
 
   // Save matrix state and do the rotation
   glPushMatrix();
   glRotatef( xRot, 1.0f, 0.0f, 0.0f );
   glRotatef( yRot, 0.0f, 1.0f, 0.0f );
 
   // Call only once for all remaining points
   glBegin( GL_LINES );
 
   z = 0.0f;
   for( angle = 0.0f; angle <= GL_PI; angle += ( GL_PI / 20.0f ) ) {
       // Top half of the circle
       x = 50.0f * sin( angle );
       y = 50.0f * cos( angle );
       glVertex3f( x, y, z );
 
       // Bottom half of the circle
       x = 50.0f * sin( angle + GL_PI);
       y = 50.0f * cos( angle + GL_PI );
       glVertex3f( x, y, z );
   }
 
   // Done drawing points
   glEnd();
 
   // Restore transformations
   glPopMatrix();
}
 
void Scene::resizeGL( int w, int h )
{
   // Prevent a divide by zero
   if( h == 0 ) {
       h = 1;
   }
 
   // Set Viewport to window dimensions
   glViewport( 0, 0, w, h );
 
   // Reset projection matrix stack
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
 
   GLfloat nRange = 100.0f;
 
   // Establish clipping volume (left, right, bottom, top, near, far)
   if ( w <= h ) {
       glOrtho ( -nRange, nRange, -nRange*h/w, nRange*h/w,
                 -nRange, nRange );
   } else {
       glOrtho ( -nRange*w/h, nRange*w/h, -nRange, nRange,
                 -nRange, nRange );
   }
 
   // Reset Model view matrix stack
   glMatrixMode( GL_MODELVIEW );
   glLoadIdentity();
}
 
void Scene::keyPressEvent( QKeyEvent *event )
{
   switch ( event->key() ) {
   case Qt::Key_Up:
       xRot -= 5.0f;
       break;
   case Qt::Key_Down:
       xRot += 5.0f;
       break;
   case Qt::Key_Left:
       yRot -= 5.0f;
       break;
   case Qt::Key_Right:
       yRot += 5.0f;
       break;
   }
 
   if( xRot > 356.0f ) {
       xRot = 0.0f;
   }
 
   if( xRot < -1.0f ) {
       xRot = 355.0f;
   }
 
   if( yRot > 356.0f) {
       yRot = 0.0f;
   }
 
   if( yRot < -1.0f) {
       yRot = 355.0f;
   }
 
   updateGL();
}
 
Записан
8Observer8
Гость
« Ответ #13 : Сентябрь 06, 2014, 21:43 »

03. LStrips. Аппроксимация кривых прямолинейными отрезками



Scene.h
Код
C++ (Qt)
#ifndef SCENE_H
#define SCENE_H
 
#include <QGLWidget>
#include <QKeyEvent>
 
class Scene : public QGLWidget
{
public:
   Scene( QWidget *parent = 0 );
 
private:
   void initializeGL();
   void paintGL();
   void resizeGL( int w, int h );
 
   void keyPressEvent( QKeyEvent *event );
 
private:
   // Rotation amounts
   GLfloat xRot;
   GLfloat yRot;
};
 
#endif // SCENE_H
 

Scene.cpp
Код
C++ (Qt)
 
#include <math.h>
#include "Scene.h"
 
// Define a constant for the value of PI
#define GL_PI 3.1415f
 
Scene::Scene( QWidget *parent ) :
   QGLWidget( parent ),
   xRot( 0.0f ),
   yRot( 0.0f )
{
   this->setFocusPolicy( Qt::StrongFocus );
}
 
void Scene::initializeGL()
{
   // Black background
   glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
 
   // Set drawing color to green
   glColor3f( 0.0f, 1.0f, 0.0f );
}
 
void Scene::paintGL()
{
   // Storeage for coordinates and angles
   GLfloat x, y, z, angle;
 
   // Clear the window with current clearing color
   glClear( GL_COLOR_BUFFER_BIT );
 
   // Save matrix state and do the rotation
   glPushMatrix();
   glRotatef( xRot, 1.0f, 0.0f, 0.0f );
   glRotatef( yRot, 0.0f, 1.0f, 0.0f );
 
   // Call only once for all remaining points
   glBegin( GL_LINE_STRIP );
 
   z = -50.0f;
   for( angle = 0.0f; angle <= ( 2.0f*3.1415f )*3.0f; angle += 0.1f ) {
       x = 50.0f * sin( angle );
       y = 50.0f * cos( angle );
 
       // Specify the point and move the Z value up a little
       glVertex3f( x, y, z );
       z += 0.5f;
   }
 
   // Done drawing points
   glEnd();
 
   // Restore transformations
   glPopMatrix();
}
 
void Scene::resizeGL( int w, int h )
{
   // Prevent a divide by zero
   if( h == 0 ) {
       h = 1;
   }
 
   // Set Viewport to window dimensions
   glViewport( 0, 0, w, h );
 
   // Reset projection matrix stack
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
 
   GLfloat nRange = 100.0f;
 
   // Establish clipping volume (left, right, bottom, top, near, far)
   if ( w <= h ) {
       glOrtho ( -nRange, nRange, -nRange*h/w, nRange*h/w,
                 -nRange, nRange );
   } else {
       glOrtho ( -nRange*w/h, nRange*w/h, -nRange, nRange,
                 -nRange, nRange );
   }
 
   // Reset Model view matrix stack
   glMatrixMode( GL_MODELVIEW );
   glLoadIdentity();
}
 
void Scene::keyPressEvent( QKeyEvent *event )
{
   switch ( event->key() ) {
   case Qt::Key_Up:
       xRot -= 5.0f;
       break;
   case Qt::Key_Down:
       xRot += 5.0f;
       break;
   case Qt::Key_Left:
       yRot -= 5.0f;
       break;
   case Qt::Key_Right:
       yRot += 5.0f;
       break;
   }
 
   if( xRot > 356.0f ) {
       xRot = 0.0f;
   }
 
   if( xRot < -1.0f ) {
       xRot = 355.0f;
   }
 
   if( yRot > 356.0f) {
       yRot = 0.0f;
   }
 
   if( yRot < -1.0f) {
       yRot = 355.0f;
   }
 
   updateGL();
}
 
Записан
Igors
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 11445


Просмотр профиля
« Ответ #14 : Сентябрь 07, 2014, 08:47 »

Igors, если у вас ещё возникнут задачи, то пишите! Как у меня накопятся мысли, то я создам дополнительную побочную тему с примерами. Не хочется в этой дискутировать Улыбающийся
Та что там жалкие 2 десятка строк дискутировать.
Записан
Страниц: [1] 2   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.483 секунд. Запросов: 22.