Raspberry Pi OGLES setup - c++

A very easy/hard question.
What packages do i need to download to be able to create a simple X11 window with an EGL/OpenGLES contex.
As i have today the the problem with dri2 failing to authenticate.
But it can’t be that i link to the wrong library else it wouldn’t accept the X11 window at all at eglGetDisplay.
I really don’t want to use any library like glfw or sdl (wrapper
wrapper).
I use raspbian stretch with the default full KMS(driver by VMWare).
My Code is(if it matter's):
#include <X11/Xlib.h>
#include <EGL/egl.h>
#include <EGL/eglplatform.h>
#include <GLES2/gl2.h>
#include <iostream>
struct Pane {
Window win;
Display *display;
Atom windowDeletMessage;
int x11_file;
EGLDisplay egl_display;
EGLContext egl_context;
EGLSurface egl_surface;
EGLConfig egl_config;
EGLint egl_num_config;
EGLint egl_minor;
EGLint egl_major;
};
void setup_window(Pane &self) {
self.display = XOpenDisplay(nullptr);
if (self.display == nullptr) {
exit(0);
}
auto s = DefaultScreen(self.display);
self.win = XCreateSimpleWindow(self.display,
RootWindow(self.display, s),
10,
10,
800,
600,
1,
BlackPixel(self.display, s),
WhitePixel(self.display, s));
self.windowDeletMessage = XInternAtom(self.display, "WM_DELETE_WINDOW", false);
XSetWMProtocols(self.display, self.win, &self.windowDeletMessage, 1);
XStoreName(self.display, self.win, "Default Window");
XSelectInput(self.display,self.win, KeyPressMask | KeyReleaseMask | LeaveWindowMask | EnterWindowMask | PointerMotionMask | ResizeRedirectMask);
XMapWindow(self.display, self.win);
XFlush(self.display);
self.x11_file = ConnectionNumber(self.display);
}
void GetEvent(Pane &self, XEvent &e) {
// Event handling...
}
void setup_egl(Pane &self)
{
const EGLint Attributes[] = //Note to much is to much
{
EGL_RED_SIZE,8,
EGL_GREEN_SIZE,8,
EGL_BLUE_SIZE,8,
EGL_ALPHA_SIZE,8,
EGL_NONE,
};
self.egl_display = eglGetDisplay(self.display);
if(self.egl_display == EGL_NO_DISPLAY)
{
printf("EGL Failed to Obtain Window!") // Note this is not Error handling!
exit(103);
}
if(eglInitialize(self.egl_display,&self.egl_major,&self.egl_minor) == EGL_FALSE)
{
printf("EGL Failed to Initzialize!""");
exit(104);
};
eglChooseConfig(self.egl_display, Attributes, &self.egl_config, 1, &self.egl_num_config);
self.egl_context = eglCreateContext(self.egl_display, self.egl_config,EGL_NO_CONTEXT,nullptr);
self.egl_surface = eglCreateWindowSurface(self.egl_display, self.egl_config, self.win, nullptr);
eglMakeCurrent(self.egl_display, self.egl_surface, self.egl_surface, self.egl_context);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
eglSwapBuffers(self.display, self.egl_surface);
}
int main(int argc, char **argv) {
Pane pane;
setup_window(pane);
setup_egl(pane);
XEvent e;
while (true) {
GetEvent(pane, e);
glClear(GL_COLOR_BUFFER_BIT);
}
}
Edit:
As i used an USB-Drive to boot and not the SD Card. So raspi-config couldn't access the config file on the SD Card and a such it could not enable full KMS.

Related

BGFX graphics not updating

A am trying to compile a simple bgfx program (from this link) and failing, because the window is not updating. Closing the window is fine, so i think the problem is in bgfx. I also tried other tutorials and those didn't work either
Code:
#include <stdio.h>
#include <bgfx/bgfx.h>
#include <bgfx/platform.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>
SDL_Window* window = NULL;
const int WIDTH = 640;
const int HEIGHT = 480;
int main (int argc, char* args[]) {
// Initialize SDL systems
if(SDL_Init( SDL_INIT_VIDEO ) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n",
SDL_GetError());
}
else {
//Create a window
window = SDL_CreateWindow("BGFX Tutorial",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WIDTH, HEIGHT,
SDL_WINDOW_SHOWN);
if(window == NULL) {
printf("Window could not be created! SDL_Error: %s\n",
SDL_GetError());
}
}
// Collect information about the window from SDL
SDL_SysWMinfo wmi;
SDL_VERSION(&wmi.version);
if (!SDL_GetWindowWMInfo(window, &wmi)) {
return 1;
}
bgfx::PlatformData pd;
// and give the pointer to the window to pd
pd.ndt = wmi.info.x11.display;
pd.nwh = (void*)(uintptr_t)wmi.info.x11.window;
// Tell bgfx about the platform and window
bgfx::setPlatformData(pd);
// Render an empty frame
bgfx::renderFrame();
// Initialize bgfx
bgfx::init();
// Reset window
bgfx::reset(WIDTH, HEIGHT, BGFX_RESET_VSYNC);
// Enable debug text.
bgfx::setDebug(BGFX_DEBUG_TEXT /*| BGFX_DEBUG_STATS*/);
// Set view rectangle for 0th view
bgfx::setViewRect(0, 0, 0, uint16_t(WIDTH), uint16_t(HEIGHT));
// Clear the view rect
bgfx::setViewClear(0,
BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH,
0x443355FF, 1.0f, 0);
// Set empty primitive on screen
bgfx::touch(0);
// Poll for events and wait till user closes window
bool quit = false;
SDL_Event currentEvent;
while(!quit) {
while(SDL_PollEvent(&currentEvent) != 0) {
if(currentEvent.type == SDL_QUIT) {
quit = true;
}
}
}
// Free up window
SDL_DestroyWindow(window);
// Shutdown SDL
SDL_Quit();
return 0;
}
Why is this happening, and how to fix it?
P.S.: I am using kali linux

