Читаем MFC и OpenGL полностью

  0, 0, 0, 0, 0, 0, // color bits ignored

  0, // no alpha buffer

  0, // shift bit ignored

  0, // no accumulation buffer

  0, 0, 0, 0, // accum bits ignored

  32, // 32-bit z-buffer

  0, // no stencil buffer

  0, // no auxiliary buffer

  PFD_MAIN_PLANE, // main layer

  0, // reserved

  0, 0, 0 // layer masks ignored

 };

 int pixelformat;

 if ((pixelformat = ChoosePixelFormat(pDC->GetSafeHdc(), &pfd)) == 0) {

  MessageBox("ChoosePixelFormat failed");

  return FALSE;

 }

 if (SetPixelFormat(pDC->GetSafeHdc(), pixelformat, &pfd) == FALSE) {

  MessageBox("SetPixelFormat failed");

  return FALSE;

 }

 return TRUE;

}

Как не трудно заметить, она почти полностью взята из Win32API приложения за исключением того, что hDC заменена на pDC->GetSafeHdc().

Теперь добавим в нашу программку обработчик от таймера (мы его недавно сделали в ф-ции Init())

void CBitScrollDlg::OnTimer(UINT nIDEvent) {

 DrawScene();

 CDialog::OnTimer(nIDEvent);

}

Все тривиально. По смыслу ясно, что каждый раз, когда срабатывает обработчик таймера (а делает он это часто) рисуется сцена. Таким образом получается анимация. Посмотрим на эту функцию:

void CBitScrollDlg::DrawScene() {

 static GLfloat angle = 0;

 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

 glLoadIdentity();

 glTranslatef(0.0f, 0.0f, –2.0f);

 glRotatef(angle, 1.0f, 0.5f, 0.3f);

 glBegin(GL_QUADS);

 glColor3f(1.0f, 0.0f, 1.0f);

 glVertex3f(-0.5f, 0.5f, 0.0f);

 glColor3f(1.0f, 1.0f, 1.0f);

 glVertex3f(0.5f, 0.5f, 0.0f);

 glColor3f(0.0f, 1.0f, 1.0f);

 glVertex3f(0.5f, –0.5f, 0.0f);

 glColor3f(0.0f, 0.0f, 1.0f);

 glVertex3f(-0.5f, –0.5f, 0.0f);

 glEnd();

 glFinish();

 SwapBuffers(wglGetCurrentDC());

 angle += 0.5f;

}

По моему проще уже некуда. Я надеюсь, что все ясно.

Ну вот казалось бы и все. Единственное, что остается сделать – убраться за собой. Т.е. надо при выходе удалить контекст рендеринга и убить таймер.

Эти вещи надо сделать в 2-х обработчиках OnClose и OnDestroy. Посмотрим на них:

void CBitScrollDlg::OnClose() {

 // TODO: Add your message handler code here and/or call default

 HGLRC hrc;

 KillTimer(1);

 hrc = ::wglGetCurrentContext();

 ::wglMakeCurrent(NULL, NULL);

 if (hrc) ::wglDeleteContext(hrc);

 CDialog::OnClose();

}

и

void CBitScrollDlg::OnDestroy() {

 CDialog::OnDestroy();

 // TODO: Add your message handler code here

 HGLRC hrc;

 KillTimer(1);

 hrc = ::wglGetCurrentContext();

 ::wglMakeCurrent(NULL, NULL);

 if (hrc) ::wglDeleteContext(hrc);

}

Она практически одинаковые. Работают так же как и case WM_CLOSE в Win32API. Т.е. убиваем таймер, получаем контекст рендеринга, если он есть – удаляем его.

Ну вот и все. Еще добавлю, что в проекте есть функция OnSize для обработки изменений размеров окна. В данном случае она не нужна, но если вставлять OpenGL в SDI или MDI, то она вам понадобится.

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных
1001 совет по обустройству компьютера
1001 совет по обустройству компьютера

В книге собраны и обобщены советы по решению различных проблем, которые рано или поздно возникают при эксплуатации как экономичных нетбуков, так и современных настольных моделей. Все приведенные рецепты опробованы на практике и разбиты по темам: аппаратные средства персональных компьютеров, компьютерные сети и подключение к Интернету, установка, настройка и ремонт ОС Windows, работа в Интернете, защита от вирусов. Рассмотрены не только готовые решения внезапно возникающих проблем, но и ответы на многие вопросы, которые возникают еще до покупки компьютера. Приведен необходимый минимум технических сведений, позволяющий принять осознанное решение.Компакт-диск прилагается только к печатному изданию книги.

Юрий Всеволодович Ревич

Программирование, программы, базы данных / Интернет / Компьютерное «железо» / ОС и Сети / Программное обеспечение / Книги по IT