Я использую glut вместе с OpenGL.
В своём приложении я рисую, белый, квадратный полигон. Без использования
imgui всё прекрасно рисуется и никаких проблем не возникает.
Но теперь мне нужно добавить GUI в своё приложение и я выбрал для этих целей
imgui, т.к. иного, что поддерживало бы работу с glut я не нашёл(если вы знаете, напишите).
При создании кода я руководствовался
этим кодом.
Проблема в том, что в итоге, моя программа рисует окно
imgui, но своего квадрата я не вижу.
С помощью класса
Camera я могу перемещаться по сцене, его реализацию можно найти
тут, я полагаю что проблема может быть из-за него.
Вот скриншот с программой без
imgui![63703922-9f6ab000-c832-11e9-9d49-7c82def](https://user-images.githubusercontent.com/37502620/63703922-9f6ab000-c832-11e9-9d49-7c82def08439.png)
А вот с созданием окна
imgui![63703933-a396cd80-c832-11e9-8c94-92f97cc](https://user-images.githubusercontent.com/37502620/63703933-a396cd80-c832-11e9-8c94-92f97ccce837.png)
А вот код программы:
#include <iostream>
#include <chrono>
#include <vector>
#include <memory>
#include <GL/glut.h>
#include <soil.h>
#include "camera.h"
#include "imgui.h"
#include "imgui_impl_glut.h"
#include "imgui_impl_opengl2.h"
#ifdef _MSC_VER
#pragma warning (disable: 4505) // unreferenced local function has been removed
#endif
#define GL_CLAMP_TO_EDGE 0x812F
using namespace std;
constexpr auto FPS_RATE = 120;
int windowHeight = 600, windowWidth = 1000, windowDepth = 600;
//for camera
struct MyPoint3f { float x; float y; float z; };
MyPoint3f lastMousePos = { };
bool mouseButtonWasPressed = false;
float mouseSensitivity = 0.00125f;
int camMoveSpeed = 1;
float camPitchAngle = 0, camYawAngle = 0;
float currentCamPitchAngle = 0, currentCamYawAngle = 0;
Camera cam;
//OpenGL
int groundImageWidth = 0, groundImageHeight = 0;
unsigned char* groundImage = 0;
GLuint groundTexture = 0;
void init();
void displayFunction();
void idleFunction();
void reshapeFunction(int, int);
void keyboardFunction(unsigned char, int, int);
void specialKeysFunction(int, int, int);
void mouseFunc(int, int, int, int);
void motionFunction(int, int);
double getTime();
double getTime()
{
using Duration = std::chrono::duration<double>;
return std::chrono::duration_cast<Duration>(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count();
}
const float frame_delay = 1.0f / FPS_RATE;
double last_render = 0;
void init()
{
//load texture image
groundImage = SOIL_load_image("groundTexture.jpg", &groundImageWidth, &groundImageHeight, 0, SOIL_LOAD_RGB);
if (!groundImage)
MessageBox(NULL, L"Load image falded", L"Error", MB_OK);
//generate 1 texture
glGenTextures(1, &groundTexture);
//setting callback functions
glutDisplayFunc(displayFunction);
glutIdleFunc(idleFunction);
glutReshapeFunc(reshapeFunction);
glutKeyboardFunc(keyboardFunction);
glutMouseFunc(mouseFunc);
glutMotionFunc(motionFunction);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glClearColor(117.0f / 255.0f, 187.0f / 255.0f, 253.0f / 255.0f, 0.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//setting cam
cam.SetPosition(glm::vec3(0.f, 100.f, 350.f));
cam.SetLookAt(glm::vec3(0.f, 100.f, 349.f));
cam.SetClipping(0.1f, 2000.f);
cam.SetFOV(45);
}
static bool showWindow = true;
void displayFunction()
{
if (abs(currentCamPitchAngle + -(camPitchAngle * mouseSensitivity)) < 0.90)
cam.ChangePitch(-(camPitchAngle * mouseSensitivity));
cam.ChangeHeading((camYawAngle * mouseSensitivity));
if (abs(currentCamPitchAngle + -(camPitchAngle * mouseSensitivity)) < 0.90)
currentCamPitchAngle += -(camPitchAngle * mouseSensitivity);
currentCamYawAngle += -(camYawAngle * mouseSensitivity);
camPitchAngle = 0; camYawAngle = 0;
//create imgui new frame
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplGLUT_NewFrame();
//draw window
if (showWindow)
{
ImGui::Begin("Another Window", &showWindow); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
showWindow = false;
ImGui::End();
}
//clear screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//set camera
glm::mat4 model, view, projection;
cam.Update();
cam.GetMatricies(projection, view, model);
glm::mat4 mvp = projection * view * model;
glLoadMatrixf(glm::value_ptr(mvp));
glMatrixMode(GL_MODELVIEW);
//draw white polygon
glBegin(GL_POLYGON);
glVertex3i(-150, 150, 0);
glVertex3i(150, 150, 0);
glVertex3i(150, -150, 0);
glVertex3i(-150, -150, 0);
glEnd();
//render
ImGui::Render();
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
glutSwapBuffers();
}
void idleFunction()
{
const double current_time = getTime();
if ((current_time - last_render) > frame_delay)
{
last_render = current_time;
glutPostRedisplay();
}
}
void reshapeFunction(int w, int h)
{
cam.SetViewport(0, 0, windowWidth, windowHeight);
}
void keyboardFunction(unsigned char key, int w, int h)
{
switch (key)
{
case '+': case '=':
break;
case '-': case '_':
break;
case 'w': case 'W':
for (int z = 0; z < camMoveSpeed; ++z)
cam.Move(FORWARD);
break;
case 'a': case 'A':
for (int z = 0; z < camMoveSpeed; ++z)
cam.Move(LEFT);
break;
case 's': case 'S':
for (int z = 0; z < camMoveSpeed; ++z)
cam.Move(BACK);
break;
case 'd': case 'D':
for (int z = 0; z < camMoveSpeed; ++z)
cam.Move(RIGHT);
break;
case 'q': case 'Q':
for (int z = 0; z < camMoveSpeed; ++z)
cam.Move(DOWN);
break;
case 'e': case 'E':
for (int z = 0; z < camMoveSpeed; ++z)
cam.Move(UP);
break;
case 27:
currentCamPitchAngle = 0;
currentCamYawAngle = 0;
break;
default:
cout << key << endl;
break;
}
}
void specialKeysFunction(int key, int x, int y)
{
cout << key << endl;
}
void mouseFunc(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
mouseButtonWasPressed = true;
lastMousePos.x = (float)x;
lastMousePos.y = (float)y;
}
}
void motionFunction(int mousePosX, int mousePosY)
{
if (mousePosX >= 0 && mousePosX < windowWidth && mousePosY >= 0 && mousePosY < windowHeight)
{
if (mouseButtonWasPressed)
{
camPitchAngle += -mousePosY + lastMousePos.y;
camYawAngle += (float)mousePosX - lastMousePos.x;
lastMousePos.x = (float)mousePosX;
lastMousePos.y = (float)mousePosY;
}
}
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(windowWidth, windowHeight);
glutInitWindowPosition((GetSystemMetrics(SM_CXSCREEN) - windowWidth) / 2, (GetSystemMetrics(SM_CYSCREEN) - windowHeight) / 2);
glutCreateWindow("Window");
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
init();
//imgui setup
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplGLUT_Init();
ImGui_ImplGLUT_InstallFuncs();
ImGui_ImplOpenGL2_Init();
glutMainLoop();
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplGLUT_Shutdown();
ImGui::DestroyContext();
return 0;
}