OpenGL GLFW not correctly recognising window resize

I have some graph that I need to resize concurrently when the window is also resized, however as of now, it changes the axis size's perfectly when resizing but when I let go of the resize (stop clicking on the corner of a window) the application's graph limits revert back to something entirely incorrect.
Here is a MRE displaying the issue:
#include <GL/glew.h>
#ifndef GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors.
#endif // GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include "ImGui/imgui.h"
#include "ImGui/implot.h"
#include "ImGui/implot_internal.h"
#include "ImGui/imgui_impl_glfw.h"
#include "ImGui/imgui_impl_opengl3.h"
#include <iostream>
static bool changedWinSize = false;
static int winWidth = 1280;
static int winHeight = 720;
static void MainLoop(GLFWwindow* window)
{
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::SetNextWindowSize({ (float)winWidth, (float)winHeight });
ImGui::SetNextWindowPos({ 0, 0 });
ImGui::Begin("Window", (bool*)0, ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize);
static bool fitPlot = false;
if (fitPlot) {
fitPlot = false;
ImPlot::SetNextPlotLimits(-10, 80, -3, 20, ImGuiCond_Always);
}
ImPlotStyle& style = ImPlot::GetStyle();
style.PlotDefaultSize.y = ImGui::GetWindowSize().y / 2 - 45 + (style.PlotDefaultSize.y = ImGui::GetWindowSize().y / 3 - 30) / 2 - 60;
style.PlotDefaultSize.x = ImGui::GetWindowSize().x - 150;
if (ImPlot::BeginPlot("Sim", "Range (m)", "Height (m)", { 0, 0 }, ImPlotFlags_NoLegend | ImPlotFlags_Equal)) {
if (ImPlot::BeginItem("Sim"))
{
if (ImPlot::FitThisFrame() || changedWinSize) {
fitPlot = true;
}
}
ImPlot::EndPlot();
}
ImGui::End();
changedWinSize = false;
// Rendering
ImGui::Render();
glClearColor(0.45f, 0.55f, 0.60f, 1.00f);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
}
static void window_size_callback(GLFWwindow* window, int width, int height)
{
changedWinSize = true;
winWidth = width;
winHeight = height;
MainLoop(window);
}
int main(int argc, char* argv[])
{
const char* glslVersion = "#version 460";
glfwInit();
// Create window with graphics context
GLFWwindow* window = glfwCreateWindow(1280, 720, "Program", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSwapInterval(0); // vsync
//Initialize GLEW + ImGui
glewInit();
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImPlot::CreateContext();
// Setup Dear ImGui style
ImGui::StyleColorsLight();
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glslVersion);
glfwSetWindowSizeCallback(window, window_size_callback);
while (!glfwWindowShouldClose(window))
{
//Events
glfwPollEvents();
MainLoop(window);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImPlot::DestroyContext();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
From this example, the plot x-axis labels begin at -5 and go to 75. When you try to resize the window (shorten the width) after a pixel or so shrinking the window, the plot lables display -10 and 80, which is exactly what I want. This correct size only occurs when resizing the window and not letting go. It is only when you let go of the window that it reverts back to the incorrect side. I can't figure out where in my code it goes wrong.
ImPlot::FitThisFrame() returns true when double clicking on the plot, however what is weird is that the plot fits correctly if winChangedSize is true, entering that if statement, but when i double click to enter it it doesn't fit the plot correctly?

Visual Studio 2013 and OpenGL

I have recently purchased a new laptop and got a new version of VS from my school. And I'm having a little trouble setting up my libraries.
I created a basic SDL_Window, as well as a SDL_GLContext.
I'm able to include my libraries and run the program, but I can't call functions like glClearColor, or glGetString(GL_VERSION). I get a rather strage warning and an error that I have never seen before, I'm guessing it's related to the 2013 version?
I have tried ignoring all specific default libraries, as well as trying to change the programtype (Multithreaded DLL, those 4).
And I have made sure all the dll-files are in place in my system folder.
What makes me wonder is the fact that glewInit() works, but not glClearColor() etc...
Output:
1>MSVCRTD.lib(cinitexe.obj) : warning LNK4098: defaultlib 'msvcrt.lib'
conflicts with use of other libs; use /NODEFAULTLIB:library
1>Window.obj : error LNK2019: unresolved external symbol
__imp__glClearColor#16 referenced in function "public: void __thiscall Window::initOpenGL(void)" (?initOpenGL#Window##QAEXXZ)
1>C:\Users\Aleksander\documents\visual studio 2013\Projects\OpenGL
Test\Debug\OpenGL Test.exe : fatal error LNK1120: 1 unresolved
externals
Header:
#pragma once
#include <SDL.h> //Tested OK
#include <SDL_image.h> //Tested OK
#include <SDL_mixer.h> //Tested OK
#include <SDL_net.h> //Tested OK
#include <OpenGL\glew.h> //?
#include <freeglut\freeglut.h> //?
#include <gl\GL.h> //?
#include <glm\glm.hpp> //Tested OK
#include <iostream> //Standard OK
#include <Box2D\Box2D.h> //Tested OK
using namespace std;
class Window {
SDL_Window *window;
SDL_GLContext context;
bool quit;
public:
Window();
~Window();
void initSDL();
void initOpenGL();
void run();
};
Source:
#include "Window.h"
Window::Window() {
printf("Starting window...\n");
//Initialize window
quit = false;
initSDL();
initOpenGL();
//Run window
run();
}
Window::~Window() {
printf("Closing window...\n");
//Clear window memory
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
//Close window library
SDL_Quit();
}
void Window::initSDL() {
if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
quit = true;
printf("Unable to initialize SDL!\n");
}
else {
//Create window
const char *title = "OpenGL Test";
int pos = SDL_WINDOWPOS_CENTERED;
int w = 800;
int h = 600;
Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
window = SDL_CreateWindow(title, pos, pos, w, h, flags);
//Create OpenGL context
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
context = SDL_GL_CreateContext(window);
}
}
void Window::initOpenGL() {
GLenum init = glewInit();
if (init != GLEW_OK) {
quit = true;
printf("Unable to initialize OpenGL!\n");
printf("Error: %s!\n", glewGetErrorString(init));
}
else {
//printf("Vendor: %s\n", glGetString(GL_VENDOR));
//printf("Version: %s\n", glGetString(GL_VERSION));
//printf("Renderer: %s\n", glGetString(GL_RENDERER));
}
}
void Window::run() {
printf("Window started running!\n");
SDL_Event event;
while (!quit) {
SDL_GL_SwapWindow(window);
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
quit = true;
}
}
}
}

