xdl_vptr XdevLOpenGLContextGLX::getProcAddress(const xdl_char* func) { return reinterpret_cast<xdl_vptr>(glXGetProcAddress((const GLubyte *)func)); }
/*! * This function implements OpenGL context creation using GLX * and a Pbuffer if GLX version is 1.4 or higher, or a XPixmap * otherwise. * \returns * - ::GR3_ERROR_NONE on success * - ::GR3_ERROR_INIT_FAILED if initialization failed */ int gr3_initGL_GLX_(void) { int major, minor; int fbcount; GLXFBConfig *fbc; GLXFBConfig fbconfig = (GLXFBConfig) NULL; gr3_log_("gr3_initGL_GLX_();"); display = XOpenDisplay(0); if (!display) { gr3_log_("Not connected to an X server!"); return GR3_ERROR_INIT_FAILED; } context = glXGetCurrentContext(); if (context != NULL) { gr3_appendtorenderpathstring_("GLX (existing context)"); } else { glXQueryVersion(display,&major,&minor); if (major > 1 || minor >=4) { int i; int fb_attribs[] = { GLX_DRAWABLE_TYPE , GLX_PBUFFER_BIT, GLX_RENDER_TYPE , GLX_RGBA_BIT, None }; int pbuffer_attribs[] = { GLX_PBUFFER_WIDTH , 1, GLX_PBUFFER_HEIGHT , 1, None }; gr3_log_("(Pbuffer)"); fbc = glXChooseFBConfig(display, DefaultScreen(display), fb_attribs, &fbcount); if (fbcount == 0) { gr3_log_("failed to find a valid a GLX FBConfig for a RGBA PBuffer"); XFree(fbc); XCloseDisplay(display); return GR3_ERROR_INIT_FAILED; } for (i = 0; i < fbcount && !pbuffer; i++) { fbconfig = fbc[i]; pbuffer = glXCreatePbuffer(display, fbconfig, pbuffer_attribs); } XFree(fbc); if (!pbuffer) { gr3_log_("failed to create a RGBA PBuffer"); XCloseDisplay(display); return GR3_ERROR_INIT_FAILED; } context = glXCreateNewContext(display, fbconfig, GLX_RGBA_TYPE, None, True); glXMakeContextCurrent(display,pbuffer,pbuffer,context); context_struct_.terminateGL = gr3_terminateGL_GLX_Pbuffer_; context_struct_.gl_is_initialized = 1; gr3_appendtorenderpathstring_("GLX (Pbuffer)"); } else { XVisualInfo *visual; int fb_attribs[] = { GLX_DRAWABLE_TYPE , GLX_PIXMAP_BIT, GLX_RENDER_TYPE , GLX_RGBA_BIT, None }; gr3_log_("(XPixmap)"); fbc = glXChooseFBConfig(display, DefaultScreen(display), fb_attribs, &fbcount); if (fbcount == 0) { gr3_log_("failed to find a valid a GLX FBConfig for a RGBA Pixmap"); XFree(fbc); XCloseDisplay(display); return GR3_ERROR_INIT_FAILED; } fbconfig = fbc[0]; XFree(fbc); context = glXCreateNewContext(display, fbconfig, GLX_RGBA_TYPE, None, True); visual = glXGetVisualFromFBConfig(display,fbconfig); pixmap = XCreatePixmap(display,XRootWindow(display,DefaultScreen(display)),1,1,visual->depth); if (glXMakeContextCurrent(display,pixmap,pixmap,context)) { context_struct_.terminateGL = gr3_terminateGL_GLX_Pixmap_; context_struct_.gl_is_initialized = 1; gr3_appendtorenderpathstring_("GLX (XPixmap)"); } else { gr3_log_("failed to make GLX OpenGL Context current with a Pixmap"); glXDestroyContext(display, context); XFreePixmap(display,pixmap); XCloseDisplay(display); return GR3_ERROR_INIT_FAILED; } } } /* Load Function pointers */ { #ifdef GR3_CAN_USE_VBO glBufferData = (PFNGLBUFFERDATAPROC)glXGetProcAddress((const GLubyte *)"glBufferData"); glBindBuffer = (PFNGLBINDBUFFERPROC)glXGetProcAddress((const GLubyte *)"glBindBuffer"); glGenBuffers = (PFNGLGENBUFFERSPROC)glXGetProcAddress((const GLubyte *)"glGenBuffers"); glDeleteBuffers = (PFNGLGENBUFFERSPROC)glXGetProcAddress((const GLubyte *)"glDeleteBuffers"); glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)glXGetProcAddress((const GLubyte *)"glVertexAttribPointer"); glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)glXGetProcAddress((const GLubyte *)"glGetAttribLocation"); glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)glXGetProcAddress((const GLubyte *)"glEnableVertexAttribArray"); glUseProgram = (PFNGLUSEPROGRAMPROC)glXGetProcAddress((const GLubyte *)"glUseProgram"); glDeleteShader = (PFNGLDELETESHADERPROC)glXGetProcAddress((const GLubyte *)"glDeleteShader"); glLinkProgram = (PFNGLLINKPROGRAMPROC)glXGetProcAddress((const GLubyte *)"glLinkProgram"); glAttachShader = (PFNGLATTACHSHADERPROC)glXGetProcAddress((const GLubyte *)"glAttachShader"); glCreateShader = (PFNGLCREATESHADERPROC)glXGetProcAddress((const GLubyte *)"glCreateShader"); glCompileShader = (PFNGLCOMPILESHADERPROC)glXGetProcAddress((const GLubyte *)"glCompileShader"); glCreateProgram = (PFNGLCREATEPROGRAMPROC)glXGetProcAddress((const GLubyte *)"glCreateProgram"); glDeleteProgram = (PFNGLDELETEPROGRAMPROC)glXGetProcAddress((const GLubyte *)"glDeleteProgram"); glUniform3f = (PFNGLUNIFORM3FPROC)glXGetProcAddress((const GLubyte *)"glUniform3f"); glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)glXGetProcAddress((const GLubyte *)"glUniformMatrix4fv"); glUniform4f = (PFNGLUNIFORM4FPROC)glXGetProcAddress((const GLubyte *)"glUniform4f"); glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)glXGetProcAddress((const GLubyte *)"glGetUniformLocation"); glShaderSource = (PFNGLSHADERSOURCEPROC)glXGetProcAddress((const GLubyte *)"glShaderSource"); #endif glDrawBuffers = (PFNGLDRAWBUFFERSPROC)glXGetProcAddress((const GLubyte *)"glDrawBuffers"); /*glBlendColor = (PFNGLBLENDCOLORPROC)glXGetProcAddress((const GLubyte *)"glBlendColor");*/ #ifdef GL_ARB_framebuffer_object glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)glXGetProcAddress((const GLubyte *)"glBindRenderbuffer"); glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)glXGetProcAddress((const GLubyte *)"glCheckFramebufferStatus"); glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)glXGetProcAddress((const GLubyte *)"glFramebufferRenderbuffer"); glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)glXGetProcAddress((const GLubyte *)"glRenderbufferStorage"); glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)glXGetProcAddress((const GLubyte *)"glBindFramebuffer"); glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)glXGetProcAddress((const GLubyte *)"glGenFramebuffers"); glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)glXGetProcAddress((const GLubyte *)"glGenRenderbuffers"); glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)glXGetProcAddress((const GLubyte *)"glDeleteFramebuffers"); glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)glXGetProcAddress((const GLubyte *)"glDeleteRenderbuffers"); #endif #ifdef GL_EXT_framebuffer_object glBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)glXGetProcAddress((const GLubyte *)"glBindRenderbufferEXT"); glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)glXGetProcAddress((const GLubyte *)"glCheckFramebufferStatusEXT"); glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)glXGetProcAddress((const GLubyte *)"glFramebufferRenderbufferEXT"); glRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)glXGetProcAddress((const GLubyte *)"glRenderbufferStorageEXT"); glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)glXGetProcAddress((const GLubyte *)"glBindFramebufferEXT"); glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)glXGetProcAddress((const GLubyte *)"glGenFramebuffersEXT"); glGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)glXGetProcAddress((const GLubyte *)"glGenRenderbuffersEXT"); glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)glXGetProcAddress((const GLubyte *)"glDeleteFramebuffersEXT"); glDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)glXGetProcAddress((const GLubyte *)"glDeleteRenderbuffersEXT"); #endif } return GR3_ERROR_NONE; }
void* GLimp_GetProcAddress( const char* Name ) { return ( void* )glXGetProcAddress( ( const GLubyte* )Name ); }
void (*wglGetProcAddress(const char *function_name))(void) { return glXGetProcAddress((GLubyte*)function_name); }
void GlxContext::EnableVerticalSync(bool enabled) { const GLubyte* name = reinterpret_cast<const GLubyte*>("glXSwapIntervalSGI"); PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = reinterpret_cast<PFNGLXSWAPINTERVALSGIPROC>(glXGetProcAddress(name)); if (glXSwapIntervalSGI) glXSwapIntervalSGI(enabled ? 1 : 0); }
int main() { hvLogInit(HV_LOG_INFO, stdout); hvPrint("HyperVision design approach test programme: X + GLX + OpenGL"); /* Open X Display */ Display *x_dsp = XOpenDisplay(NULL); hvErrorCheck(!x_dsp, "Failed to open X display"); /* Check and report GLX version*/ int glx_maj = 0, glx_min = 0; glXQueryVersion(x_dsp, &glx_maj, &glx_min); hvErrorCheck(glx_maj * 10 + glx_min < 14, "Invalid GLX version (1.4 required)"); //*1 hvInfo("GLX version: ", glXGetClientString(x_dsp, GLX_VERSION)); /* Choose best GLX FB configuration and get the GLX visual */ static int glx_fb_atr[] = { GLX_X_RENDERABLE , True, GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT, GLX_RENDER_TYPE , GLX_RGBA_BIT, GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR, GLX_CONFIG_CAVEAT , GLX_NONE, GLX_RED_SIZE , 8, GLX_GREEN_SIZE , 8, GLX_BLUE_SIZE , 8, GLX_ALPHA_SIZE , 8, GLX_DEPTH_SIZE , 24, GLX_STENCIL_SIZE , 8, GLX_DOUBLEBUFFER , True, None }; int glx_fb_cnt; GLXFBConfig *glx_fb_cfg = glXChooseFBConfig(x_dsp, DefaultScreen(x_dsp), glx_fb_atr, &glx_fb_cnt); hvErrorCheck(!glx_fb_cfg, "Failed to retrieve a framebuffer config"); // Pick the FB config with the most samples per pixel int top_fbc = 0, top_smp = 0, smp; for (int i = 0; i < glx_fb_cnt; i++) { glXGetFBConfigAttrib(x_dsp, glx_fb_cfg[i], GLX_SAMPLES, &smp); if (smp > top_smp) top_fbc = i, top_smp = smp; } GLXFBConfig glx_fbc = glx_fb_cfg[top_fbc]; XFree(glx_fb_cfg); XVisualInfo *glx_vsl = glXGetVisualFromFBConfig(x_dsp, glx_fbc); hvInfo("Chosen visual ID = ", hvHex(glx_vsl->visualid)); /* Create and map X window */ Colormap x_cmap = XCreateColormap(x_dsp, RootWindow(x_dsp, glx_vsl->screen), glx_vsl->visual, AllocNone); XSetWindowAttributes x_swa; x_swa.colormap = x_cmap; x_swa.background_pixmap = None; x_swa.border_pixel = 0; x_swa.event_mask = StructureNotifyMask; Window x_wnd = XCreateWindow(x_dsp, RootWindow(x_dsp, glx_vsl->screen), 0, 0, 100, 100, 0, glx_vsl->depth, InputOutput, glx_vsl->visual, CWBorderPixel|CWColormap|CWEventMask, &x_swa); hvErrorCheck(!x_wnd, "Failed to create window"); XFree(glx_vsl); XStoreName(x_dsp, x_wnd, "HyperVision GLX test"); XMapWindow(x_dsp, x_wnd); /* Retreive GLX_ARB_create_context extension and create OpenGL 3.0 context */ int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 0, GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, None }; const char *glx_exts = glXQueryExtensionsString(x_dsp, DefaultScreen(x_dsp)); glXCreateContextAttribsARBProc glXCreateContextAttribsARB = NULL; glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddress((const GLubyte*) "glXCreateContextAttribsARB"); hvErrorCheck(!hvInSet(glx_exts, "GLX_ARB_create_context") || !glXCreateContextAttribsARB, "GLX_ARB_create_context extension missing"); GLXContext glx_ctx = glXCreateContextAttribsARB(x_dsp, glx_fbc, 0, True, context_attribs ); if (!glXIsDirect(x_dsp, glx_ctx)) { hvInfo("GLX rendering context: indirect"); } else { hvInfo("GLX rendering context: DRI"); } /* Render OpenGL scene */ glXMakeCurrent(x_dsp, x_wnd, glx_ctx); glClearColor(0, 0.5, 1, 1); glClear (GL_COLOR_BUFFER_BIT); glXSwapBuffers(x_dsp, x_wnd); sleep(1); glClearColor(1, 0.5, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glXSwapBuffers(x_dsp, x_wnd); sleep(1); glXMakeCurrent(x_dsp, 0, 0); /* Release used resources */ glXDestroyContext(x_dsp, glx_ctx); XDestroyWindow(x_dsp, x_wnd); XFreeColormap(x_dsp, x_cmap); XCloseDisplay(x_dsp); }
VdpStatus vdpDeviceCreateX11(Display *display_orig, int screen, VdpDevice *device, VdpGetProcAddress **get_proc_address) { if (!display_orig || !device) return VDP_STATUS_INVALID_POINTER; // Let's get own connection to the X server Display *display = handle_xdpy_ref(display_orig); if (NULL == display) return VDP_STATUS_ERROR; if (global.quirks.buggy_XCloseDisplay) { // XCloseDisplay could segfault on fglrx. To avoid calling XCloseDisplay, // make one more reference to xdpy copy. handle_xdpy_ref(display_orig); } VdpDeviceData *data = calloc(1, sizeof(VdpDeviceData)); if (NULL == data) return VDP_STATUS_RESOURCES; glx_ctx_lock(); // use glx lock to serialize X calls data->type = HANDLETYPE_DEVICE; data->display = display; data->display_orig = display_orig; // save supplied pointer too data->screen = screen; data->refcount = 0; pthread_mutex_init(&data->refcount_mutex, NULL); data->root = DefaultRootWindow(display); XWindowAttributes wnd_attrs; XGetWindowAttributes(display, data->root, &wnd_attrs); data->color_depth = wnd_attrs.depth; data->fn.glXBindTexImageEXT = (PFNGLXBINDTEXIMAGEEXTPROC)glXGetProcAddress((GLubyte *)"glXBindTexImageEXT"); data->fn.glXReleaseTexImageEXT = (PFNGLXRELEASETEXIMAGEEXTPROC)glXGetProcAddress((GLubyte *)"glXReleaseTexImageEXT"); glx_ctx_unlock(); if (!data->fn.glXBindTexImageEXT || !data->fn.glXReleaseTexImageEXT) { traceError("error (%s): can't get glXBindTexImageEXT address\n"); free(data); return VDP_STATUS_RESOURCES; } // create master GLX context to share data between further created ones glx_ctx_ref_glc_hash_table(display, screen); data->root_glc = glx_ctx_get_root_context(); glx_ctx_push_thread_local(data); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // initialize VAAPI if (global.quirks.avoid_va) { // pretend there is no VA-API available data->va_available = 0; } else { data->va_dpy = vaGetDisplay(display); data->va_available = 0; VAStatus status = vaInitialize(data->va_dpy, &data->va_version_major, &data->va_version_minor); if (VA_STATUS_SUCCESS == status) { data->va_available = 1; traceInfo("libva (version %d.%d) library initialized\n", data->va_version_major, data->va_version_minor); } else { data->va_available = 0; traceInfo("warning: failed to initialize libva. " "No video decode acceleration available.\n"); } } compile_shaders(data); glGenTextures(1, &data->watermark_tex_id); glBindTexture(GL_TEXTURE_2D, data->watermark_tex_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, watermark_width, watermark_height, 0, GL_BGRA, GL_UNSIGNED_BYTE, watermark_data); glFinish(); *device = handle_insert(data); if (get_proc_address) *get_proc_address = &vdpGetProcAddress; GLenum gl_error = glGetError(); glx_ctx_pop(); if (GL_NO_ERROR != gl_error) { traceError("error (%s): gl error %d\n", __func__, gl_error); return VDP_STATUS_ERROR; } return VDP_STATUS_OK; }
int main(int argc, char **argv) { Display *dpy; int numScreens; int screen, initScreen = 0; struct window_info *wi = NULL; int ret = 0; GLXContext *ctxs; char **vendorNames; MakeCurrentScreenThreadArgs *tArgs = NULL; int major, event, error; TestOptions t; int i; init_options(argc, argv, &t); dpy = XOpenDisplay(NULL); FAILIF(!dpy, "No display!\n"); numScreens = ScreenCount(dpy); FAILIF(numScreens < 0, "Invalid screen count!\n"); FAILIF(!XQueryExtension(dpy, XGLV_EXTENSION_NAME, &major, &event, &error), "No " XGLV_EXTENSION_NAME " extension!\n"); wi = malloc(sizeof(struct window_info) * numScreens); ctxs = malloc(sizeof(GLXContext) * numScreens); vendorNames = malloc(sizeof(char *) * numScreens); FAILIF(!wi || !ctxs || !vendorNames, "Out of memory!\n"); tArgs = malloc(sizeof(*tArgs) * t.threads); for (i = 0; i < t.threads; i++) { tArgs[i].iterations = t.iterations; tArgs[i].firstScreen = i % numScreens; tArgs[i].numScreens = numScreens; tArgs[i].wi = wi; tArgs[i].ctxs = ctxs; tArgs[i].vendorNames = vendorNames; } for (; initScreen < numScreens; initScreen++) { FAILIF(!testUtilsCreateWindow(dpy, &wi[initScreen], initScreen), "Failed to create window for screen %d!\n", initScreen); ctxs[initScreen] = glXCreateContext(dpy, wi[initScreen].visinfo, NULL, GL_TRUE); FAILIF(!ctxs[initScreen], "Failed to create a context!\n"); vendorNames[initScreen] = XGLVQueryScreenVendorMapping(dpy, initScreen); } pMakeCurrentTestResults = (PFNGLMAKECURRENTTESTRESULTSPROC) glXGetProcAddress((GLubyte *)"glMakeCurrentTestResults"); FAILIF(!pMakeCurrentTestResults, "Could not get glMakeCurrentTestResults!\n"); if (t.threads == 1) { ret = (int)!!MakeCurrentScreenThread((void *)&tArgs[0]); } else { glvnd_thread_t *threads = malloc(t.threads * sizeof(glvnd_thread_t)); void *one_ret; XInitThreads(); if (!glvndSetupPthreads(RTLD_DEFAULT, &pImp)) { exit(1); } for (i = 0; i < t.threads; i++) { FAILIF(pImp.create(&threads[i], NULL, MakeCurrentScreenThread, (void *)&tArgs[i]) != 0, "Error in pthread_create(): %s\n", strerror(errno)); } for (i = 0; i < t.threads; i++) { FAILIF(pImp.join(threads[i], &one_ret) != 0, "Error in pthread_join(): %s\n", strerror(errno)); if (one_ret) { ret = 1; } } free(threads); } cleanup: free(tArgs); if (wi) { for (screen = 0; screen < initScreen; screen++) { testUtilsDestroyWindow(dpy, &wi[screen]); } } free(wi); if (dpy) { XCloseDisplay(dpy); } return ret; }
static void initializeARBExtensions(Display* display) { static bool initialized = false; if (initialized) return; initialized = true; if (GLPlatformContext::supportsGLXExtension(display, "GLX_ARB_create_context_robustness")) glXCreateContextAttribsARB = reinterpret_cast<GLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXCreateContextAttribsARB"))); }
GLXContextType* glxInit(Display *x11Display, Window x11Window) { GLXContext glxContext = NULL; static GLXContextType context; if (context.glxContext) { ASSERT(context.x11Display == x11Display && context.x11Window == x11Window); return &context; } // get func pointer for TFP extension int screen = DefaultScreen(x11Display); const char *ext = glXQueryExtensionsString(x11Display, screen); if (!strstr(ext, "GLX_EXT_texture_from_pixmap")) { fprintf(stderr, "GLX_EXT_texture_from_pixmap not supported.\n"); return NULL; } glXBindTexImageEXT_func = (PFNGLXBINDTEXIMAGEEXTPROC) glXGetProcAddress((GLubyte *) "glXBindTexImageEXT"); glXReleaseTexImageEXT_func = (PFNGLXRELEASETEXIMAGEEXTPROC) glXGetProcAddress((GLubyte*) "glXReleaseTexImageEXT"); if (!glXBindTexImageEXT_func || !glXReleaseTexImageEXT_func) { fprintf(stderr, "glXGetProcAddress[glXBindTexImageEXT, glXReleaseTexImageEXT] failed!\n"); return NULL; } // create GLXContext int attribs[] = { GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_DOUBLEBUFFER, None}; XVisualInfo *visualInfo = glXChooseVisual(x11Display, screen, attribs); ASSERT(visualInfo); glxContext = glXCreateContext(x11Display, visualInfo, NULL, True); ASSERT(glxContext); context.glxContext = glxContext; context.x11Display = x11Display; context.x11Window = x11Window; // init gl rendering context glXMakeCurrent(x11Display, x11Window, glxContext); Window rootWindow; int x, y; unsigned int windowWidth, windowHeight, windowBorder, windowDepth; XGetGeometry(x11Display, x11Window, &rootWindow , &x, &y, &windowWidth, &windowHeight, &windowBorder, &windowDepth); glViewport(0, 0, windowWidth, windowHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1.01, 1.01, -1.01, 1.01, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); ASSERT_GL_ERROR(); return &context; }
extern void (*linker_foo(const unsigned char *procName))() { return glXGetProcAddress(procName); }
__eglMustCastToProperFunctionPointerType __getProcAddress(const char *procname) { return (__eglMustCastToProperFunctionPointerType )glXGetProcAddress((const GLubyte *)procname); }
int main (int argc, char *argv[]) { Display *dpy; int nScreens, screenNum, i; enum INFO_FUNC func = LIST; char *funcArg = NULL; char *dpyName = NULL; GetScreenDriver = (glXGetScreenDriver_t *)glXGetProcAddress ("glXGetScreenDriver"); GetDriverConfig = (glXGetDriverConfig_t *)glXGetProcAddress ("glXGetDriverConfig"); if (!GetScreenDriver || !GetDriverConfig) { fprintf (stderr, "libGL is too old.\n"); return 1; } /* parse the command line */ for (i = 1; i < argc; ++i) { char **argPtr = NULL; if (!strcmp (argv[i], "-display")) argPtr = &dpyName; else if (!strcmp (argv[i], "nscreens")) func = NSCREENS; else if (!strcmp (argv[i], "driver")) { func = DRIVER; argPtr = &funcArg; } else if (!strcmp (argv[i], "options")) { func = OPTIONS; argPtr = &funcArg; } else { printUsage (); return 1; } if (argPtr) { if (++i == argc) { printUsage (); return 1; } *argPtr = argv[i]; } } /* parse screen number argument */ if (func == DRIVER || func == OPTIONS) { if (sscanf (funcArg, "%i", &screenNum) != 1) screenNum = -1; else if (screenNum < 0) { fprintf (stderr, "Negative screen number \"%s\".\n", funcArg); return 1; } } /* if the argument to the options command is a driver name, we can handle * it without opening an X connection */ if (func == OPTIONS && screenNum == -1) { const char *options = (*GetDriverConfig) (funcArg); if (!options) { fprintf (stderr, "Driver \"%s\" is not installed or does not support configuration.\n", funcArg); return 1; } printf ("%s", options); if (isatty (STDOUT_FILENO)) printf ("\n"); return 0; } /* driver command needs a valid screen number */ else if (func == DRIVER && screenNum == -1) { fprintf (stderr, "Invalid screen number \"%s\".\n", funcArg); return 1; } /* open display and count the number of screens */ if (!(dpy = XOpenDisplay (dpyName))) { fprintf (stderr, "Error: Couldn't open display\n"); return 1; } nScreens = ScreenCount (dpy); /* final check on the screen number argument (if any)*/ if ((func == DRIVER || func == OPTIONS) && screenNum >= nScreens) { fprintf (stderr, "Screen number \"%d\" out of range.\n", screenNum); return 1; } switch (func) { case NSCREENS: printf ("%d", nScreens); if (isatty (STDOUT_FILENO)) printf ("\n"); break; case DRIVER: { const char *name = (*GetScreenDriver) (dpy, screenNum); if (!name) { fprintf (stderr, "Screen \"%d\" is not direct rendering capable.\n", screenNum); return 1; } printf ("%s", name); if (isatty (STDOUT_FILENO)) printf ("\n"); break; } case OPTIONS: { const char *name = (*GetScreenDriver) (dpy, screenNum), *options; if (!name) { fprintf (stderr, "Screen \"%d\" is not direct rendering capable.\n", screenNum); return 1; } options = (*GetDriverConfig) (name); if (!options) { fprintf (stderr, "Driver \"%s\" is not installed or does not support configuration.\n", name); return 1; } printf ("%s", options); if (isatty (STDOUT_FILENO)) printf ("\n"); break; } case LIST: for (i = 0; i < nScreens; ++i) { const char *name = (*GetScreenDriver) (dpy, i); if (name) printf ("Screen %d: %s\n", i, name); else printf ("Screen %d: not direct rendering capable.\n", i); } } return 0; }
/** * Try to create a GLX context of the given version with flags/options. * Note: A version number is required in order to get a core profile * (at least w/ NVIDIA). */ static GLXContext create_context_flags(Display *dpy, GLXFBConfig fbconfig, int major, int minor, int contextFlags, int profileMask, Bool direct) { #ifdef GLX_ARB_create_context static PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB_func = 0; static Bool firstCall = True; int (*old_handler)(Display *, XErrorEvent *); GLXContext context; int attribs[20]; int n = 0; if (firstCall) { /* See if we have GLX_ARB_create_context_profile and get pointer to * glXCreateContextAttribsARB() function. */ const char *glxExt = glXQueryExtensionsString(dpy, 0); if (extension_supported("GLX_ARB_create_context_profile", glxExt)) { glXCreateContextAttribsARB_func = (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddress((const GLubyte *) "glXCreateContextAttribsARB"); } firstCall = False; } if (!glXCreateContextAttribsARB_func) return 0; /* setup attribute array */ if (major) { attribs[n++] = GLX_CONTEXT_MAJOR_VERSION_ARB; attribs[n++] = major; attribs[n++] = GLX_CONTEXT_MINOR_VERSION_ARB; attribs[n++] = minor; } if (contextFlags) { attribs[n++] = GLX_CONTEXT_FLAGS_ARB; attribs[n++] = contextFlags; } #ifdef GLX_ARB_create_context_profile if (profileMask) { attribs[n++] = GLX_CONTEXT_PROFILE_MASK_ARB; attribs[n++] = profileMask; } #endif attribs[n++] = 0; /* install X error handler */ old_handler = XSetErrorHandler(create_context_error_handler); CreateContextErrorFlag = False; /* try creating context */ context = glXCreateContextAttribsARB_func(dpy, fbconfig, 0, /* share_context */ direct, attribs); /* restore error handler */ XSetErrorHandler(old_handler); if (CreateContextErrorFlag) context = 0; if (context && direct) { if (!glXIsDirect(dpy, context)) { glXDestroyContext(dpy, context); return 0; } } return context; #else return 0; #endif }
bool CWindowUnix::Init(int width, int height, int bpp, axelynx::WindowMode wm, int samples) { XVisualInfo *vi; Colormap cmap; XSetWindowAttributes swa; int dummy; width_ = width; height_ = height; /*** (1) open a connection to the X server ***/ dpy_ = XOpenDisplay(NULL); if (dpy_ == NULL) fatalError("could not open display"); int nelements; GLXFBConfig *fbc = glXChooseFBConfig(dpy_, DefaultScreen(dpy_), 0, &nelements); /*** (2) make sure OpenGL's GLX extension supported ***/ if(!glXQueryExtension(dpy_, &dummy, &dummy)) fatalError("X server has no OpenGL GLX extension"); /*** (3) 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) fatalError("no RGB visual with depth buffer"); doubleBuffer_ = GL_FALSE; } //if(vi->class != TrueColor) // fatalError("TrueColor visual required for this program"); /*** (4) create an OpenGL rendering context ***/ /* create an OpenGL rendering context */ // cx_ = glXCreateContext(dpy_, vi, /* no shared dlists */ None, /* direct rendering if possible */ GL_TRUE); /*** (5) 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 | FocusChangeMask; win_ = XCreateWindow(dpy_, RootWindow(dpy_, vi->screen), 0, 0, width_, height_, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa); XSetStandardProperties(dpy_, win_, "main", "main", None, 0, 0, NULL); PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB"); int attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 3, 0}; cx_ = glXCreateContextAttribsARB(dpy_, *fbc, 0, true, attribs); //glXMakeCurrent (dpy, win, ctx); /*** (6) bind the rendering context to the window ***/ glXMakeCurrent(dpy_, win_, cx_); /*** (7) request the X window to be displayed on the screen ***/ XMapWindow(dpy_, win_); /*** (8) 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 */ /* establish initial viewport */ /* pedantic, full window size is default viewport */ isFullscreen_ = false; Resize(width,height,wm); fprintf(stderr, "succers: %d\n", width); return true; }
void* RenderContext_Base_GL::GetExtension(const char* name) { size_t len = std::strlen(name); if (len > 3 && !std::strcmp((name + len - 3), "ARB")) return (void*) glXGetProcAddressARB((const GLubyte *) name); return (void*) glXGetProcAddress((const GLubyte *) name); }
Error ContextGL_X11::initialize() { GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = NULL; // const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display)); glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB"); ERR_FAIL_COND_V( !glXCreateContextAttribsARB, ERR_UNCONFIGURED ); static int visual_attribs[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_DOUBLEBUFFER, true, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 24, None }; int fbcount; GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount); ERR_FAIL_COND_V(!fbc,ERR_UNCONFIGURED); XVisualInfo *vi = glXGetVisualFromFBConfig(x11_display, fbc[0]); XSetWindowAttributes swa; swa.colormap = XCreateColormap(x11_display, RootWindow(x11_display, vi->screen), vi->visual, AllocNone); swa.border_pixel = 0; swa.event_mask = StructureNotifyMask; /* char* windowid = getenv("GODOT_WINDOWID"); if (windowid) { //freopen("/home/punto/stdout", "w", stdout); //reopen("/home/punto/stderr", "w", stderr); x11_window = atol(windowid); } else { */ x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa); ERR_FAIL_COND_V(!x11_window,ERR_UNCONFIGURED); XMapWindow(x11_display, x11_window); while(true) { // wait for mapnotify (window created) XEvent e; XNextEvent(x11_display, &e); if (e.type == MapNotify) break; } //}; if (!OS::get_singleton()->get_video_mode().resizable) { XSizeHints *xsh; xsh = XAllocSizeHints(); xsh->flags = PMinSize | PMaxSize; xsh->min_width = OS::get_singleton()->get_video_mode().width; xsh->max_width = OS::get_singleton()->get_video_mode().width; xsh->min_height = OS::get_singleton()->get_video_mode().height; xsh->max_height = OS::get_singleton()->get_video_mode().height; XSetWMNormalHints(x11_display, x11_window, xsh); } if (!opengl_3_context) { //oldstyle context: p->glx_context = glXCreateContext(x11_display, vi, 0, GL_TRUE); } else { static int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 0, None }; p->glx_context = glXCreateContextAttribsARB(x11_display, fbc[0], NULL, true, context_attribs); ERR_FAIL_COND_V(!p->glx_context,ERR_UNCONFIGURED); } glXMakeCurrent(x11_display, x11_window, p->glx_context); /* glWrapperInit(wrapper_get_proc_address); glFlush(); glXSwapBuffers(x11_display,x11_window); */ //glXMakeCurrent(x11_display, None, NULL); return OK; }
//////////////////////////////////////////////////////////// /// /see WindowImpl::UseVerticalSync //////////////////////////////////////////////////////////// void WindowImplX11::UseVerticalSync(bool Enabled) { const GLubyte* ProcAddress = reinterpret_cast<const GLubyte*>("glXSwapIntervalSGI"); PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = reinterpret_cast<PFNGLXSWAPINTERVALSGIPROC>(glXGetProcAddress(ProcAddress)); if (glXSwapIntervalSGI) glXSwapIntervalSGI(Enabled ? 1 : 0); }
bool Example::init() { // Assign the appropriate procedure addresses to glGenbuffers, glBindBuffer, // and glBufferData. More wgl stuff. #ifdef _WIN32 glGenBuffers = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffers"); glBindBuffer = (PFNGLBINDBUFFERPROC)wglGetProcAddress("glBindBuffer"); glBufferData = (PFNGLBUFFERDATAPROC)wglGetProcAddress("glBufferData"); #else glGenBuffers = (PFNGLGENBUFFERSARBPROC)glXGetProcAddress((const GLubyte*)"glGenBuffers"); glBindBuffer = (PFNGLBINDBUFFERPROC)glXGetProcAddress((const GLubyte*)"glBindBuffer"); glBufferData = (PFNGLBUFFERDATAPROC)glXGetProcAddress((const GLubyte*)"glBufferData"); #endif if (!glGenBuffers || !glBindBuffer || !glBufferData) { std::cerr << "VBOs are not supported by your graphics card" << std::endl; return false; } // STUDENTS: Seed a random number generator using srand() and time() // Enable z-buffer depth sorting (objects in front hide objects behind them) glEnable(GL_DEPTH_TEST); // Specify colors used to clear color buffers glClearColor(0.5f, 0.5f, 0.5f, 0.5f); // STUDENTS: Change this loop so that it creates 15 random vertices // Let // X range from -3.5f to 3.5f // Y stay at 0.0f // Z range from -2.5f to 2.5f for (float point = -4.0f; point < 5.0; point+=0.5f) { m_vertices.push_back(point); //X m_vertices.push_back(0.0f); //Y m_vertices.push_back(0.0f); //Z } // 1. Generate a name for the buffer. // void glGenBuffers(GLsizei n, GLuint *buffers); // // In the method call below, we're generating one buffer name that will // be stored in m_vertexBuffer glGenBuffers(1, &m_vertexBuffer); // 2. Bind (activate) the buffer. // void glBindBuffer(GLenum target, GLuint buffer); // // Besides GL_ARRAY_BUFFER, another possible target is GL_ELEMENT_ARRAY_BUFFER, // which may be used in more complex renderings. glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); // 3. Store data in the buffer. // void glBufferData(GLenum target, GLsizeiptr size, // const GLvoid *data, GLenum usage); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * m_vertices.size(), &m_vertices[0], GL_STATIC_DRAW); //Return success return true; }
COffscreenGLContext::COffscreenGLContext() { if (!mainGlActiveTexture) mainGlActiveTexture = (PFNGLACTIVETEXTUREPROC)glXGetProcAddress((const GLubyte*)"glActiveTexture"); //! Get MainCtx & X11-Display GLXContext mainCtx = glXGetCurrentContext(); display = glXGetCurrentDisplay(); //GLXDrawable mainDrawable = glXGetCurrentDrawable(); if(!mainCtx) throw opengl_error("Couldn't create an offscreen GL context: glXGetCurrentContext failed!"); if (!display) throw opengl_error("Couldn't create an offscreen GL context: Couldn't determine display!"); int scrnum = XDefaultScreen(display); //! Create a FBConfig int nelements = 0; const int fbattribs[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, GLX_BUFFER_SIZE, 32, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8, None }; GLXFBConfig* fbcfg = glXChooseFBConfig(display, scrnum, (const int*)fbattribs, &nelements); if (!fbcfg || (nelements == 0)) throw opengl_error("Couldn't create an offscreen GL context: glXChooseFBConfig failed!"); //! Create a pbuffer (each render context needs a drawable) const int pbuf_attribs[] = { GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, GLX_PRESERVED_CONTENTS, false, None }; pbuf = glXCreatePbuffer(display, fbcfg[0], (const int*)pbuf_attribs); if (!pbuf) throw opengl_error("Couldn't create an offscreen GL context: glXCreatePbuffer failed!"); /* //Create a GL 3.0 context const int ctx_attribs[] = { //GLX_CONTEXT_MAJOR_VERSION_ARB, 2, //GLX_CONTEXT_MINOR_VERSION_ARB, 0, GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB, //GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, None }; workerCtx = glXCreateContextAttribsARB(display, fbcfg[0], mainCtx, true, ctx_attribs); */ //! Create render context workerCtx = glXCreateNewContext(display, fbcfg[0], GLX_RGBA_TYPE, mainCtx, true); if (!workerCtx) throw opengl_error("Couldn't create an offscreen GL context: glXCreateNewContext failed!"); XFree(fbcfg); }
/* initialize controller */ struct nvstusb_context * nvstusb_init(char const * fw) { /* initialize usb */ if (!nvstusb_usb_init()) return 0; /* open device */ struct nvstusb_usb_device *dev = nvstusb_usb_open_device(fw? fw : "nvstusb.fw"); if (0 == dev) return 0; /* allocate context */ struct nvstusb_context *ctx = malloc(sizeof(*ctx)); if (0 == ctx) { fprintf(stderr, "nvstusb: Could not allocate %d bytes for nvstusb_context...\n", (int)sizeof(*ctx)); nvstusb_usb_close_device(dev); nvstusb_usb_deinit(); return 0; } ctx->rate = 0.0; ctx->eye = 0; ctx->device = dev; ctx->vblank_method = 0; ctx->toggled3D = 0; ctx->invert_eyes = 0; ctx->b_thread_running = 0; /* Vblank init */ /* NVIDIA VBlank syncing environment variable defined, signal it and disable * any attempt to application side method */ if (getenv ("__GL_SYNC_TO_VBLANK")) { fprintf (stderr, "__GL_SYNC_TO_VBLANK defined in environment\n"); ctx->vblank_method = 2; goto out_err; } /* Swap interval */ glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddress("glXSwapIntervalSGI"); if (NULL != glXSwapIntervalSGI) { fprintf(stderr, "nvstusb: forcing vsync\n"); ctx->vblank_method = 3; } /* Sync Video */ glXGetVideoSyncSGI = (PFNGLXGETVIDEOSYNCSGIPROC)glXGetProcAddress("glXGetVideoSyncSGI"); glXWaitVideoSyncSGI = (PFNGLXWAITVIDEOSYNCSGIPROC)glXGetProcAddress("glXWaitVideoSyncSGI"); if (NULL == glXWaitVideoSyncSGI) { glXGetVideoSyncSGI = 0; } else { ctx->vblank_method = 1; } if (NULL != glXGetVideoSyncSGI ) { fprintf(stderr, "nvstusb: GLX_SGI_video_sync supported!\n"); } fprintf(stderr, "nvstusb:selected vblank method: %d\n", ctx->vblank_method); out_err: return ctx; }
bool CVideoSyncGLX::Setup(PUPDATECLOCK func) { CSingleLock lock(g_graphicsContext); m_glXWaitVideoSyncSGI = NULL; m_glXGetVideoSyncSGI = NULL; m_vInfo = NULL; m_Window = 0; m_Context = NULL; UpdateClock = func; int singleBufferAttributes[] = { GLX_RGBA, GLX_RED_SIZE, 0, GLX_GREEN_SIZE, 0, GLX_BLUE_SIZE, 0, None }; int ReturnV, SwaMask; unsigned int GlxTest; XSetWindowAttributes Swa; m_vInfo = NULL; m_Context = NULL; m_Window = 0; CLog::Log(LOGDEBUG, "CVideoReferenceClock: Setting up GLX"); g_Windowing.Register(this); m_displayLost = false; m_displayReset = false; m_lostEvent.Reset(); if (!m_Dpy) { m_Dpy = XOpenDisplay(NULL); if (!m_Dpy) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: Unable to open display"); return false; } } if (!glXQueryExtension(m_Dpy, NULL, NULL)) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: X server does not support GLX"); return false; } bool ExtensionFound = false; std::istringstream Extensions(glXQueryExtensionsString(m_Dpy, g_Windowing.GetCurrentScreen())); std::string ExtensionStr; while (!ExtensionFound) { Extensions >> ExtensionStr; if (Extensions.fail()) break; if (ExtensionStr == "GLX_SGI_video_sync") ExtensionFound = true; } if (!ExtensionFound) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: X server does not support GLX_SGI_video_sync"); return false; } m_vInfo = glXChooseVisual(m_Dpy, g_Windowing.GetCurrentScreen(), singleBufferAttributes); if (!m_vInfo) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXChooseVisual returned NULL"); return false; } Swa.border_pixel = 0; Swa.event_mask = StructureNotifyMask; Swa.colormap = XCreateColormap(m_Dpy, g_Windowing.GetWindow(), m_vInfo->visual, AllocNone ); SwaMask = CWBorderPixel | CWColormap | CWEventMask; m_Window = XCreateWindow(m_Dpy, g_Windowing.GetWindow(), 0, 0, 256, 256, 0, m_vInfo->depth, InputOutput, m_vInfo->visual, SwaMask, &Swa); m_Context = glXCreateContext(m_Dpy, m_vInfo, NULL, True); if (!m_Context) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXCreateContext returned NULL"); return false; } ReturnV = glXMakeCurrent(m_Dpy, m_Window, m_Context); if (ReturnV != True) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXMakeCurrent returned %i", ReturnV); return false; } m_glXWaitVideoSyncSGI = (int (*)(int, int, unsigned int*))glXGetProcAddress((const GLubyte*)"glXWaitVideoSyncSGI"); if (!m_glXWaitVideoSyncSGI) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXWaitVideoSyncSGI not found"); return false; } ReturnV = m_glXWaitVideoSyncSGI(2, 0, &GlxTest); if (ReturnV) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXWaitVideoSyncSGI returned %i", ReturnV); return false; } m_glXGetVideoSyncSGI = (int (*)(unsigned int*))glXGetProcAddress((const GLubyte*)"glXGetVideoSyncSGI"); if (!m_glXGetVideoSyncSGI) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXGetVideoSyncSGI not found"); return false; } ReturnV = m_glXGetVideoSyncSGI(&GlxTest); if (ReturnV) { CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXGetVideoSyncSGI returned %i", ReturnV); return false; } return true; }
__GLXextFuncPtr glXGetProcAddressEXT(const GLubyte * procname){ return glXGetProcAddress(procname); }
const GrGLInterface* GrGLCreateNativeInterface() { if (NULL != glXGetCurrentContext()) { const char* versionString = (const char*) glGetString(GL_VERSION); GrGLVersion glVer = GrGLGetVersionFromString(versionString); // This may or may not succeed depending on the gl version. GrGLGetStringiProc glGetStringi = (GrGLGetStringiProc) glXGetProcAddress(reinterpret_cast<const GLubyte*>("glGetStringi")); GrGLExtensions extensions; if (!extensions.init(kGL_GrGLStandard, glGetString, glGetStringi, glGetIntegerv)) { return NULL; } if (glVer < GR_GL_VER(1,5)) { // We must have array and element_array buffer objects. return NULL; } GrGLInterface* interface = SkNEW(GrGLInterface()); interface->fActiveTexture = glActiveTexture; GR_GL_GET_PROC(AttachShader); GR_GL_GET_PROC(BindAttribLocation); GR_GL_GET_PROC(BindBuffer); GR_GL_GET_PROC(BindFragDataLocation); GR_GL_GET_PROC(BeginQuery); interface->fBindTexture = glBindTexture; interface->fBlendFunc = glBlendFunc; if (glVer >= GR_GL_VER(1,4) || extensions.has("GL_ARB_imaging") || extensions.has("GL_EXT_blend_color")) { GR_GL_GET_PROC(BlendColor); } GR_GL_GET_PROC(BufferData); GR_GL_GET_PROC(BufferSubData); interface->fClear = glClear; interface->fClearColor = glClearColor; interface->fClearStencil = glClearStencil; interface->fClientActiveTexture = glClientActiveTexture; interface->fColorMask = glColorMask; GR_GL_GET_PROC(CompileShader); interface->fCompressedTexImage2D = glCompressedTexImage2D; interface->fCopyTexSubImage2D = glCopyTexSubImage2D; GR_GL_GET_PROC(CreateProgram); GR_GL_GET_PROC(CreateShader); interface->fCullFace = glCullFace; GR_GL_GET_PROC(DeleteBuffers); GR_GL_GET_PROC(DeleteProgram); GR_GL_GET_PROC(DeleteQueries); GR_GL_GET_PROC(DeleteShader); interface->fDeleteTextures = glDeleteTextures; interface->fDepthMask = glDepthMask; interface->fDisable = glDisable; interface->fDisableClientState = glDisableClientState; GR_GL_GET_PROC(DisableVertexAttribArray); interface->fDrawArrays = glDrawArrays; interface->fDrawBuffer = glDrawBuffer; GR_GL_GET_PROC(DrawBuffers); interface->fDrawElements = glDrawElements; interface->fEnable = glEnable; interface->fEnableClientState = glEnableClientState; GR_GL_GET_PROC(EnableVertexAttribArray); GR_GL_GET_PROC(EndQuery); interface->fFinish = glFinish; interface->fFlush = glFlush; interface->fFrontFace = glFrontFace; GR_GL_GET_PROC(GenBuffers); GR_GL_GET_PROC(GenerateMipmap); GR_GL_GET_PROC(GetBufferParameteriv); interface->fGetError = glGetError; interface->fGetIntegerv = glGetIntegerv; GR_GL_GET_PROC(GetQueryObjectiv); GR_GL_GET_PROC(GetQueryObjectuiv); if (glVer >= GR_GL_VER(3,3) || extensions.has("GL_ARB_timer_query")) { GR_GL_GET_PROC(GetQueryObjecti64v); GR_GL_GET_PROC(GetQueryObjectui64v); GR_GL_GET_PROC(QueryCounter); } else if (extensions.has("GL_EXT_timer_query")) { GR_GL_GET_PROC_SUFFIX(GetQueryObjecti64v, EXT); GR_GL_GET_PROC_SUFFIX(GetQueryObjectui64v, EXT); } GR_GL_GET_PROC(GetQueryiv); GR_GL_GET_PROC(GetProgramInfoLog); GR_GL_GET_PROC(GetProgramiv); GR_GL_GET_PROC(GetShaderInfoLog); GR_GL_GET_PROC(GetShaderiv); interface->fGetString = glGetString; GR_GL_GET_PROC(GetStringi); interface->fGetTexLevelParameteriv = glGetTexLevelParameteriv; GR_GL_GET_PROC(GenQueries); interface->fGenTextures = glGenTextures; GR_GL_GET_PROC(GetUniformLocation); interface->fLineWidth = glLineWidth; GR_GL_GET_PROC(LinkProgram); GR_GL_GET_PROC(MapBuffer); interface->fPixelStorei = glPixelStorei; interface->fReadBuffer = glReadBuffer; interface->fReadPixels = glReadPixels; interface->fScissor = glScissor; GR_GL_GET_PROC(ShaderSource); interface->fStencilFunc = glStencilFunc; GR_GL_GET_PROC(StencilFuncSeparate); interface->fStencilMask = glStencilMask; GR_GL_GET_PROC(StencilMaskSeparate); interface->fStencilOp = glStencilOp; GR_GL_GET_PROC(StencilOpSeparate); interface->fTexImage2D = glTexImage2D; interface->fTexGenf = glTexGenf; interface->fTexGenfv = glTexGenfv; interface->fTexGeni = glTexGeni; interface->fTexParameteri = glTexParameteri; interface->fTexParameteriv = glTexParameteriv; if (glVer >= GR_GL_VER(4,2) || extensions.has("GL_ARB_texture_storage")) { GR_GL_GET_PROC(TexStorage2D); } else if (extensions.has("GL_EXT_texture_storage")) { GR_GL_GET_PROC_SUFFIX(TexStorage2D, EXT); } interface->fTexSubImage2D = glTexSubImage2D; GR_GL_GET_PROC(Uniform1f); GR_GL_GET_PROC(Uniform1i); GR_GL_GET_PROC(Uniform1fv); GR_GL_GET_PROC(Uniform1iv); GR_GL_GET_PROC(Uniform2f); GR_GL_GET_PROC(Uniform2i); GR_GL_GET_PROC(Uniform2fv); GR_GL_GET_PROC(Uniform2iv); GR_GL_GET_PROC(Uniform3f); GR_GL_GET_PROC(Uniform3i); GR_GL_GET_PROC(Uniform3fv); GR_GL_GET_PROC(Uniform3iv); GR_GL_GET_PROC(Uniform4f); GR_GL_GET_PROC(Uniform4i); GR_GL_GET_PROC(Uniform4fv); GR_GL_GET_PROC(Uniform4iv); GR_GL_GET_PROC(UniformMatrix2fv); GR_GL_GET_PROC(UniformMatrix3fv); GR_GL_GET_PROC(UniformMatrix4fv); GR_GL_GET_PROC(UnmapBuffer); GR_GL_GET_PROC(UseProgram); GR_GL_GET_PROC(VertexAttrib4fv); GR_GL_GET_PROC(VertexAttribPointer); GR_GL_GET_PROC(VertexPointer); interface->fViewport = glViewport; GR_GL_GET_PROC(BindFragDataLocationIndexed); if (glVer >= GR_GL_VER(3,0) || extensions.has("GL_ARB_vertex_array_object")) { // no ARB suffix for GL_ARB_vertex_array_object GR_GL_GET_PROC(BindVertexArray); GR_GL_GET_PROC(GenVertexArrays); GR_GL_GET_PROC(DeleteVertexArrays); } // First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since // GL_ARB_framebuffer_object doesn't use ARB suffix.) if (glVer >= GR_GL_VER(3,0) || extensions.has("GL_ARB_framebuffer_object")) { GR_GL_GET_PROC(GenFramebuffers); GR_GL_GET_PROC(GetFramebufferAttachmentParameteriv); GR_GL_GET_PROC(GetRenderbufferParameteriv); GR_GL_GET_PROC(BindFramebuffer); GR_GL_GET_PROC(FramebufferTexture2D); GR_GL_GET_PROC(CheckFramebufferStatus); GR_GL_GET_PROC(DeleteFramebuffers); GR_GL_GET_PROC(RenderbufferStorage); GR_GL_GET_PROC(GenRenderbuffers); GR_GL_GET_PROC(DeleteRenderbuffers); GR_GL_GET_PROC(FramebufferRenderbuffer); GR_GL_GET_PROC(BindRenderbuffer); GR_GL_GET_PROC(RenderbufferStorageMultisample); GR_GL_GET_PROC(BlitFramebuffer); } else if (extensions.has("GL_EXT_framebuffer_object")) { GR_GL_GET_PROC_SUFFIX(GenFramebuffers, EXT); GR_GL_GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT); GR_GL_GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT); GR_GL_GET_PROC_SUFFIX(BindFramebuffer, EXT); GR_GL_GET_PROC_SUFFIX(FramebufferTexture2D, EXT); GR_GL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT); GR_GL_GET_PROC_SUFFIX(DeleteFramebuffers, EXT); GR_GL_GET_PROC_SUFFIX(RenderbufferStorage, EXT); GR_GL_GET_PROC_SUFFIX(GenRenderbuffers, EXT); GR_GL_GET_PROC_SUFFIX(DeleteRenderbuffers, EXT); GR_GL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT); GR_GL_GET_PROC_SUFFIX(BindRenderbuffer, EXT); if (extensions.has("GL_EXT_framebuffer_multisample")) { GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT); } if (extensions.has("GL_EXT_framebuffer_blit")) { GR_GL_GET_PROC_SUFFIX(BlitFramebuffer, EXT); } } else { // we must have FBOs delete interface; return NULL; } GR_GL_GET_PROC(LoadIdentity); GR_GL_GET_PROC(LoadMatrixf); GR_GL_GET_PROC(MatrixMode); if (extensions.has("GL_NV_path_rendering")) { GR_GL_GET_PROC_SUFFIX(PathCommands, NV); GR_GL_GET_PROC_SUFFIX(PathCoords, NV); GR_GL_GET_PROC_SUFFIX(PathSubCommands, NV); GR_GL_GET_PROC_SUFFIX(PathSubCoords, NV); GR_GL_GET_PROC_SUFFIX(PathString, NV); GR_GL_GET_PROC_SUFFIX(PathGlyphs, NV); GR_GL_GET_PROC_SUFFIX(PathGlyphRange, NV); GR_GL_GET_PROC_SUFFIX(WeightPaths, NV); GR_GL_GET_PROC_SUFFIX(CopyPath, NV); GR_GL_GET_PROC_SUFFIX(InterpolatePaths, NV); GR_GL_GET_PROC_SUFFIX(TransformPath, NV); GR_GL_GET_PROC_SUFFIX(PathParameteriv, NV); GR_GL_GET_PROC_SUFFIX(PathParameteri, NV); GR_GL_GET_PROC_SUFFIX(PathParameterfv, NV); GR_GL_GET_PROC_SUFFIX(PathParameterf, NV); GR_GL_GET_PROC_SUFFIX(PathDashArray, NV); GR_GL_GET_PROC_SUFFIX(GenPaths, NV); GR_GL_GET_PROC_SUFFIX(DeletePaths, NV); GR_GL_GET_PROC_SUFFIX(IsPath, NV); GR_GL_GET_PROC_SUFFIX(PathStencilFunc, NV); GR_GL_GET_PROC_SUFFIX(PathStencilDepthOffset, NV); GR_GL_GET_PROC_SUFFIX(StencilFillPath, NV); GR_GL_GET_PROC_SUFFIX(StencilStrokePath, NV); GR_GL_GET_PROC_SUFFIX(StencilFillPathInstanced, NV); GR_GL_GET_PROC_SUFFIX(StencilStrokePathInstanced, NV); GR_GL_GET_PROC_SUFFIX(PathCoverDepthFunc, NV); GR_GL_GET_PROC_SUFFIX(PathColorGen, NV); GR_GL_GET_PROC_SUFFIX(PathTexGen, NV); GR_GL_GET_PROC_SUFFIX(PathFogGen, NV); GR_GL_GET_PROC_SUFFIX(CoverFillPath, NV); GR_GL_GET_PROC_SUFFIX(CoverStrokePath, NV); GR_GL_GET_PROC_SUFFIX(CoverFillPathInstanced, NV); GR_GL_GET_PROC_SUFFIX(CoverStrokePathInstanced, NV); GR_GL_GET_PROC_SUFFIX(GetPathParameteriv, NV); GR_GL_GET_PROC_SUFFIX(GetPathParameterfv, NV); GR_GL_GET_PROC_SUFFIX(GetPathCommands, NV); GR_GL_GET_PROC_SUFFIX(GetPathCoords, NV); GR_GL_GET_PROC_SUFFIX(GetPathDashArray, NV); GR_GL_GET_PROC_SUFFIX(GetPathMetrics, NV); GR_GL_GET_PROC_SUFFIX(GetPathMetricRange, NV); GR_GL_GET_PROC_SUFFIX(GetPathSpacing, NV); GR_GL_GET_PROC_SUFFIX(GetPathColorGeniv, NV); GR_GL_GET_PROC_SUFFIX(GetPathColorGenfv, NV); GR_GL_GET_PROC_SUFFIX(GetPathTexGeniv, NV); GR_GL_GET_PROC_SUFFIX(GetPathTexGenfv, NV); GR_GL_GET_PROC_SUFFIX(IsPointInFillPath, NV); GR_GL_GET_PROC_SUFFIX(IsPointInStrokePath, NV); GR_GL_GET_PROC_SUFFIX(GetPathLength, NV); GR_GL_GET_PROC_SUFFIX(PointAlongPath, NV); } interface->fStandard = kGL_GrGLStandard; return interface; } else { return NULL; } }
void GlxContext::CreateContext(GlxContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings) { // Save the creation settings mySettings = settings; // Get the attributes of the target window XWindowAttributes windowAttributes; if (XGetWindowAttributes(myDisplay, myWindow, &windowAttributes) == 0) { Err() << "Failed to get the window attributes" << std::endl; return; } // Setup the visual infos to match XVisualInfo tpl; tpl.depth = windowAttributes.depth; tpl.visualid = XVisualIDFromVisual(windowAttributes.visual); tpl.screen = DefaultScreen(myDisplay); // Get all the visuals matching the template int nbVisuals = 0; XVisualInfo* visuals = XGetVisualInfo(myDisplay, VisualDepthMask | VisualIDMask | VisualScreenMask, &tpl, &nbVisuals); if (!visuals || (nbVisuals == 0)) { if (visuals) XFree(visuals); Err() << "There is no valid visual for the selected screen" << std::endl; return; } // Find the best visual int bestScore = 0xFFFF; XVisualInfo* bestVisual = NULL; for (int i = 0; i < nbVisuals; ++i) { // Get the current visual attributes int RGBA, doubleBuffer, red, green, blue, alpha, depth, stencil, multiSampling, samples; glXGetConfig(myDisplay, &visuals[i], GLX_RGBA, &RGBA); glXGetConfig(myDisplay, &visuals[i], GLX_DOUBLEBUFFER, &doubleBuffer); glXGetConfig(myDisplay, &visuals[i], GLX_RED_SIZE, &red); glXGetConfig(myDisplay, &visuals[i], GLX_GREEN_SIZE, &green); glXGetConfig(myDisplay, &visuals[i], GLX_BLUE_SIZE, &blue); glXGetConfig(myDisplay, &visuals[i], GLX_ALPHA_SIZE, &alpha); glXGetConfig(myDisplay, &visuals[i], GLX_DEPTH_SIZE, &depth); glXGetConfig(myDisplay, &visuals[i], GLX_STENCIL_SIZE, &stencil); glXGetConfig(myDisplay, &visuals[i], GLX_SAMPLE_BUFFERS_ARB, &multiSampling); glXGetConfig(myDisplay, &visuals[i], GLX_SAMPLES_ARB, &samples); // First check the mandatory parameters if ((RGBA == 0) || (doubleBuffer == 0)) continue; // Evaluate the current configuration int color = red + green + blue + alpha; int score = EvaluateFormat(bitsPerPixel, mySettings, color, depth, stencil, multiSampling ? samples : 0); // Keep it if it's better than the current best if (score < bestScore) { bestScore = score; bestVisual = &visuals[i]; } } // Make sure that we have found a visual if (!bestVisual) { Err() << "Failed to find a suitable pixel format for the window -- cannot create OpenGL context" << std::endl; return; } // Get the context to share display lists with GLXContext toShare = shared ? shared->myContext : NULL; // Create the OpenGL context -- first try context versions >= 3.0 if it is requested (they require special code) while (!myContext && (mySettings.MajorVersion >= 3)) { const GLubyte* name = reinterpret_cast<const GLubyte*>("glXCreateContextAttribsARB"); PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(name)); if (glXCreateContextAttribsARB) { int nbConfigs = 0; GLXFBConfig* configs = glXChooseFBConfig(myDisplay, DefaultScreen(myDisplay), NULL, &nbConfigs); if (configs && nbConfigs) { // Create the context int attributes[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, mySettings.MajorVersion, GLX_CONTEXT_MINOR_VERSION_ARB, mySettings.MinorVersion, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0, 0 }; myContext = glXCreateContextAttribsARB(myDisplay, configs[0], toShare, true, attributes); } if (configs) XFree(configs); } // If we couldn't create the context, lower the version number and try again -- stop at 3.0 // Invalid version numbers will be generated by this algorithm (like 3.9), but we really don't care if (!myContext) { if (mySettings.MinorVersion > 0) { // If the minor version is not 0, we decrease it and try again mySettings.MinorVersion--; } else { // If the minor version is 0, we decrease the major version mySettings.MajorVersion--; mySettings.MinorVersion = 9; } } } // If the OpenGL >= 3.0 context failed or if we don't want one, create a regular OpenGL 1.x/2.x context if (!myContext) { // set the context version to 2.0 (arbitrary) mySettings.MajorVersion = 2; mySettings.MinorVersion = 0; myContext = glXCreateContext(myDisplay, bestVisual, toShare, true); if (!myContext) { Err() << "Failed to create an OpenGL context for this window" << std::endl; return; } } // Update the creation settings from the chosen format int depth, stencil, multiSampling, samples; glXGetConfig(myDisplay, bestVisual, GLX_DEPTH_SIZE, &depth); glXGetConfig(myDisplay, bestVisual, GLX_STENCIL_SIZE, &stencil); glXGetConfig(myDisplay, bestVisual, GLX_SAMPLE_BUFFERS_ARB, &multiSampling); glXGetConfig(myDisplay, bestVisual, GLX_SAMPLES_ARB, &samples); mySettings.DepthBits = static_cast<unsigned int>(depth); mySettings.StencilBits = static_cast<unsigned int>(stencil); mySettings.AntialiasingLevel = multiSampling ? samples : 0; // Change the target window's colormap so that it matches the context's one ::Window root = RootWindow(myDisplay, DefaultScreen(myDisplay)); Colormap colorMap = XCreateColormap(myDisplay, root, bestVisual->visual, AllocNone); XSetWindowColormap(myDisplay, myWindow, colorMap); // Free the temporary visuals array XFree(visuals); }
static void make_window( Display *dpy, const char *name, int x, int y, int width, int height, Window *winRet, GLXContext *ctxRet) { int scrnum; XSetWindowAttributes attr; unsigned long mask; Window root; Window win; GLXContext ctx; XVisualInfo *visinfo; scrnum = DefaultScreen( dpy ); root = RootWindow( dpy, scrnum ); // 3.2 support //#ifdef glXCreateContextAttribsARB if (gContextVersionMajor > 2) { // We asked for OpenGL3+, but can we do it? typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*); // Verify GL driver supports glXCreateContextAttribsARB() glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0; // Verify that GLX implementation supports the new context create call if ( strstr( glXQueryExtensionsString( dpy, scrnum ), "GLX_ARB_create_context" ) != 0 ) glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddress( (const GLubyte *) "glXCreateContextAttribsARB" ); if ( !glXCreateContextAttribsARB ) { printf( "Can't create new-style GL context\n" ); } // We need this for OpenGL3 int elemc; GLXFBConfig *fbcfg; int attribs[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, // ? GLX_RED_SIZE, 1, // 1 = prefer high precision GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_ALPHA_SIZE, 1, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None }; int i = 12; if (gMode & GLUT_DOUBLE) { attribs[i++] = GLX_DOUBLEBUFFER; attribs[i++] = 1; } if (gMode & GLUT_DEPTH) { attribs[i++] = GLX_DEPTH_SIZE; attribs[i++] = 1; } if (gMode & GLUT_STENCIL) { attribs[i++] = GLX_STENCIL_SIZE; attribs[i++] = 8; // Smallest available, at least 8. Configurable setting needed! } if (gMode & GLUT_MULTISAMPLE) { attribs[i++] = GLX_SAMPLE_BUFFERS; attribs[i++] = 1; attribs[i++] = GLX_SAMPLES; attribs[i++] = 4; } fbcfg = glXChooseFBConfig(dpy, scrnum, attribs, &elemc); if (!fbcfg) { fbcfg = glXChooseFBConfig(dpy, scrnum, NULL, &elemc); } if (!fbcfg) printf("Couldn't get FB configs\n"); int gl3attr[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, gContextVersionMajor, GLX_CONTEXT_MINOR_VERSION_ARB, gContextVersionMinor, // GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, None }; ctx = glXCreateContextAttribsARB(dpy, fbcfg[0], NULL, 1, gl3attr); if (ctx == NULL) printf("No ctx!\n"); visinfo = glXGetVisualFromFBConfig(dpy, fbcfg[0]); if (!visinfo) printf("Error: couldn't create OpenGL window with this pixel format.\n"); } else // old style //#endif { int attribs[] = { GLX_RGBA, GLX_RED_SIZE, 1, // 1 = prefer high precision GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None }; int i = 7; if (gMode & GLUT_DOUBLE) attribs[i++] = GLX_DOUBLEBUFFER; if (gMode & GLUT_DEPTH) { attribs[i++] = GLX_DEPTH_SIZE; attribs[i++] = 1; } if (gMode & GLUT_STENCIL) { attribs[i++] = GLX_STENCIL_SIZE; attribs[i++] = 8; // Smallest available, at least 8. Configurable setting needed! } visinfo = glXChooseVisual( dpy, scrnum, attribs ); if (!visinfo) { printf("Error: couldn't get a visual according to settings\n"); exit(1); } ctx = glXCreateContext( dpy, visinfo, 0, True ); if (ctx == NULL) printf("No ctx!\n"); } /* window attributes */ attr.background_pixel = 0; attr.border_pixel = 0; attr.colormap = XCreateColormap( dpy, root, visinfo->visual, AllocNone); attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPress | ButtonReleaseMask | Button1MotionMask | PointerMotionMask; attr.override_redirect = 0; mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect; win = XCreateWindow( dpy, root, x, y, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr ); // Register delete! wmDeleteMessage = XInternAtom(dpy, "WM_DELETE_WINDOW", False); XSetWMProtocols(dpy, win, &wmDeleteMessage, 1); // Register /* set hints and properties */ XSizeHints sizehints; sizehints.x = x; sizehints.y = y; sizehints.width = width; sizehints.height = height; sizehints.flags = USSize | USPosition; XSetNormalHints(dpy, win, &sizehints); XSetStandardProperties(dpy, win, name, name, None, (char **)NULL, 0, &sizehints); if (!ctx) { printf("Error: glXCreateContext failed\n"); exit(1); } XFree(visinfo); *winRet = win; *ctxRet = ctx; }
static bool borisgl_initialize(int width, int height, const char *title) { int screen; Window root; XVisualInfo *xvi; int fbcount; GLXFBConfig *fbconfiglist, fbconfig; int i; const int glx_attribs[] = { GLX_X_RENDERABLE, True, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 1, GLX_DOUBLEBUFFER, True, None }; static int ctx_attribs[] = { #if USE_GLES2 GLX_CONTEXT_MAJOR_VERSION_ARB, 2, GLX_CONTEXT_MINOR_VERSION_ARB, 0, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_ES2_PROFILE_BIT_EXT, #else GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 0, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, /* GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, */ #endif None }; dpy = XOpenDisplay(NULL); if (!dpy) return false; wm_protocols = XInternAtom(dpy, "WM_PROTOCOLS", False); wm_delete_window = XInternAtom(dpy, "WM_DELETE_WINDOW", 0); screen = DefaultScreen(dpy); root = RootWindow(dpy, screen); fbconfiglist = glXChooseFBConfig(dpy, screen, glx_attribs, &fbcount); if (fbcount <= 0) { pr_err("No valid FB configurations"); return 1; } for (i = 0; i < fbcount; i++) { xvi = glXGetVisualFromFBConfig(dpy, fbconfiglist[i]); if (!xvi) continue; fbconfig = fbconfiglist[i]; goto found_fbconfig; } pr_err("No valid FB configurations"); return 1; found_fbconfig: XFree(fbconfiglist); XSetWindowAttributes wattr; wattr.event_mask = StructureNotifyMask | KeyPressMask; wattr.background_pixmap = None; wattr.background_pixel = 0; wattr.border_pixel = 0; wattr.colormap = XCreateColormap(dpy, root, xvi->visual, AllocNone); win = XCreateWindow(dpy, root, (DisplayWidth(dpy, screen) - width) / 2, (DisplayHeight(dpy, screen) - height) / 2, width, height, 0, xvi->depth, InputOutput, xvi->visual, CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask, &wattr); if (!win) { pr_err("Unable to create window"); return false; } /* setup various window manager(WM) metadata */ if (title) XStoreName(dpy, win, title); XSizeHints sizehints; sizehints.flags = PPosition | PBaseSize | PMinSize | PMaxSize | PResizeInc | PAspect; sizehints.x = 200; sizehints.y = 100; sizehints.base_width = width; sizehints.base_height = height; sizehints.min_width = width / 8; sizehints.min_height = height / 8; sizehints.max_width = width * 8 ; sizehints.max_height = height * 8; sizehints.width_inc = 16; sizehints.height_inc = 16; sizehints.min_aspect.x = width; sizehints.min_aspect.y = height; sizehints.max_aspect.x = width; sizehints.max_aspect.y = height; XSetWMNormalHints(dpy, win, &sizehints ); XSetWMProtocols(dpy, win, &wm_delete_window, 1); /* make a temporary context to find glXCreateContextAttribsARB() */ GLXContext ctx_tmp = glXCreateContext(dpy, xvi, 0, True); if (!ctx_tmp) { pr_err("Failed to allocate legacy GL context!"); goto failed; } glXMakeCurrent(dpy, win, ctx_tmp); PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB"); if (!glXCreateContextAttribsARB) { pr_err("Failed to bind glXCreateContextAttribsARB!"); glXMakeCurrent(dpy, None, 0); glXDestroyContext(dpy, ctx_tmp); goto failed_destroy_context; } glXMakeCurrent(dpy, None, 0); glXDestroyContext(dpy, ctx_tmp); /* now that we have glXCreateContextAttribsARB, we can make the real context */ ctx = glXCreateContextAttribsARB(dpy, fbconfig, 0, True, ctx_attribs); if (!ctx) { pr_err("Failed to allocate GL context!"); goto failed; } XSync(dpy, False); glXMakeCurrent(dpy, win, ctx); pr_info("GL_VERSION=%s", glGetString(GL_VERSION)); pr_info("GL_RENDERER=%s", glGetString(GL_RENDERER)); #if 0 // not supported/broken on one of my systems GLint gl_major = 0, gl_minor = 0; glGetIntegerv(GL_MAJOR_VERSION, &gl_major); glerr("GL_MAJOR_VERSION"); glGetIntegerv(GL_MINOR_VERSION, &gl_minor); inf("GL_VERSION_MAJOR=%d GL_VERSION_MINOR=%d", (int)gl_major, (int)gl_minor); #endif PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddress((const GLubyte*)"glXSwapIntervalEXT"); if (!glXSwapIntervalEXT) { pr_err("Failed to bind glXCreateContextAttribsARB!"); goto failed_destroy_context; } glXSwapIntervalEXT(dpy, win, 1); /* done - we can show the window */ XMapRaised(dpy, win); XFlush(dpy); /* report to the game that we are ready */ game_initialize(); return true; failed_destroy_context: glXMakeCurrent(dpy, None, 0); glXDestroyContext(dpy, ctx); failed: XDestroyWindow(dpy, win); return false; }
int main(int argc, char** argv) { int attrib[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_DOUBLEBUFFER, True, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, None }; PlatformContext context; context.MainDisplay = XOpenDisplay(NULL); int screenIndex = DefaultScreen(context.MainDisplay); Window root = RootWindow(context.MainDisplay, screenIndex); int fbcount; PFNGLXCHOOSEFBCONFIGPROC glXChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddress((GLubyte*)"glXChooseFBConfig"); GLXFBConfig *fbc = glXChooseFBConfig(context.MainDisplay, screenIndex, attrib, &fbcount); if (!fbc) pezFatal("Failed to retrieve a framebuffer config\n"); PFNGLXGETVISUALFROMFBCONFIGPROC glXGetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC) glXGetProcAddress((GLubyte*)"glXGetVisualFromFBConfig"); if (!glXGetVisualFromFBConfig) pezFatal("Failed to get a GLX function pointer\n"); PFNGLXGETFBCONFIGATTRIBPROC glXGetFBConfigAttrib = (PFNGLXGETFBCONFIGATTRIBPROC) glXGetProcAddress((GLubyte*)"glXGetFBConfigAttrib"); if (!glXGetFBConfigAttrib) pezFatal("Failed to get a GLX function pointer\n"); if (PezGetConfig().Multisampling) { int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999; for ( int i = 0; i < fbcount; i++ ) { XVisualInfo *vi = glXGetVisualFromFBConfig( context.MainDisplay, fbc[i] ); if (!vi) { continue; } int samp_buf, samples; glXGetFBConfigAttrib( context.MainDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf ); glXGetFBConfigAttrib( context.MainDisplay, fbc[i], GLX_SAMPLES , &samples ); //printf( " Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d," // " SAMPLES = %d\n", // i, (unsigned int) vi->visualid, samp_buf, samples ); if ( best_fbc < 0 || (samp_buf && samples > best_num_samp) ) best_fbc = i, best_num_samp = samples; if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp ) worst_fbc = i, worst_num_samp = samples; XFree( vi ); } fbc[0] = fbc[ best_fbc ]; } XVisualInfo *visinfo = glXGetVisualFromFBConfig(context.MainDisplay, fbc[0]); if (!visinfo) pezFatal("Error: couldn't create OpenGL window with this pixel format.\n"); XSetWindowAttributes attr; attr.background_pixel = 0; attr.border_pixel = 0; attr.colormap = XCreateColormap(context.MainDisplay, root, visinfo->visual, AllocNone); attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask; context.MainWindow = XCreateWindow( context.MainDisplay, root, 0, 0, PezGetConfig().Width, PezGetConfig().Height, 0, visinfo->depth, InputOutput, visinfo->visual, CWBackPixel | /*CWBorderPixel |*/ CWColormap | CWEventMask, &attr ); int borderless = 1; if (borderless) { Atom mwmHintsProperty = XInternAtom(context.MainDisplay, "_MOTIF_WM_HINTS", 0); MwmHints hints = {0}; hints.flags = MWM_HINTS_DECORATIONS; hints.decorations = 0; XChangeProperty(context.MainDisplay, context.MainWindow, mwmHintsProperty, mwmHintsProperty, 32, PropModeReplace, (unsigned char *)&hints, PROP_MWM_HINTS_ELEMENTS); } XMapWindow(context.MainDisplay, context.MainWindow); int centerWindow = 1; if (centerWindow) { Screen* pScreen = XScreenOfDisplay(context.MainDisplay, screenIndex); int left = XWidthOfScreen(pScreen)/2 - PezGetConfig().Width/2; int top = XHeightOfScreen(pScreen)/2 - PezGetConfig().Height/2; XMoveWindow(context.MainDisplay, context.MainWindow, left, top); } GLXContext glcontext = 0; if (PEZ_FORWARD_COMPATIBLE_GL) { PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribs = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((GLubyte*)"glXCreateContextAttribsARB"); if (!glXCreateContextAttribs) { pezFatal("Your platform does not support OpenGL 4.0.\n" "Try changing PEZ_FORWARD_COMPATIBLE_GL to 0.\n"); } int attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 4, GLX_CONTEXT_MINOR_VERSION_ARB, 0, GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; glcontext = glXCreateContextAttribs(context.MainDisplay, fbc[0], NULL, True, attribs); } else { glcontext = glXCreateContext(context.MainDisplay, visinfo, NULL, True); } glXMakeCurrent(context.MainDisplay, context.MainWindow, glcontext); PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress((GLubyte*)"glXSwapIntervalSGI"); if (glXSwapIntervalSGI) { glXSwapIntervalSGI(PezGetConfig().VerticalSync ? 1 : 0); } /* GLenum err = glewInit(); if (GLEW_OK != err) pezFatal("GLEW Error: %s\n", glewGetErrorString(err)); // Work around some GLEW issues: #define glewGetProcAddress(name) (*glXGetProcAddressARB)(name) glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)glewGetProcAddress((const GLubyte*)"glPatchParameteri"); glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)glewGetProcAddress((const GLubyte*)"glBindVertexArray"); glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)glewGetProcAddress((const GLubyte*)"glDeleteVertexArrays"); glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)glewGetProcAddress((const GLubyte*)"glGenVertexArrays"); glIsVertexArray = (PFNGLISVERTEXARRAYPROC)glewGetProcAddress((const GLubyte*)"glIsVertexArray"); */ // Reset OpenGL error state: glGetError(); // Lop off the trailing .c bstring name = bfromcstr(PezGetConfig().Title); bstring shaderPrefix = bmidstr(name, 0, blength(name) - 1); pezSwInit(bdata(shaderPrefix)); bdestroy(shaderPrefix); // Set up the Shader Wrangler pezSwAddPath("./", ".glsl"); pezSwAddPath("../", ".glsl"); char qualifiedPath[128]; strcpy(qualifiedPath, pezResourcePath()); strcat(qualifiedPath, "/"); pezSwAddPath(qualifiedPath, ".glsl"); pezSwAddDirective("*", "#version 420"); // Perform user-specified intialization pezPrintString("OpenGL Version: %s\n", glGetString(GL_VERSION)); PezInitialize(); bstring windowTitle = bmidstr(name, 5, blength(name) - 7); XStoreName(context.MainDisplay, context.MainWindow, bdata(windowTitle)); bdestroy(windowTitle); bdestroy(name); // ------------------- // Start the Game Loop // ------------------- unsigned int previousTime = GetMicroseconds(); int done = 0; while (!done) { if (glGetError() != GL_NO_ERROR) pezFatal("OpenGL error.\n"); if (XPending(context.MainDisplay)) { XEvent event; XNextEvent(context.MainDisplay, &event); switch (event.type) { case Expose: //redraw(display, event.xany.window); break; case ConfigureNotify: //resize(event.xconfigure.width, event.xconfigure.height); break; #ifdef PEZ_MOUSE_HANDLER case ButtonPress: PezHandleMouse(event.xbutton.x, event.xbutton.y, PEZ_DOWN); break; case ButtonRelease: PezHandleMouse(event.xbutton.x, event.xbutton.y, PEZ_UP); break; case MotionNotify: PezHandleMouse(event.xmotion.x, event.xmotion.y, PEZ_MOVE); break; #endif case KeyRelease: case KeyPress: { XComposeStatus composeStatus; char asciiCode[32]; KeySym keySym; int len; len = XLookupString(&event.xkey, asciiCode, sizeof(asciiCode), &keySym, &composeStatus); switch (asciiCode[0]) { case 'x': case 'X': case 'q': case 'Q': case 0x1b: done = 1; break; } } } } unsigned int currentTime = GetMicroseconds(); unsigned int deltaTime = currentTime - previousTime; previousTime = currentTime; PezUpdate((float) deltaTime / 1000000.0f); PezRender(0); glXSwapBuffers(context.MainDisplay, context.MainWindow); } pezSwShutdown(); return 0; }
static GrGLFuncPtr glx_get(void* ctx, const char name[]) { SkASSERT(nullptr == ctx); SkASSERT(glXGetCurrentContext()); return glXGetProcAddress(reinterpret_cast<const GLubyte*>(name)); }
RenderTargetImpl* createPlatformWindowRenderTarget(xen::ArenaLinear& arena, xen::Window* window){ xen::MemoryTransaction transaction(arena); // taken from: http://apoorvaj.io/creating-a-modern-opengl-context.html RenderTargetImpl* result = xen::reserveType<RenderTargetImpl>(arena); result->drawable = window->xwindow; result->window = window; int gl_attribs[] = { // Ensure we render using RGBA color space rather than palette GLX_RENDER_TYPE, GLX_RGBA_BIT, // Ensure we can use the context to draw to an x window GLX_X_RENDERABLE, True, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, // Enable double buffering GLX_DOUBLEBUFFER, true, // These are minimum values for depth of various buffers GL will pick // the max available -> so we just set to 1 to make sure that we don't // get a context without a buffer for any of these GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_ACCUM_RED_SIZE, 1, GLX_ACCUM_GREEN_SIZE, 1, GLX_ACCUM_BLUE_SIZE, 1, GLX_DEPTH_SIZE, 1, None }; ///////////////////////////////////////////////////////////////////// // Get list of supported frame buffer configurations int fb_config_count = 0; GLXFBConfig* fb_configs = glXChooseFBConfig(window->xdisplay, DefaultScreen(window->xdisplay), gl_attribs, &fb_config_count ); if (!fb_config_count) { XenLogFatal("Failed to get framebuffer config list"); } else { XenLogInfo("Found %i valid framebuffer configurations", fb_config_count); } ///////////////////////////////////////////////////////////////////// // Create an old GL context so we can get function pointer to // glXCreateContextAttribsARBProc XVisualInfo* visual_info = glXGetVisualFromFBConfig(window->xdisplay, fb_configs[0] ); GLXContext ctx_old = glXCreateContext(window->xdisplay, visual_info, 0, GL_TRUE ); glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0; glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB"); ///////////////////////////////////////////////////////////////////// // Destroy the old context glXMakeCurrent(window->xdisplay, 0, 0); glXDestroyContext(window->xdisplay, ctx_old); if (!glXCreateContextAttribsARB) { XenLogError("glXCreateContextAttribsARB() not found"); XenBreak(); } ///////////////////////////////////////////////////////////////////// // Set GL Context settings int context_attribs[] = { // Minimum GL Version GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 2, None }; ///////////////////////////////////////////////////////////////////// // Create the GL Context result->gl_context = glXCreateContextAttribsARB(window->xdisplay, fb_configs[0], NULL, true, context_attribs ); transaction.commit(); return result; }