I am trying to set up openGl with glfw and glew. This is the source code:
#define GLFW_INCLUDE_GLU
#ifdef _WIN32
#define GLFW_DLL // -> windows
#include <GL/glew.h>
#elif __linux__
#include <GL/glew.h>
#endif
#include <GLFW/glfw3.h>
#include <iostream>
#include <stdexcept>
GLFWwindow* window = NULL;
GLFWmonitor* monitor = NULL;
int window_width = 800;
int window_height = 600;
static void window_hints() {
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
}
static void set_window_callbacks() {
glfwSetWindowCloseCallback(window, [] (GLFWwindow *window) {
std::cout << "closing window!";
});
glfwSetKeyCallback(window, [] (GLFWwindow *window, int key,int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
});
glfwSetWindowSizeCallback(window, [] (GLFWwindow *window, int width, int height) {
glViewport(0, 0, width, height);
window_width = width;
window_height = height;
glLoadIdentity();
GLdouble aspect = (GLdouble)window_width / window_height;
glOrtho(-1, 1, -1 / aspect, 1 / aspect, 0.01, 10000);
glTranslatef(0, 0, -10);
});
}
void GLAPIENTRY
MessageCallback( GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam )
{
fprintf( stderr, "GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n",
( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ),
type, severity, message );
}
int main(int argc, char *argv[])
{
glfwSetErrorCallback([] (int code, const char * err_msg) {
std::cerr << "GLFW Error " << code << ": \n\t" << err_msg << std::endl;
});
if(!glfwInit())
throw std::runtime_error("glfwInit failed");
monitor = glfwGetPrimaryMonitor();
window_hints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
window = glfwCreateWindow(window_width, window_height, "test window", NULL, NULL);
if(!window)
throw std::runtime_error("glfwOpenWindow failed.");
set_window_callbacks();
// GLFW settings
glfwMakeContextCurrent(window);
glewInit();
glfwSwapInterval(1);
std::cout << glGetString(GL_VERSION) << std::endl;
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(MessageCallback, 0);
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, window_width, window_height);
glLoadIdentity();
GLdouble aspect = (GLdouble)window_width / window_height;
glOrtho(-1, 1, -1 / aspect, 1 / aspect, 0.01, 10000);
glTranslatef(0, 0, -10);
while(!glfwWindowShouldClose(window))
{
// process pending events
glfwPollEvents();
glClearColor(0, 0, 0, 1); // black
glClear(GL_COLOR_BUFFER_BIT);
//glRotatef(1, 0, 0, 0.1);
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(-0.5, -0.5);
glColor3f(0.0, 1.0, 0.0);
glVertex2f( 0.5, -0.5);
glColor3f(0.0, 0.0, 1.0);
glVertex2f( 0.0, 0.5);
glEnd();
glfwSwapBuffers(window);
}
// clean up and exit
glfwTerminate();
std::cerr << std::endl;
return 0;
}
And this works perfectly under Linux with the following makefile:
main: main.cpp makefile
g++ main.cpp -g -o main -lglfw -lGL -lX11 -lGLEW -std=c++2a
Then, I wanted to make it to compile under windows too, so I tried with this makefile:
main.exe: main.cpp makefile
g++ main.cpp -g -o main.exe -I"D:\cpp_libraries\glfw-3.3.5.bin.WIN64\include" -I"D:\cpp_libraries\glew-2.1.0\include" -L"D:\cpp_libraries\glfw-3.3.5.bin.WIN64\lib-mingw-w64" -L"D:\cpp_libraries\glew-2.1.0\lib\Release\x64" -lglfw3dll -lglew32 -lopengl32
Here, "glew-2.1.0" and "glfw-3.3.5.bin.WIN64" are downloaded from the respective download pages for precompiled windows binaries. I have added "D:\cpp_libraries\glew-2.1.0\bin\Release\x64" and "D:\cpp_libraries\glfw-3.3.5.bin.WIN64\lib-mingw-w64" to the Path environment variable as they contain glew32.dll and glfw3.dll.
When I try to compile, g++ gives "undefined reference to " every single glew/gl/glfw function call. I also tried running the same g++ command through VS Code's tasks.json with the same result.
Then I noticed that everyone on the internet said I must link against "glfw3.lib" and I noticed that the first -L argument to g++ is a folder that does not actually contain any .lib files as it should. But I cannot find the "glfw3.lib" anywhere in the zip I downloaded earlier. I even tried building glfw from source with CMake, Make and Code::Blocks, but none of them generated a .lib file I can link against.
Edit: I forgot to mention that I have not added the dlls to my project directory, but it really should not be necessary. I tried it anyway and it didn't fix the problem.
Edit 2: it would be better to link with -lglfw, not -lglfwdll, so I changed that.
Edit 3: actually, gl functions are getting linked fine. The problem is only with glfw and glew.
I finally got it working. It turns out the precompiled binaries for glew and glfw do not work on my machine. I had to download both sources and compile the libraries myself. This is the makefile that finally works:
main.exe: main.cpp makefile
g++ main.cpp -g -o main.exe -I"D:/cpp_libraries/glfw-3.3.5-source/include" -I"D:/cpp_libraries/glew-2.1.0-source/include" -L"D:/cpp_libraries/glfw-3.3.5-compiled/src" -L"D:/cpp_libraries/glew-2.1.0-compiled/lib" -lglfw3 -lglew32 -lopengl32
Related
I've writed a toy example using OpenGL and c++
#include <GL/glut.h>
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glOrtho(-5, 5, -5, 5, 5, 15);
glMatrixMode(GL_MODELVIEW);
gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0);
return;
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0, 0);
glutWireTeapot(3);
glFlush();
return;
}
void test()
{
int argc = 0;
char **argv=NULL;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowPosition(0, 0);
glutInitWindowSize(300, 300);
glutCreateWindow("OpenGL 3D View");
init();
glutDisplayFunc(display);
glutMainLoop();
}
And then build the code using
gcc -o test test.c -lGL -lGLU -lglut
It works fine. But I want to call this function in Python, than I've tried
# include <pybind11/pybind11.h>
...
PYBIND11_MODULE(py2cpp, m)
{
m.doc() = "opengl test";
m.def("display", &test, "test opengl");
}
Build code above using
g++ -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` -lGL -lGLU -lglut test.cpp -o py2cpp`python3-config --extension-suffix` -I /home/xiaohanbao/anaconda3/envs/ros/include/python3.8
I compiled the code successfully. But when I import the library using import py2cpp, I got
Import Error: /path/py2cpp.cpython-38-x86_64-linux-gnu.so: undefined symbol: glutInitWindowPosition
Is there any way to fix it?
I've tried to set the window icon from the scripts within the stackoverflow questions below, but nothing did work to my solution
GLFW SetWindowIcon
https://learn.microsoft.com/en-us/windows/win32/menurc/using-icons
My entire main.cpp from my solution:
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include <string>
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <Windows.h>
#include <WinUser.h>
#include <WinNls32.h>
int main()
{
// Create a custom icon at run time.
// Initialize GLFW
glfwInit();
// Tell GLFW what version of OpenGL we are using
// In this case we are using OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// Tell GLFW we are using the CORE profile
// So that means we only have the modern functions
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create a GLFWwindow object of 800 by 800 pixels, naming it "YoutubeOpenGL"
GLFWwindow* window = glfwCreateWindow(1200, 700, "Dessor 0.1.0c", NULL, NULL);
// Error check if the window fails to create
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
// Introduce the window into the current context
glfwMakeContextCurrent(window);
//Load GLAD so it configures OpenGL
gladLoadGL();
// Specify the viewport of OpenGL in the Window
// In this case the viewport goes from x = 0, y = 0, to x = 800, y = 800
glViewport(0, 0, 1200, 700);
// Initialize ImGUI
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 330");
// Variables to be changed in the ImGUI window
bool drawCube = false;
float size = 1.0f;
float color[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
// Main while loop
while (!glfwWindowShouldClose(window))
{
// Specify the color of the background
glClearColor(0.11f, 0.11f, 0.11f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Clean the back buffer and assign the new color to it
// Tell OpenGL a new frame is about to begin
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
if (drawCube)
glClearColor(0.01f, 0.01f, 0.01f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// ImGUI window creation
// Particular widget styling
static int i2 = 3;
static int ifov = 60;
static float size = 3.0;
static char name[128] = "5";
static const ImVec4 edge_color = ImVec4(0.25f, 0.25f, 0.90f, 1.00f);
static const ImVec4 inside_color = ImVec4(0.55f, 0.55f, 0.90f, 1.00f);
const ImVec2 size2 = ImVec2(250, 200);
ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 0, 0, 255));
ImGui::Begin("Drawing HyperCube Options", NULL, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::PopStyleColor();
ImGui::Checkbox("Draw Shape", &drawCube);
ImGui::SliderInt("D", &i2, 0, atoi(name), "%d-dimensional hypercube");
ImGui::InputText("", name, 7, ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_EnterReturnsTrue);
ImGui::SameLine();
ImGui::TextColored(ImVec4(255, 0, 255, 255), name);
ImGui::NewLine();
ImGui::SliderFloat("SIZE", &size, 1.0, 10.0);
ImGui::SliderInt("FOV", &ifov, 30, 120, "%d");
ImGui::NewLine();
ImGui::Button("Render", ImVec2(250, 60));
ImGui::BeginChild("Inside color", size2);
ImGui::TextColored(inside_color, "INSIDE COLOR");
ImGui::ColorPicker3("", (float*)&inside_color);
ImGui::TextColored(edge_color, "EDGE COLOR");
ImGui::ColorEdit3("", (float*)&edge_color);
ImGui::EndChild();
ImGui::NewLine();
ImGui::End();
// Checkbox that appears in the window
// Renders the ImGUI elements
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// Swap the back buffer with the front buffer
glfwSwapBuffers(window);
// Take care of all GLFW events
glfwPollEvents();
}
// Deletes all ImGUI instances
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
// Delete window before ending the program
glfwDestroyWindow(window);
// Terminate GLFW before ending the program
glfwTerminate();
return 0;
}
How can I use the glfwSetWindowIcon() or there's another way for change window icon in native c++?
I'm trying to make a simple program to work. I am using SD2 + OpenGL Shading Language. Also, I'm trying to this on MacOS, more precisely 10.15.5.
I know Apple is deprecating OpenGL in favor of Metal, but it seems they are still supporting at least up to OpenGL 4.1.
This is a simplified version of the program I'm trying to run:
#include <OpenGL/glext.h>
#include <OpenGL/glu.h>
#include <SDL.h>
#include <iostream>
const int WIDTH = 600;
const int HEIGHT = 600;
const int numVAOs = 1;
GLuint renderingProgram;
GLuint vao[numVAOs];
GLuint createShaderProgram() {
GLint vertCompiled;
GLint fragCompiled;
GLint linked;
const char *vshaderSource =
"#version 410\n"
"void main(void)\n"
"{gl_Position = vec4(0.0, 0.0, 0.0, 1.0); }";
const char *fshaderSource =
"#version 410\n"
"out vec4 color; \n"
"void main(void)\n"
"{color = vec4(1.0, 0.0, 0.0, 1.0);}";
GLuint vShader = glCreateShader(GL_VERTEX_SHADER);
GLuint fShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vShader, 1, &vshaderSource, NULL);
glShaderSource(fShader, 1, &fshaderSource, NULL);
glCompileShader(vShader);
glCompileShader(fShader);
GLuint vfProgram = glCreateProgram();
glAttachShader(vfProgram, vShader);
glAttachShader(vfProgram, fShader);
glLinkProgram(vfProgram);
return vfProgram;
}
int main() {
SDL_Window *window;
SDL_GLContext gl_context;
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
return -1;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
window = SDL_CreateWindow(
"OpenGL Shaders",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WIDTH,
HEIGHT,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
gl_context = SDL_GL_CreateContext(window);
std::cout << glGetString(GL_VERSION) << std::endl;
renderingProgram = createShaderProgram();
glGenVertexArraysAPPLE(numVAOs, vao);
glBindVertexArrayAPPLE(vao[0]);
bool isRunning = true;
SDL_Event event;
while (isRunning) {
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
isRunning = false;
break;
}
}
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(renderingProgram);
glPointSize(30.0f);
glDrawArrays(GL_POINTS, 0, 1);
SDL_GL_SwapWindow(window);
}
SDL_GL_DeleteContext(gl_context);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
This shows only a blank screen and on the console it prints 4.1 ATI-3.9.15. So I am sure I got the correct profile.
I have tried playing with the headers. It seems i don't need a library to get extension names, seems Apple already has them int heir OpenGL headers.
The full program has some routines which handles errors when creating/linking the shaders and I can tell they are not failing to compile/link.
The program should show a point in the middle of the screen, but is not showing anything but a white screen(the clear color).
Any idea what am I missing or doing wrong?
Ok. I made it work.
The problem was this lines:
glGenVertexArraysAPPLE(numVAOs, vao);
glBindVertexArrayAPPLE(vao[0]);
For some reason, the APPLE version of those doesn't work.
What I did is:
Install GLEW with brew (which I thought I didn't need)
Update my cmake file to link glew correctly
Add glew headers and glew_init()
Replace the APPLE functions with "normal" ones.
glGenVertexArrays(numVAOs, vao);
glBindVertexArray(vao[0]);
Now the program shows points/triangles
Hope this helps anyone else in the future.
I have a simple program using FreeGLUT, OpenGL, and some nice simplex noise functions from Eliot Eshelman. The goal is to display 2D slices some 3D simplex noise, which I've managed with SDL.
My problem is: I'm getting multiple definition errors that I can't seem to resolve.
I've searched around on Google and these forums for a while. I learned about quite a few things that could cause errors, BUT I can't seem to find the cause of mine. I've been stumped by these errors for many hours.
Here's my relevant sources and error outputs.
Note that there could be more bugs past the errors I'm getting, but I haven't been able to debug far enough to get to them yet.
Output:
-------------- Build: Release in OpenGL Test (compiler: GNU GCC Compiler)---------------
mingw32-g++.exe -Wall -O2 -std=c++11 -IC:\freeglut\include -c "C:\OpenGL Test\OpenGL Test\main.cpp" -o obj\Release\main.o
mingw32-g++.exe -LC:\freeglut\lib -o "bin\Release\OpenGL Test.exe" obj\Release\LUtil.o obj\Release\main.o obj\Release\simplexnoise.o -s -lmingw32 -lOpenGL32 -lglu32 -lfreeglut -mwindows
obj\Release\main.o:main.cpp:(.bss+0x0): multiple definition of `textureName'
obj\Release\LUtil.o:LUtil.cpp:(.bss+0x0): first defined here
obj\Release\main.o:main.cpp:(.bss+0x20): multiple definition of `noiseImage'
obj\Release\LUtil.o:LUtil.cpp:(.bss+0x20): first defined here
obj\Release\main.o:main.cpp:(.bss+0x12c020): multiple definition of `zOffset'
obj\Release\LUtil.o:LUtil.cpp:(.bss+0x12c020): first defined here
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))
LUtil.h:
/*This source code copyrighted by Lazy Foo' Productions (2004-2013)
and may not be redistributed without written permission.*/
//Version: 001
#ifndef LUTIL_H
#define LUTIL_H
#include "LOpenGL.h"
#include "simplexnoise.h"
//Screen Constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_FPS = 60;
float zOffset = 0;
float noiseImage[640][480];
GLuint textureName;
bool initGL();
/*
Pre Condition:
-A valid OpenGL context
Post Condition:
-Initializes matrices and clear color
-Reports to console if there was an OpenGL error
-Returns false if there was an error in initialization
Side Effects:
-Projection matrix is set to identity matrix
-Modelview matrix is set to identity matrix
-Matrix mode is set to modelview
-Clear color is set to black
*/
void update();
/*
Pre Condition:
-None
Post Condition:
-Does per frame logic
Side Effects:
-None
*/
void render();
/*
Pre Condition:
-A valid OpenGL context
-Active modelview matrix
Post Condition:
-Renders the scene
Side Effects:
-Clears the color buffer
-Swaps the front/back buffer
*/
#endif
LUtil.cpp:
/*This source code copyrighted by Lazy Foo' Productions (2004-2013)
and may not be redistributed without written permission.*/
//Version: 001
#include "LUtil.h"
bool initGL()
{
//Initialize Projection Matrix
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
//Initialize Modelview Matrix
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
//Initialize clear color
glClearColor( 0.f, 0.f, 0.f, 1.f );
//Check for error
GLenum error = glGetError();
if( error != GL_NO_ERROR )
{
printf( "Error initializing OpenGL! %s\n", gluErrorString( error ) );
return false;
}
glGenTextures(1, &textureName);
glBindTexture(GL_TEXTURE_2D, textureName);
return true;
}
void update()
{
for(int y = 0; y < SCREEN_HEIGHT; y++)
{
for(int x = 0; x < SCREEN_WIDTH; x++)
{
noiseImage[x][y] = raw_noise_3d(x, y, zOffset);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SCREEN_WIDTH, SCREEN_HEIGHT, 0, GL_RGB, GL_FLOAT, &noiseImage[0][0]);
}
}
}
void render()
{
//Clear color buffer
glClear( GL_COLOR_BUFFER_BIT );
glColor4f(1, 0.5f, 0, 1);
//Render quad
glBegin( GL_QUADS );
glTexCoord2f( -1.f, -1.f );
glTexCoord2f( -1.f, 1.f );
glTexCoord2f( 1.f, -0.f );
glTexCoord2f( 1.f, 1.f );
glEnd();
//Update screen
glutSwapBuffers();
}
main.cpp:
/*This source code copyrighted by Lazy Foo' Productions (2004-2013)
and may not be redistributed without written permission.*/
//Version: 001
#include "LUtil.h"
void runMainLoop( int val );
/*
Pre Condition:
-Initialized freeGLUT
Post Condition:
-Calls the main loop functions and sets itself to be called back in 1000 / SCREEN_FPS milliseconds
Side Effects:
-Sets glutTimerFunc
*/
int main( int argc, char* args[] )
{
//Initialize FreeGLUT
glutInit( &argc, args );
//Create OpenGL 2.1 context
glutInitContextVersion( 4, 4 );
//Create Double Buffered Window
glutInitDisplayMode( GLUT_DOUBLE );
glutInitWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );
glutCreateWindow( "OpenGL" );
//Do post window/context creation initialization
if( !initGL() )
{
printf( "Unable to initialize graphics library!\n" );
return 1;
}
//Set rendering function
glutDisplayFunc( render );
//Set main loop
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, 0 );
//Start GLUT main loop
glutMainLoop();
return 0;
}
void runMainLoop( int val )
{
//Frame logic
update();
render();
//Run frame one more time
glutTimerFunc( 1000 / SCREEN_FPS, runMainLoop, val );
}
As far as I can tell, there are no multiple definitions, but I could be wrong.
Once again, I'm sorry if I'm "That guy" with this question.
Move the definitions of your global variabls to LUtil.cpp:
float zOffset = 0;
float noiseImage[640][480];
GLuint textureName;
Then declare the variabls in LUtil.h:
extern float zOffset;
extern float noiseImage[640][480];
extern GLuint textureName;
I'm using Visual Studio 2013, and as I am learning OpenGL 3.3 I thought best to use
#define GLFW_INCLUDE_GLCOREARB
#include <GLFW/glfw3.h>
to force 'intellisense' to not even show old depreciated functions such as glVertex2f etc...
However the inclusion of said #define prevents any gl* functions from showing up. Even glViewport is undefined. When attempting to compile a simple application I get among many errors
error C3861: 'glViewport': identifier not found
glcorearb.h is my include files path though, downloaded from http://www.opengl.org/registry/api/GL/glcorearb.h only yesterday.
I might be doing something completely wrong here. But here is my full source code...
// Include standard headers
#include <stdio.h>
#include <stdlib.h>
#define GLFW_INCLUDE_GLCOREARB
// Include GLFW3
#include <GLFW/glfw3.h>
//Error Callback - Outputs to STDERR
static void error_callback(int error, const char* description)
{
fputs(description, stderr);
}
//Key Press Callback
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
int main(){
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
// Initialise GLFW
if (!glfwInit())
{
fputs("Failed to initialize GLFW\n", stderr);
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_SAMPLES, 2); // 2x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL
// Open a window and create its OpenGL context
window = glfwCreateWindow(640, 480, "Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
while (!glfwWindowShouldClose(window))
{
float ratio;
int width, height;
glfwGetFramebufferSize(window, &width, &height);
ratio = width / (float)height;
glViewport(0, 0, width, height);
glClearColor(0.5f, 0.7f, 1.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}