OS X Mavericks OpenGL/X11 C code compiling error

I have problem with compiling c code which worked earlier before updating o OS X Mavericks.
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include <stdio.h>
#include <stdlib.h>
#include <X11/Xutil.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
char WINDOW_NAME[] = "Graphics Window";
char ICON_NAME[] = "Icon";
Display *display;
int screen;
Window main_window;
unsigned long foreground, background;
static int snglBuf[] = {GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 12, None};
static int dblBuf[] = {GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 12,GLX_DOUBLEBUFFER, None};
Bool doubleBuffer = True;
XVisualInfo *vi;
GLXContext cx;
Colormap cmap;
XSetWindowAttributes swa;
Bool recalcModelView = True;
int dummy;
void connectX()
{
display = XOpenDisplay(NULL);
if (display == NULL) {fprintf(stderr, "Cannot connect to X\n");
exit(1);}
screen = DefaultScreen(display);
if (!glXQueryExtension(display, &dummy, &dummy)){
fprintf(stderr, "X server has no OpenGL GLX Extension\n");
exit(1);}
vi = glXChooseVisual(display, screen, dblBuf);
if (vi == NULL){
fprintf(stderr, "Double Buffering not available\n");
vi = glXChooseVisual(display, screen, snglBuf);
if (vi == NULL) fprintf(stderr, "No RGB Visual with depth buffer\n");
doubleBuffer = False;
}
if (doubleBuffer == True) fprintf(stderr, "We have double buffering\n");
if (vi->class != TrueColor){
fprintf(stderr, "Need a TrueColor visual\n");
exit(1);
}
cx = glXCreateContext(display, vi , None, True);
if (cx == NULL){
fprintf(stderr, "No rendering context\n");
exit(1);
}
else printf(stderr, "We have a rendering context\n");
cmap = XCreateColormap(display, RootWindow(display, vi->screen),
vi->visual, AllocNone);
if (cmap == NULL){
fprintf(stderr, "Color map is not available\n");
exit(1);
}
swa.colormap = cmap;
swa.border_pixel = 0;
swa.event_mask = ExposureMask | ButtonPressMask | StructureNotifyMask |
KeyPressMask;
}
Window openWindow(int x, int y, int width, int height,
int border_width, int argc, char** argv)
{
XSizeHints size_hints;
Window new_window;
new_window = XCreateWindow(display, RootWindow(display, vi->screen),
x,y, width, height, border_width, vi->depth, InputOutput,
vi->visual, CWBorderPixel | CWColormap | CWEventMask,
&swa);
size_hints.x = x;
size_hints.y = y;
size_hints.width = width;
size_hints.height = height;
size_hints.flags = PPosition | PSize;
XSetStandardProperties(display, new_window, WINDOW_NAME, ICON_NAME,
None, argv, argc, &size_hints);
XSelectInput(display, new_window, (ButtonPressMask | KeyPressMask |
StructureNotifyMask | ExposureMask));
return (new_window);
}
void init(void)
{
const GLubyte *renderer = glGetString(GL_RENDERER);
const GLubyte *vendor = glGetString(GL_VENDOR);
const GLubyte *version = glGetString(GL_VERSION);
const GLubyte *glslversion = glGetString(GL_SHADING_LANGUAGE_VERSION);
GLint major, minor;
//glGetIntegerv(GL_MAJOR_VERSION, &major);
//glGetIntegerv(GL_MINOR_VERSION, &minor);
printf("GL_VENDOR : %s\n", vendor);
printf("GL_RENDERER : %s\n", renderer);
printf("GL_VERSION (string) : %s\n", version);
//printf("GL_VERSION (int) : %d.%d\n", major, minor);
printf("GLSL Version : %s\n", glslversion);
}
void disconnectX()
{
XCloseDisplay(display);
exit(0);
}
void doKeyPressEvent(XKeyEvent *pEvent)
{
int key_buffer_size = 10;
char key_buffer[9];
XComposeStatus compose_status;
KeySym key_sym;
XLookupString(pEvent, key_buffer, key_buffer_size,
&key_sym, &compose_status);
switch(key_buffer[0]){
case 'q':
exit(0);
break;
}
}
void redraw(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
glBegin(GL_POLYGON);
glColor3f(1.0,0.0,0.0);
glVertex2f(-0.9,-0.9);
glColor3f(0.0,1.0,0.0);
glVertex2f(0.9,-0.9);
glColor3f(0.0,0.0,1.0);
glVertex2f(0.0,0.9);
glEnd();
if (doubleBuffer) glXSwapBuffers(display,main_window); else
glFlush();
fprintf(stderr, "redraw called\n");
}
void doButtonPressEvent(XButtonEvent *pEvent)
{
fprintf(stderr, "Mouse button pressed\n");
}
int main (int argc, char** argv){
XEvent event;
connectX();
main_window = openWindow(10,20,500,400,5, argc, argv);
glXMakeCurrent(display, main_window, cx);
XMapWindow(display, main_window);
glClear(GL_COLOR_BUFFER_BIT);
init();
/*glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0,1.0, -1.0, 1.0,0.0,10.0);*/
while(1){
do{
XNextEvent(display, &event);
switch (event.type){
case KeyPress:
doKeyPressEvent(&event);
break;
case ConfigureNotify:
glViewport(0,0, event.xconfigure.width, event.xconfigure.height);
case Expose:
redraw();
break;
case ButtonPress:
doButtonPressEvent(&event);
break;
}
}
while (True); //XPending(display));
}
}
I get this error:
ld: symbol(s) not found for architecture x86_64 clang: error: linker
command failed with exit code 1 (use -v to see invocation)
I've already install XQuartz and I'm using -I/opt/X11/include and -L/opt/X11/lib.
OpenGL programs which don't use X11 work perfectly.
#Giorgi Shavgulidze, I think my issue is similar. I had code that compiled fine with Mountain Lion. I upgraded to Mavericks. I go to recompile the code with Mavericks and Xcode 5.0.2, and glEnable(GL_SMOOTH) is causing an error. I just commented the line out and everything is fine. Why I do not know...
I know this is probably a little late for you, however, I believe this may help someone else.
I recently had essentially the exact same problem. It is important to note the difference between including something and linking to it in regards to compiling c code through methods such as gcc, as Andon mentioned above. A good SO post about this can be found here.
Your postbin shows that you are not linking properly to both OpenGL and X11. To link to them, you need to add links to your gcc command. My understanding is that you can either link to them through another path specific to your computer, via -L, or you can use pre-made links in your gcc command, which seems to be the far simpler option.
In regards to X11, while you do link to the directory holding the X11 libraries via -L/opt/X11/lib, you do not specify which library(s) you want to use. I believe the additional link you would need for X11 is -lX11.
In regards to OpenGL, you would use a different flag. While I have not used OpenGL (only used GL), my understanding is these are the appropriate flags you would have to use: -lGLU -lglut.
It is also important to note that order matters when linking and libraries should always go last.
I have included my gcc command, even though it is slightly different than what you would need, as an example.
gcc -I/opt/X11/include -L/opt/X11/lib -lX11 -lncurses -lGL spitmat8w_3.c -o hello

GL/glx isn't linking correctly

System Specs and task
I am using Code::Blocks on Ubuntu 10.10 and playing around with OpenGL and glx. I'm in the process of learning C++(from a background in C and Java), so the style of any code doesn't conform to any real good standards (but I'm open to suggestions on how to improve, even if you don't have an answer to the question)
Edit:
Huge Realization: The default OpenGL Project Code::Blocks creates is C, not C++. I'm looking into this now.
I'm currently trying to modify the default OpenGL project on Code::Blocks into a simple 3d engine. I am currently getting the error:
expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before 'Draw'
Which disappears as soon as I comment out the #include for < GL/glx.h>
I read on a forum somewhere that Code::Blocks doesn't look in usr/include/ by default, but I added that to the search directories for the compiler in the project build options and it didn't seem to fix anything.
Code:
main.cpp: main.c:
#include <time.h>
#include "Draw.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
/*draw init here*/
Draw::Draw renderer = Draw::Draw.getDraw();
printf( "Press left mouse button to rotate around X axis\n" );
printf( "Press middle mouse button to rotate around Y axis\n" );
printf( "Press right mouse button to rotate around Z axis\n" );
printf( "Press ESC to quit the application\n" );
/* timing variable*/
/* Set it to delay half a second before rendering the first frame*/
clock_t flip_time = clock() + 0.5f * CLOCKS_PER_SEC;
while (1)
{
/* Update models */
/* Draw scene */
/* wait until it's been 1/60th of a second*/
while(clock() < flip_time){}
flip_time = clock() + (1.0f/60.0f) * CLOCKS_PER_SEC;
/* Actually flip the frame */
}
}
Draw.h:
#ifndef DRAW_H
#define DRAW_H
#include <GL/glx.h> /* This is the problem line */
#include <GL/gl.h>
#include <X11/X.h> /* X11 constant (e.g. TrueColor) */
#include <X11/keysym.h>
class Draw
{
public:
static Draw getDraw();
virtual ~Draw();
void update();
void render();
protected:
private:
Draw();
bool init();
/* The singleton*/
static Draw *instance;
static bool exists;
/* X Window values */
Display *dpy;
Window win;
GLboolean doubleBuffer;
/* X Parameters*/
XVisualInfo *vi;
Colormap cmap;
XSetWindowAttributes swa;
GLXContext cx;
XEvent event;
int dummy;
};
#endif // DRAW_H
Last, but not least Draw.cpp:
#include "Draw.h"
/* Set up the singleton*/
bool Draw::exists = false;
Draw* Draw::instance = NULL;
Draw::Draw()
{
/*TODO: make this constructor */
}
Draw::~Draw()
{
//dtor
}
Draw Draw::getDraw()
{
if(!exists)
{
instance = new Draw();
instance->init();
exists = true; //Thanks mat, This line was accidentally removed with extraneous comments
}
return *instance;
}
bool Draw::init()
{
/* Get the buffers ready */
static int snglBuf[] = {GLX_RGBA, GLX_DEPTH_SIZE, 16, None};
static int dblBuf[] = {GLX_RGBA, GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, None};
/* Double Buffered is best*/
doubleBuffer = GL_TRUE;
/*TODO: add constructor if it hasn't been constructed already*/
dpy = XOpenDisplay(NULL);
if (dpy == NULL)
{
return false;
}
/* make sure OpenGL's GLX extension supported */
if(!glXQueryExtension(dpy, &dummy, &dummy))
{
return false;
}
/* find an appropriate visual */
/* find an OpenGL-capable RGB visual with depth buffer */
vi = glXChooseVisual(dpy, DefaultScreen(dpy), dblBuf);
if (vi == NULL)
{
vi = glXChooseVisual(dpy, DefaultScreen(dpy), snglBuf);
if (vi == NULL)
{
return false;
}
doubleBuffer = GL_FALSE;
}
/*
TODO: Fix or remove this
if(vi->class != TrueColor)
{
return false;
}
*/
/* create an OpenGL rendering context */
/* create an OpenGL rendering context */
cx = glXCreateContext(dpy, vi, /* no shared dlists */ None,
/* direct rendering if possible */ GL_TRUE);
if (cx == NULL)
{
return false;
}
/* create an X window with the selected visual */
/* create an X colormap since probably not using default visual */
cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen), vi->visual, AllocNone);
swa.colormap = cmap;
swa.border_pixel = 0;
swa.event_mask = KeyPressMask | ExposureMask
| ButtonPressMask | StructureNotifyMask;
win = XCreateWindow(dpy, RootWindow(dpy, vi->screen), 0, 0,
300, 300, 0, vi->depth, InputOutput, vi->visual,
CWBorderPixel | CWColormap | CWEventMask, &swa);
XSetStandardProperties(dpy, win, "main", "main", None,
NULL, NULL, NULL);
/* bind the rendering context to the window */
glXMakeCurrent(dpy, win, cx);
/* request the X window to be displayed on the screen */
XMapWindow(dpy, win);
/* configure the OpenGL context for rendering */
glEnable(GL_DEPTH_TEST); /* enable depth buffering */
glDepthFunc(GL_LESS); /* pedantic, GL_LESS is the default */
glClearDepth(1.0); /* pedantic, 1.0 is the default */
/* frame buffer clears should be to black */
glClearColor(0.0, 0.0, 0.0, 0.0);
/* set up projection transform */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10.0);
/* establish initial viewport */
/* pedantic, full window size is default viewport */
glViewport(0, 0, 300, 300);
return true;
}
void Draw::update()
{
/*TODO: Add things to draw here*/
}
void Draw::render()
{
/* actually flip buffers here */
}
I removed a ton of comments before posting this here, but that shouldn't affect whether or not it compiles.
Thanks!
This line in your main file is wrong:
Draw::Draw renderer = Draw::Draw.getDraw();
Draw::Draw is not a type. To get this to compile, you just need:
Draw renderer = Draw.getDraw();
It looks like you're trying to build a singleton. You code does not do that at all, you'll get a copy each time. (Note that you're not setting exists anywhere, but that's just an extra bug.) You should be returning a pointer or a reference to the shared instance. See for instance this article to get the syntax right: C++ Singleton design pattern.
I found the issue with the linking.
The default project for OpenGL in Code::Blocks is NOT C++, it's C. I configured it to use g++ and it fixed the issue with glx not linking in correctly. I revised my singleton to look a little more like this and it works correctly now too. I have an issue now with the window not appearing, but I should be able to figure that out.
Thanks!