/*!**************************************************************************** @Function InitView @Return bool true if no error occurred @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependent on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLESAntialiasedLines::InitView() { bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); m_iWidth = PVRShellGet(prefWidth); m_iHeight = PVRShellGet(prefHeight); glClearColor(0.6f, 0.8f, 1.0f, 1.0f); // Initialise Print3D if(m_Print3D.SetTextures(0, m_iWidth, m_iHeight, bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D.\n"); return false; } // Initialise the texture if (PVRTTextureLoadFromPVR("LineRound.pvr", &m_uiTexture) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Failed to load texture.\n"); return false; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Initialise geometry SVertex *paVertices = new SVertex[c_iNumLines * 2]; // 2 vertices per GL_LINE STexVertex *paTexVertices = new STexVertex[c_iNumLines * 8]; // 8 vertices per AA line (includes caps) GLushort *paui16Indices = new GLushort[c_iNumLines * 18]; // 18 indices per AA line (6 triangles) if(!paVertices || !paTexVertices || !paui16Indices) { delete[] paVertices; delete[] paTexVertices; delete[] paui16Indices; PVRShellSet(prefExitMessage, "ERROR: Failed to allocate line vertices and indices.\n"); return false; } srand(0); float fAngleStep = PVRT_TWO_PI / c_iNumLines; float fSize = PVRT_MIN(m_iWidth, m_iHeight) * 0.4f; for (int i = 0; i < c_iNumLines; ++i) { // Place the line vertices on a circle paVertices[i*2].vPosition.x = fSize * PVRTSIN(fAngleStep * (i + c_fLineArc)); paVertices[i*2].vPosition.y = fSize * PVRTCOS(fAngleStep * (i + c_fLineArc)); paVertices[i*2+1].vPosition.x = fSize * PVRTSIN(fAngleStep * i); paVertices[i*2+1].vPosition.y = fSize * PVRTCOS(fAngleStep * i); // Pick a random RGB color paVertices[i*2].uiColor = (0xFF << 24) + ((rand() & 0xFF) << 16) + ((rand() & 0xFF) << 8) + (rand() & 0xFF); paVertices[i*2+1].uiColor = paVertices[i*2].uiColor; // Tessellate the antialiased line TessellateLine(paVertices[i*2].vPosition, paVertices[i*2+1].vPosition, c_fLineWidth, paVertices[i*2].uiColor, &paTexVertices[i * 8], i * 8, &paui16Indices[i * 18]); } // We use 3 VBOs for clarity: // 0: AA line vertex data // 1: AA line index data // 2: GL_LINES vertex data glGenBuffers(3, m_uiVbos); // Bind the VBOs and fill them with data glBindBuffer(GL_ARRAY_BUFFER, m_uiVbos[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(*paTexVertices) * c_iNumLines * 8, paTexVertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_uiVbos[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(*paui16Indices) * c_iNumLines * 18, paui16Indices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, m_uiVbos[2]); glBufferData(GL_ARRAY_BUFFER, sizeof(*paVertices) * c_iNumLines * 2, paVertices, GL_STATIC_DRAW); // Unbind buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // Set projection to use pixel coordinates glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0, (float)PVRShellGet(prefWidth), (float)PVRShellGet(prefHeight), 0, 0, 1); delete[] paVertices; delete[] paTexVertices; delete[] paui16Indices; // Setup our render states glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE); return true; }
int main(int argc, char *argv[]) { SDL_Window *window; /* main window */ SDL_GLContext context; //int w, h; Uint32 startFrame; /* time frame began to process */ Uint32 endFrame; /* time frame ended processing */ Uint32 delay; /* time to pause waiting to draw next frame */ int done; /* should we clean up and exit? */ /* initialize SDL */ if (SDL_Init(SDL_INIT_VIDEO) < 0) { fatalError("Could not initialize SDL"); } /* seed the random number generator */ srand(time(NULL)); /* request some OpenGL parameters that may speed drawing */ SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 0); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); /* create main window and renderer */ window = SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS); context = SDL_GL_CreateContext(window); /* load the particle texture */ initializeTexture(); /* check if GL_POINT_SIZE_ARRAY_OES is supported this is used to give each particle its own size */ pointSizeExtensionSupported = SDL_GL_ExtensionSupported("GL_OES_point_size_array"); /* set up some OpenGL state */ glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); SDL_GetWindowSize(window, &screen_w, &screen_h); glViewport(0, 0, screen_w, screen_h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof((GLfloat) 0, (GLfloat) screen_w, (GLfloat) screen_h, (GLfloat) 0, 0.0, 1.0); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnable(GL_POINT_SPRITE_OES); glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, 1); if (pointSizeExtensionSupported) { /* we use this to set the sizes of all the particles */ glEnableClientState(GL_POINT_SIZE_ARRAY_OES); } else { /* if extension not available then all particles have size 10 */ glPointSize(10); } done = 0; /* enter main loop */ while (!done) { startFrame = SDL_GetTicks(); SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { done = 1; } if (event.type == SDL_MOUSEBUTTONDOWN) { int x, y; SDL_GetMouseState(&x, &y); spawnEmitterParticle(x, y); } } stepParticles(); drawParticles(); SDL_GL_SwapWindow(window); endFrame = SDL_GetTicks(); /* figure out how much time we have left, and then sleep */ delay = MILLESECONDS_PER_FRAME - (endFrame - startFrame); if (delay > MILLESECONDS_PER_FRAME) { delay = MILLESECONDS_PER_FRAME; } if (delay > 0) { SDL_Delay(delay); } } /* delete textures */ glDeleteTextures(1, &particleTextureID); /* shutdown SDL */ SDL_Quit(); return 0; }
void Target_draw() { GLshort vertices[12]; unsigned int touchIndex; if (darkClearColor) { glClearColor(0.0f, 0.25f, 0.5f, 0.0f); } else { glClearColor(0.25f, 0.5f, 0.75f, 0.0f); } glClear(GL_COLOR_BUFFER_BIT); if (EAGLShell_getOpenGLAPIVersion() == EAGLShellOpenGLVersion_ES1) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0, viewportWidth, viewportHeight, 0, -1, 1); glMatrixMode(GL_MODELVIEW); if (lastAccelerometerReading.x != 0.0) { vertices[0] = viewportWidth / 3 - 5; vertices[1] = viewportHeight / 2; vertices[2] = viewportWidth / 3 + 5; vertices[3] = viewportHeight / 2; vertices[4] = viewportWidth / 3 + 5; vertices[5] = viewportHeight / 2 + lastAccelerometerReading.x * viewportHeight / 6; vertices[6] = viewportWidth / 3 - 5; vertices[7] = viewportHeight / 2 + lastAccelerometerReading.x * viewportHeight / 6; glVertexPointer(2, GL_SHORT, 0, vertices); glColor4ub(0xFF, 0x00, 0x00, 0xFF); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } if (lastAccelerometerReading.y != 0.0) { vertices[0] = viewportWidth / 2 - 5; vertices[1] = viewportHeight / 2; vertices[2] = viewportWidth / 2 + 5; vertices[3] = viewportHeight / 2; vertices[4] = viewportWidth / 2 + 5; vertices[5] = viewportHeight / 2 + lastAccelerometerReading.y * viewportHeight / 6; vertices[6] = viewportWidth / 2 - 5; vertices[7] = viewportHeight / 2 + lastAccelerometerReading.y * viewportHeight / 6; glVertexPointer(2, GL_SHORT, 0, vertices); glColor4ub(0x00, 0xFF, 0x00, 0xFF); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } if (lastAccelerometerReading.z != 0.0) { vertices[0] = viewportWidth - viewportWidth / 3 - 5; vertices[1] = viewportHeight / 2; vertices[2] = viewportWidth - viewportWidth / 3 + 5; vertices[3] = viewportHeight / 2; vertices[4] = viewportWidth - viewportWidth / 3 + 5; vertices[5] = viewportHeight / 2 + lastAccelerometerReading.z * viewportHeight / 6; vertices[6] = viewportWidth - viewportWidth / 3 - 5; vertices[7] = viewportHeight / 2 + lastAccelerometerReading.z * viewportHeight / 6; glVertexPointer(2, GL_SHORT, 0, vertices); glColor4ub(0x00, 0x00, 0xFF, 0xFF); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } vertices[0] = 0; vertices[1] = 0; vertices[2] = 16; vertices[3] = 0; vertices[4] = 0; vertices[5] = 16; vertices[6] = viewportWidth; vertices[7] = viewportHeight; vertices[8] = viewportWidth - 16; vertices[9] = viewportHeight; vertices[10] = viewportWidth; vertices[11] = viewportHeight - 16; glVertexPointer(2, GL_SHORT, 0, vertices); glColor4ub(0xFF, 0xFF, 0xFF, 0xFF); glDrawArrays(GL_TRIANGLES, 0, 6); for (touchIndex = 0; touchIndex < 32; touchIndex++) { if (touches[touchIndex].active) { vertices[0] = touches[touchIndex].x - 24; vertices[1] = touches[touchIndex].y - 24; vertices[2] = touches[touchIndex].x - 24; vertices[3] = touches[touchIndex].y + 24; vertices[4] = touches[touchIndex].x + 24; vertices[5] = touches[touchIndex].y + 24; vertices[6] = touches[touchIndex].x + 24; vertices[7] = touches[touchIndex].y - 24; glVertexPointer(2, GL_SHORT, 0, vertices); glColor4ub(0x7F, 0xFF, 0x7F, 0xFF); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } } } else { GLfloat projectionMatrix[16] = { 2.0f / viewportWidth, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f / viewportHeight, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f }; GLfloat modelviewMatrix[16] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; glUseProgram(shaderProgram); glUniformMatrix4fv(projectionMatrixUniform, 1, GL_FALSE, projectionMatrix); glUniformMatrix4fv(modelviewMatrixUniform, 1, GL_FALSE, modelviewMatrix); if (lastAccelerometerReading.x != 0.0) { vertices[0] = viewportWidth / 3 - 5; vertices[1] = viewportHeight / 2; vertices[2] = viewportWidth / 3 + 5; vertices[3] = viewportHeight / 2; vertices[4] = viewportWidth / 3 + 5; vertices[5] = viewportHeight / 2 + lastAccelerometerReading.x * viewportHeight / 6; vertices[6] = viewportWidth / 3 - 5; vertices[7] = viewportHeight / 2 + lastAccelerometerReading.x * viewportHeight / 6; glVertexAttribPointer(VERTEX_ATTRIB_INDEX, 2, GL_SHORT, GL_FALSE, 0, vertices); glUniform4f(constantColorUniform, 1.0f, 0.0f, 0.0f, 1.0f); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } if (lastAccelerometerReading.y != 0.0) { vertices[0] = viewportWidth / 2 - 5; vertices[1] = viewportHeight / 2; vertices[2] = viewportWidth / 2 + 5; vertices[3] = viewportHeight / 2; vertices[4] = viewportWidth / 2 + 5; vertices[5] = viewportHeight / 2 + lastAccelerometerReading.y * viewportHeight / 6; vertices[6] = viewportWidth / 2 - 5; vertices[7] = viewportHeight / 2 + lastAccelerometerReading.y * viewportHeight / 6; glVertexAttribPointer(VERTEX_ATTRIB_INDEX, 2, GL_SHORT, GL_FALSE, 0, vertices); glUniform4f(constantColorUniform, 0.0f, 1.0f, 0.0f, 1.0f); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } if (lastAccelerometerReading.z != 0.0) { vertices[0] = viewportWidth - viewportWidth / 3 - 5; vertices[1] = viewportHeight / 2; vertices[2] = viewportWidth - viewportWidth / 3 + 5; vertices[3] = viewportHeight / 2; vertices[4] = viewportWidth - viewportWidth / 3 + 5; vertices[5] = viewportHeight / 2 + lastAccelerometerReading.z * viewportHeight / 6; vertices[6] = viewportWidth - viewportWidth / 3 - 5; vertices[7] = viewportHeight / 2 + lastAccelerometerReading.z * viewportHeight / 6; glVertexAttribPointer(VERTEX_ATTRIB_INDEX, 2, GL_SHORT, GL_FALSE, 0, vertices); glUniform4f(constantColorUniform, 0.0f, 0.0f, 1.0f, 1.0f); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } vertices[0] = 0; vertices[1] = 0; vertices[2] = 16; vertices[3] = 0; vertices[4] = 0; vertices[5] = 16; vertices[6] = viewportWidth; vertices[7] = viewportHeight; vertices[8] = viewportWidth - 16; vertices[9] = viewportHeight; vertices[10] = viewportWidth; vertices[11] = viewportHeight - 16; glVertexAttribPointer(VERTEX_ATTRIB_INDEX, 2, GL_SHORT, GL_FALSE, 0, vertices); glUniform4f(constantColorUniform, 1.0f, 1.0f, 1.0f, 1.0f); glDrawArrays(GL_TRIANGLES, 0, 6); for (touchIndex = 0; touchIndex < 32; touchIndex++) { if (touches[touchIndex].active) { vertices[0] = touches[touchIndex].x - 24; vertices[1] = touches[touchIndex].y - 24; vertices[2] = touches[touchIndex].x - 24; vertices[3] = touches[touchIndex].y + 24; vertices[4] = touches[touchIndex].x + 24; vertices[5] = touches[touchIndex].y + 24; vertices[6] = touches[touchIndex].x + 24; vertices[7] = touches[touchIndex].y - 24; glVertexAttribPointer(VERTEX_ATTRIB_INDEX, 2, GL_SHORT, GL_FALSE, 0, vertices); glUniform4f(constantColorUniform, 0.5f, 1.0f, 0.5f, 1.0f); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } } } if (postRedisplayAtEndOfTarget_draw) { darkClearColor = !darkClearColor; Shell_redisplay(); } }
JNIEXPORT void JNICALL JNIFUNCTION_NATIVE(nativeDrawFrame(JNIEnv* env, jobject obj)) { float width, height; if (!videoInited) { #ifdef DEBUG LOGI("nativeDrawFrame !VIDEO\n"); #endif return; // No point in trying to draw until video is inited. } #ifdef DEBUG LOGI("nativeDrawFrame\n"); #endif if (!gARViewInited) { if (!initARView()) return; } if (gARViewLayoutRequired) layoutARView(); // Upload new video frame if required. if (videoFrameNeedsPixelBufferDataUpload) { arglPixelBufferDataUploadBiPlanar(gArglSettings, gVideoFrame, gVideoFrame + videoWidth*videoHeight); videoFrameNeedsPixelBufferDataUpload = false; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the buffers for new frame. // Display the current frame arglDispImage(gArglSettings); // Set up 3D mode. glMatrixMode(GL_PROJECTION); glLoadMatrixf(cameraLens); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glStateCacheEnableDepthTest(); // Set any initial per-frame GL state you require here. // ---> // Lighting and geometry that moves with the camera should be added here. // (I.e. should be specified before camera pose transform.) // ---> VirtualEnvironmentHandleARViewDrawPreCamera(); if (cameraPoseValid) { glMultMatrixf(cameraPose); // All lighting and geometry to be drawn in world coordinates goes here. // ---> VirtualEnvironmentHandleARViewDrawPostCamera(); } // If you added external OpenGL code above, and that code doesn't use the glStateCache routines, // then uncomment the line below. //glStateCacheFlush(); // Set up 2D mode. glMatrixMode(GL_PROJECTION); glLoadIdentity(); width = (float)viewPort[viewPortIndexWidth]; height = (float)viewPort[viewPortIndexHeight]; glOrthof(0.0f, width, 0.0f, height, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glStateCacheDisableDepthTest(); // Add your own 2D overlays here. // ---> VirtualEnvironmentHandleARViewDrawOverlay(); // If you added external OpenGL code above, and that code doesn't use the glStateCache routines, // then uncomment the line below. //glStateCacheFlush(); #ifdef DEBUG // Example of 2D drawing. It just draws a white border line. Change the 0 to 1 to enable. const GLfloat square_vertices [4][2] = { {0.5f, 0.5f}, {0.5f, height - 0.5f}, {width - 0.5f, height - 0.5f}, {width - 0.5f, 0.5f} }; glStateCacheDisableLighting(); glStateCacheDisableTex2D(); glVertexPointer(2, GL_FLOAT, 0, square_vertices); glStateCacheEnableClientStateVertexArray(); glColor4ub(255, 255, 255, 255); glDrawArrays(GL_LINE_LOOP, 0, 4); #endif }
void glOrthofOES(GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat near, GLfloat far) { glOrthof(left, right, bottom, top, near, far); }
/** ** Initialize OpenGL */ static void InitOpenGL() { InitOpenGLExtensions(); glViewport(0, 0, (GLsizei)Video.ViewportWidth, (GLsizei)Video.ViewportHeight); #ifdef USE_OPENGL glMatrixMode(GL_PROJECTION); glLoadIdentity(); #endif #ifdef USE_GLES glOrthof(0.0f, (GLfloat)Video.Width, (GLfloat)Video.Height, 0.0f, -1.0f, 1.0f); #endif #ifdef USE_OPENGL if (!GLShaderPipelineSupported) { glOrtho(0, Video.Width, Video.Height, 0, -1, 1); } else { glOrtho(0, Video.ViewportWidth, Video.ViewportHeight, 0, -1, 1); } #endif glMatrixMode(GL_MODELVIEW); glLoadIdentity(); #ifdef USE_OPENGL glTranslatef(0.375, 0.375, 0.); #endif glClearColor(0.0f, 0.0f, 0.0f, 0.0f); #ifdef USE_GLES glClearDepthf(1.0f); #endif #ifdef USE_OPENGL glClearDepth(1.0f); if (GLShaderPipelineSupported) { SetupFramebuffer(); } #endif glShadeModel(GL_FLAT); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glGetIntegerv(GL_MAX_TEXTURE_SIZE, &GLMaxTextureSize); if (GLMaxTextureSize == 0) { // FIXME: try to use GL_PROXY_TEXTURE_2D to get a valid size #if 0 glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glGetTexLevelParameterfv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &internalFormat); #endif fprintf(stderr, "GL_MAX_TEXTURE_SIZE is 0, using 256 by default\n"); GLMaxTextureSize = 256; } if (GLMaxTextureSize > GLMaxTextureSizeOverride && GLMaxTextureSizeOverride > 0) { GLMaxTextureSize = GLMaxTextureSizeOverride; } }
int initEGL(int n_buf) { #ifdef GLES_20 EGLint context_attr[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; #else typedef NativeDisplayType EGLNativeDisplayType; typedef NativeWindowType EGLNativeWindowType; #endif EGLint disp_w, disp_h; EGLNativeDisplayType disp_type; EGLNativeWindowType window; EGLConfig cfgs[2]; EGLint n_cfgs; EGLint egl_attr[] = { EGL_BUFFER_SIZE, EGL_DONT_CARE, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 8, #ifdef GLES_20 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, #endif EGL_NONE }; #ifdef X11 if (initX11(&disp_w, &disp_h)) return -1; disp_type = (EGLNativeDisplayType)x11Display; window = (EGLNativeWindowType)x11Window; #else if (get_disp_resolution(&disp_w, &disp_h)) { printf("ERROR: get display resolution failed\n"); return -1; } printf("\n\nliuxu, 04/21/2014, get_disp_resolution, disp_w=%d, disp_h=%d\n\n", disp_w, disp_h); disp_type = (EGLNativeDisplayType)EGL_DEFAULT_DISPLAY; window = 0; #endif dpy = eglGetDisplay(disp_type); if (eglInitialize(dpy, NULL, NULL) != EGL_TRUE) { print_err("eglInitialize"); return -1; } if (eglGetConfigs(dpy, cfgs, 2, &n_cfgs) != EGL_TRUE) { print_err("eglGetConfigs"); goto cleanup; } if (eglChooseConfig(dpy, egl_attr, cfgs, 2, &n_cfgs) != EGL_TRUE) { print_err("eglChooseConfig"); goto cleanup; } surface = eglCreateWindowSurface(dpy, cfgs[0], window, NULL); if (surface == EGL_NO_SURFACE) { print_err("eglCreateWindowSurface"); goto cleanup; } #ifdef GLES_20 context = eglCreateContext(dpy, cfgs[0], EGL_NO_CONTEXT, context_attr); #else context = eglCreateContext(dpy, cfgs[0], EGL_NO_CONTEXT, NULL); #endif if (context == EGL_NO_CONTEXT) { print_err("eglCreateContext"); goto cleanup; } if (eglMakeCurrent(dpy, surface, surface, context) != EGL_TRUE) { print_err("eglMakeCurrent"); goto cleanup; } /* 0 - do not sync with video frame */ if (profiling == TRUE) { if (eglSwapInterval(dpy, 0) != EGL_TRUE) { print_err("eglSwapInterval"); goto cleanup; } } #ifndef GLES_20 glShadeModel(GL_FLAT); glTexParameterf(GL_TEXTURE_STREAM_IMG, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_STREAM_IMG, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFrontFace(GL_CW); glCullFace(GL_FRONT); glEnable(GL_CULL_FACE); glEnable(GL_NORMALIZE); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(-CUBE_V_LEN * disp_w / disp_h, CUBE_V_LEN * disp_w / disp_h, -CUBE_V_LEN, CUBE_V_LEN, -CUBE_V_LEN * 2, CUBE_V_LEN * 2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); #endif return 0; cleanup: deInitEGL(n_buf); #ifdef X11 deInitX11(); #endif return -1; }
void lzs_renderer_draw(lzs_renderer_t* self) { assert(self); LOGD("debug"); double t0 = a3d_utime(); // stretch screen to 800x480 glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0.0f, SCREEN_W, SCREEN_H, 0.0f, 0.0f, 2.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // draw camera glEnable(GL_TEXTURE_EXTERNAL_OES); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindTexture(GL_TEXTURE_EXTERNAL_OES, self->texid); glVertexPointer(3, GL_FLOAT, 0, VERTEX); glTexCoordPointer(2, GL_FLOAT, 0, COORDS); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_EXTERNAL_OES); utime_update("setup", &t0); // capture buffers GLint format = TEXGZ_BGRA; GLint type = GL_UNSIGNED_BYTE; glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES, &format); glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE_OES, &type); if((format == TEXGZ_BGRA) && (type == GL_UNSIGNED_BYTE)) { LOGD("readpixels format=0x%X, type=0x%X", format, type); // TODO - check for texgz errors // process buffers texgz_tex_t* bc = self->buffer_color; texgz_tex_t* bg = self->buffer_gray; texgz_tex_t* bsx = self->buffer_sx; texgz_tex_t* bsy = self->buffer_sy; glReadPixels(self->sphero_x - RADIUS_BALL, (SCREEN_H - self->sphero_y - 1) - RADIUS_BALL, bc->width, bc->height, bc->format, bc->type, (void*) bc->pixels); #ifdef DEBUG_BUFFERS texgz_tex_export(bc, "/sdcard/laser-shark/color.texgz"); #endif utime_update("readpixels", &t0); texgz_tex_computegray(bc, bg); utime_update("computegray", &t0); texgz_tex_computeedges3x3(bg, bsx, bsy); utime_update("computeedges", &t0); // compute peak { int x; int y; int peak_x = 0; int peak_y = 0; float peak = 0.0f; float* gpixels = (float*) bg->pixels; float* xpixels = (float*) bsx->pixels; float* ypixels = (float*) bsy->pixels; for(x = 0; x < bg->width; ++x) { for(y = 0; y < bg->height; ++y) { int idx = bg->width*y + x; // compute magnitude squared float magsq = xpixels[idx]*xpixels[idx] + ypixels[idx]*ypixels[idx]; gpixels[idx] = magsq; if(magsq > peak) { peak_x = x; peak_y = y; peak = magsq; } } } LOGD("peak=%f, peak_x=%i, peak_y=%i", peak, peak_x, peak_y); utime_update("computepeak", &t0); #ifdef DEBUG_BUFFERS texgz_tex_export(bg, "/sdcard/laser-shark/peak.texgz"); #endif // move sphero center to match peak self->sphero_x += (float) peak_x - (float) bg->width / 2.0f; self->sphero_y -= (float) peak_y - (float) bg->height / 2.0f; } } else { LOGE("unsupported format=0x%X, type=0x%X", format, type); } // compute phone X, Y center compute_position(self, SCREEN_CX, SCREEN_CY, &self->phone_X, &self->phone_Y); // compute sphero X, Y compute_position(self, self->sphero_x, self->sphero_y, &self->sphero_X, &self->sphero_Y); utime_update("computeposition", &t0); // compute goal float dx = self->phone_X - self->sphero_X; float dy = self->phone_Y - self->sphero_Y; float a = fix_angle(atan2f(dx, dy) * 180.0f / M_PI); self->sphero_goal = a - self->sphero_heading_offset; // compute speed float dotp = cosf((a - self->sphero_heading) * M_PI / 180.0f); if(dotp > 0.0f) { // linearly interpolate speed based on the turning angle self->sphero_speed = SPEED_MAX*dotp + SPEED_MIN*(1.0f - dotp); } else { // go slow to turn around self->sphero_speed = SPEED_MIN; } // draw camera cross-hair { float x = SCREEN_CX; float y = SCREEN_CY; float r = RADIUS_CROSS; limit_position(r, &x, &y); lzs_renderer_crosshair(y - r, x - r, y + r, x + r, 1.0f, 0.0f, 0.0f); } // draw sphero search box { float r = RADIUS_BALL; limit_position(r, &self->sphero_x, &self->sphero_y); float x = self->sphero_x; float y = self->sphero_y; lzs_renderer_drawbox(y - r, x - r, y + r, x + r, 0.0f, 1.0f, 0.0f, 0); } lzs_renderer_step(self); // draw string a3d_texstring_printf(self->string_sphero, "sphero: head=%i, x=%0.1f, y=%0.1f, spd=%0.2f, goal=%i", (int) fix_angle(self->sphero_heading + self->sphero_heading_offset), self->sphero_X, self->sphero_Y, self->sphero_speed, (int) fix_angle(self->sphero_goal)); a3d_texstring_printf(self->string_phone, "phone: heading=%i, slope=%i, x=%0.1f, y=%0.1f", (int) fix_angle(self->phone_heading), (int) fix_angle(self->phone_slope), self->phone_X, self->phone_Y); a3d_texstring_draw(self->string_sphero, 400.0f, 16.0f, 800, 480); a3d_texstring_draw(self->string_phone, 400.0f, 16.0f + self->string_sphero->size, 800, 480); a3d_texstring_draw(self->string_fps, (float) SCREEN_W - 16.0f, (float) SCREEN_H - 16.0f, SCREEN_W, SCREEN_H); utime_update("draw", &t0); //texgz_tex_t* screen = texgz_tex_new(SCREEN_W, SCREEN_H, SCREEN_W, SCREEN_H, TEXGZ_UNSIGNED_BYTE, TEXGZ_BGRA, NULL); //glReadPixels(0, 0, screen->width, screen->height, screen->format, screen->type, (void*) screen->pixels); //texgz_tex_export(screen, "/sdcard/laser-shark/screen.texgz"); //texgz_tex_delete(&screen); A3D_GL_GETERROR(); }
void GL11Renderer::Initialize( int width, int height ) { // // Buffer Setup... // // Create the depth buffer. glGenRenderbuffersOES( 1, &m_depthRenderbuffer ); glBindRenderbufferOES( GL_RENDERBUFFER_OES, m_depthRenderbuffer ); glRenderbufferStorageOES( GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height ); // Create the framebuffer object; attach the depth and color buffers. glGenFramebuffersOES( 1, &m_framebuffer ); glBindFramebufferOES( GL_FRAMEBUFFER_OES, m_framebuffer ); glFramebufferRenderbufferOES( GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, m_colorRenderbuffer ); glFramebufferRenderbufferOES( GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, m_depthRenderbuffer ); // Bind the color buffer for rendering. glBindRenderbufferOES( GL_RENDERBUFFER_OES, m_colorRenderbuffer ); // // General Setup... // glEnable( GL_TEXTURE_2D ); glDisable( GL_LIGHTING ); // // Point Sprites... // glEnable( GL_POINT_SPRITE_OES ); glTexEnvi( GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE ); glTexEnvi( GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_FALSE ); //glPointSize( 10.0f ); // This helps as a work around for order-dependency artifacts that can occur when sprites overlap. glBlendFunc( GL_SRC_ALPHA, GL_ONE ); // // Texture Setup... // glGenTextures( 1, &m_snowTextureId ); glBindTexture( GL_TEXTURE_2D, m_snowTextureId ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); TextureDescription desc = m_resourceLoader->LoadPngImage( "snow.png" ); GLvoid* pixels = m_resourceLoader->GetImageData(); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, desc.Width, desc.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels ); m_resourceLoader->UnloadImage(); // // VBO Setup for Snow Flakes... // for( int i = 0; i < MaxSnowFlakes; ++i ) { m_pos[i][0] = RandomFloat( -ViewMaxX, ViewMaxX ); m_pos[i][1] = RandomFloat( -ViewMaxY, ViewMaxY ); m_vel[i][0] = RandomFloat( -0.004f, 0.004f ); // Flakes move side to side m_vel[i][1] = RandomFloat( -0.01f, -0.008f ); // Flakes fall down m_col[i][0] = 1.0f; m_col[i][1] = 1.0f; m_col[i][2] = 1.0f; m_col[i][3] = 1.0f; //RandomFloat( 0.6f, 1.0f ); // It seems that Doodle Jump snow does not use alpha. m_size[i] = RandomFloat( 3.0, 6.0f ); // It looks strange if the flakes all turn at the same time, so // lets vary their turn times with a random negative value. m_timeSinceLastTurn[i] = RandomFloat( -5.0, 0.0f ); } // VBO for vertex positions. glGenBuffers( 1, &m_vertexBufferId ); glBindBuffer( GL_ARRAY_BUFFER, m_vertexBufferId ); glBufferData( GL_ARRAY_BUFFER, sizeof(m_pos), m_pos, GL_DYNAMIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); // TODO: Due to the possibility of cache misses, it might be a little faster to // combine the colors and point sizes into an interleaved array, but it // seems that this optimization makes less sense on newer CPUs. // VBO for vertex colors. glGenBuffers( 1, &m_colorBufferId ); glBindBuffer( GL_ARRAY_BUFFER, m_colorBufferId ); glBufferData( GL_ARRAY_BUFFER, sizeof(m_col), m_col, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); // VBO for point sizes of point sprites. glGenBuffers( 1, &m_pointSizeBufferId ); glBindBuffer( GL_ARRAY_BUFFER, m_pointSizeBufferId ); glBufferData( GL_ARRAY_BUFFER, sizeof(m_size), m_size, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); // // View Settings... // glViewport( 0, 0, width, height ); // Initialize the projection matrix to orthogrpahic and create // a flat 2D game space that is 2 units wide and 3 units high. glMatrixMode( GL_PROJECTION ); glOrthof( -ViewMaxX, +ViewMaxX, -ViewMaxY, +ViewMaxY, -1, 1 ); }
/* basically, draw a textured rectangle in orthogonal mode */ void draw_textbox(TextBox *box) { GLfloat vertex_arr[8] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f }; GLfloat tex_arr[8] = { 0, 0, 0, 1, 1, 0, 1, 1, }; if (box->str == NULL) return; vertex_arr[3] = vertex_arr[7] = box->h; vertex_arr[4] = vertex_arr[6] = box->w; glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); #ifdef OPENGLES glOrthof(0, screen_width, screen_height, 0, -1, 10); #else glOrtho(0, screen_width, screen_height, 0, -1, 10); #endif glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(box->x, box->y, 0.0f); glColor4f(1, 1, 1, 1); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, box->tex_id); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(2, GL_FLOAT, 0, vertex_arr); glTexCoordPointer(2, GL_FLOAT, 0, tex_arr); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); /* draw fake reflection While this seemed like a nice idea, it looks annoying glColor4f(0.4f, 0.4f, 0.4f, 1); glVertexPointer(2, GL_FLOAT, 0, vertex_arr); glTexCoordPointer(2, GL_FLOAT, 0, tex_reflect); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); */ glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glDisable(GL_BLEND); }
int main(int argc, char *argv[]) { int rc; // Renderer variables mmr_connection_t* mmr_connection = 0; mmr_context_t* mmr_context = 0; strm_dict_t* dict = NULL; // I/O variables int video_device_output_id = -1; int audio_device_output_id = -1; // Position of the play and stop button. static int ctrl_x = 0; static int ctrl_y = 0; EGLint surface_width; EGLint surface_height; srand(time(0)); app_id = rand(); // I/O devices static char *audio_device_url = "audio:default"; static char video_device_url[PATH_MAX]; rc = snprintf(video_device_url, PATH_MAX, "screen:?winid=videosamplewindowgroup_%d&wingrp=videosamplewindowgroup_%d", app_id, app_id); if (rc >= PATH_MAX) { fprintf(stderr, "URL too long\n"); } // Name of video context...with a random number appended. static char video_context_name[PATH_MAX]; rc = snprintf(video_context_name, PATH_MAX, "samplevideocontextname_%d", app_id); if (rc >= PATH_MAX) { fprintf(stderr, "Video context name too long\n"); } // Window group name...with the same random number appended. static char window_group_name[PATH_MAX]; rc = snprintf(window_group_name, PATH_MAX, "videosamplewindowgroup_%d", app_id); if (rc >= PATH_MAX) { fprintf(stderr, "Video context name too long\n"); } // Video file bundled with our app static const char *video_file_relative_path = "app/native/pb_sample.mp4"; bps_initialize(); // Create the Screen Context. if (screen_create_context(&g_screen_ctx, SCREEN_APPLICATION_CONTEXT) != 0) { fprintf(stderr, "screen_create_context failed\n"); return EXIT_FAILURE; } // Create the window and initialize EGL for GL_ES_1 rendering rc = initialize_egl_window(g_screen_ctx, window_group_name); if (rc != EXIT_SUCCESS) { fprintf(stderr, "initialize_egl_window failed\n"); return EXIT_FAILURE; } // Query width and height of the window surface created by utility code eglQuerySurface(g_egl_disp, g_egl_surf, EGL_WIDTH, &surface_width); eglQuerySurface(g_egl_disp, g_egl_surf, EGL_HEIGHT, &surface_height); EGLint err = eglGetError(); if (err != EGL_SUCCESS) { fprintf(stderr, "Unable to query EGL surface dimensions\n"); return EXIT_FAILURE; } // Initialize GL for 2D rendering glViewport(0, 0, (int)surface_width, (int) surface_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Set world coordinates to coincide with screen pixels glScalef(1.0f / (float)surface_width, 1.0f / (float)surface_height, 1.0f); // We can calculate location and verticies of the controls ctrl_x = (float)surface_width / 2 - ctrl_w / 2; ctrl_y = (float)surface_height / 2 - ctrl_h / 2; g_triangle_vertices[0] = ctrl_x; g_triangle_vertices[1] = ctrl_y; g_triangle_vertices[2] = ctrl_x; g_triangle_vertices[3] = ctrl_y + ctrl_h; g_triangle_vertices[4] = ctrl_x + ctrl_w; g_triangle_vertices[5] = ctrl_y + ctrl_h / 2; g_square_vertices[0] = ctrl_x; g_square_vertices[1] = ctrl_y; g_square_vertices[2] = ctrl_x; g_square_vertices[3] = ctrl_y + ctrl_h; g_square_vertices[4] = ctrl_x + ctrl_w; g_square_vertices[5] = ctrl_y + ctrl_h; g_square_vertices[6] = ctrl_x + ctrl_w; g_square_vertices[7] = ctrl_y; g_square_vertices[8] = ctrl_x; g_square_vertices[9] = ctrl_y; // Configure mm-renderer. mmr_connection = mmr_connect(NULL); if (mmr_connection == NULL) { fprintf(stderr, "mmr_connect failed\n"); return EXIT_FAILURE; } mmr_context = mmr_context_create(mmr_connection, video_context_name, 0, S_IRWXU|S_IRWXG|S_IRWXO); if (mmr_context == NULL) { fprintf(stderr, "mmr_context_create failed\n"); return EXIT_FAILURE; } // Configure video and audio output. video_device_output_id = mmr_output_attach(mmr_context, video_device_url, "video"); if (video_device_output_id == -1) { fprintf(stderr, "mmr_output_attach(video) failed\n"); return EXIT_FAILURE; } audio_device_output_id = mmr_output_attach(mmr_context, audio_device_url, "audio"); if (audio_device_output_id == -1) { fprintf(stderr, "mmr_output_attach(audio) failed\n"); return EXIT_FAILURE; } // render 'paused' render(true); // Build up the path where our bundled resource is. char cwd[PATH_MAX]; char media_file[PATH_MAX]; getcwd(cwd,PATH_MAX); rc = snprintf(media_file, PATH_MAX, "file://%s/%s", cwd, video_file_relative_path); if ((rc == -1) || (rc >= PATH_MAX)) { fprintf(stderr, "snprintf(media_file) failed\n"); return EXIT_FAILURE; } // Attach the input media. if (mmr_input_attach(mmr_context, media_file, "track") != 0) { fprintf(stderr, "mmr_input_attach(track) failed\n"); return EXIT_FAILURE; } int video_speed = 0; // Set the speed to 0 to pause the video initially if (mmr_speed_set(mmr_context, video_speed) != 0) { fprintf(stderr, "mmr_set_speed(0) failed\n"); return EXIT_FAILURE; } // Change to the play state, although speed is zero if (mmr_play(mmr_context) != 0) { fprintf(stderr, "mmr_play failed\n"); return EXIT_FAILURE; } /* Do some work to make the aspect ratio correct. */ dict = calculate_rect(surface_width, surface_height); if (NULL == dict) { fprintf(stderr, "calculate_rect failed\n"); return EXIT_FAILURE; } if (mmr_output_parameters(mmr_context, video_device_output_id, dict) != 0) { fprintf(stderr, "mmr_output_parameters failed\n"); return EXIT_FAILURE; } /* Note that we allocated memory for the dictionary, but the call to * mmr_output_parameters() deallocates that memory even on failure. */ dict = NULL; screen_request_events(g_screen_ctx); navigator_request_events(0); screen_window_t video_window = (screen_window_t)0; bool app_window_above = true; int screen_val; int exit_value = EXIT_SUCCESS; // Handle keyboard events and stop playback upon user request. for (;;) { bps_event_t *event = NULL; if (bps_get_event(&event, 0) != BPS_SUCCESS) { return EXIT_FAILURE; } if (event) { if (bps_event_get_domain(event) == navigator_get_domain()) { if (bps_event_get_code(event) == NAVIGATOR_EXIT) { break; } else if(NAVIGATOR_SWIPE_DOWN == bps_event_get_code(event)) { if ((screen_window_t)0 != video_window) { app_window_above = !app_window_above; if (app_window_above) { screen_val = 1; } else { screen_val = -1; } if (screen_set_window_property_iv(video_window, SCREEN_PROPERTY_ZORDER, &screen_val) != 0) { fprintf(stderr, "screen_set_window_property(ZORDER) failed\n"); exit_value = EXIT_FAILURE; break; } screen_val = 1; if (screen_set_window_property_iv(video_window, SCREEN_PROPERTY_VISIBLE, &screen_val) != 0) { fprintf(stderr, "screen_set_window_property(VISIBLE) failed\n"); exit_value = EXIT_FAILURE; break; } rc = screen_flush_context(g_screen_ctx, SCREEN_WAIT_IDLE); if (rc != 0) { fprintf (stderr, "Warning: Failed to flush\n"); } } } } else if (bps_event_get_domain(event) == screen_get_domain()) { screen_event_t screen_event = screen_event_get_event(event); int event_type; screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &event_type); if (event_type == SCREEN_EVENT_CREATE && (video_window == (screen_window_t)0)) { char id[256]; rc = screen_get_event_property_pv(screen_event, SCREEN_PROPERTY_WINDOW, (void**)&video_window); if (rc != 0) { fprintf(stderr, "screen_get_event_property(WINDOW) failed\n"); exit_value = EXIT_FAILURE; break; } fprintf(stderr, "video_window%d\n",(int)video_window); rc = screen_get_window_property_cv(video_window, SCREEN_PROPERTY_ID_STRING, 256, id); if (rc != 0) { fprintf(stderr, "screen_get_window_property(ID) failed\n"); exit_value = EXIT_FAILURE; break; } fprintf(stderr, "window ID is %s\n", id); if (strncmp(id, window_group_name, strlen(window_group_name)) != 0) { fprintf(stderr, "window ID mismatch\n"); exit_value = EXIT_FAILURE; break; } } else if(event_type == SCREEN_EVENT_MTOUCH_TOUCH) { if (video_speed == 0) { video_speed = 1000; render(false); } else { video_speed = 0; render(true); } if (mmr_speed_set(mmr_context, video_speed) != 0) { fprintf(stderr, "mmr_speed_set(%d) failed\n", video_speed); exit_value = EXIT_FAILURE; break; } } } } } screen_stop_events(g_screen_ctx); if (mmr_stop(mmr_context) != 0) { fprintf(stderr, "mmr_stop failed\n"); exit_value = EXIT_FAILURE; } if (mmr_output_detach(mmr_context, audio_device_output_id) != 0) { fprintf(stderr, "mmr_output_detach(audio) failed\n"); exit_value = EXIT_FAILURE; } if (mmr_output_detach(mmr_context, video_device_output_id) != 0) { fprintf(stderr, "mmr_output_detach(video) failed\n"); exit_value = EXIT_FAILURE; } if (mmr_context_destroy(mmr_context) != 0) { fprintf(stderr, "mmr_context_destroy failed\n"); exit_value = EXIT_FAILURE; } mmr_context = 0; video_device_output_id = -1; audio_device_output_id = -1; mmr_disconnect(mmr_connection); mmr_connection = 0; bps_shutdown(); if (screen_destroy_window(g_screen_win) != 0) { fprintf(stderr, "screen_destroy_window failed\n"); exit_value = EXIT_FAILURE; } if (screen_destroy_context(g_screen_ctx) != 0) { fprintf(stderr, "screen_destroy_context failed\n"); exit_value = EXIT_FAILURE; } g_screen_ctx = 0; g_screen_win = 0; return exit_value; }
int init_blocks() { EGLint surface_width, surface_height; //Initialize common vertex data vertices[0] = 0.0f; vertices[1] = 0.0f; vertices[2] = 1.0f; vertices[3] = 0.0f; vertices[4] = 0.0f; vertices[5] = 1.0f; vertices[6] = 1.0f; vertices[7] = 1.0f; //Initialize app data max_size = 60.0; //Query width and height of the window surface created by utility code eglQuerySurface(egl_disp, egl_surf, EGL_WIDTH, &surface_width); eglQuerySurface(egl_disp, egl_surf, EGL_HEIGHT, &surface_height); EGLint err = eglGetError(); if (err != 0x3000) { fprintf(stderr, "Unable to query egl surface dimensions\n"); return EXIT_FAILURE; } width = (float) surface_width; height = (float) surface_height; //Initialize GL for 2D rendering glViewport(0, 0, (int) width, (int) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0.0f, width / height, 0.0f, 1.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Set world coordinates to coincide with screen pixels glScalef(1.0f / height, 1.0f / height, 1.0f); gravity_x = 0.0; gravity_y = 0.0; boxes = (box*) malloc(sizeof(box) * MAX_BOXES); if (!boxes) { return EXIT_FAILURE; } num_boxes = 0; //Set clear color to a shade of green for good looks glClearColor(0.0f, 0.25f, 0.0f, 1.0f); return EXIT_SUCCESS; }
void WorldRenderer::render() { World *world = context->world; if (world->gameState == GAMESTATE_LOADING) { world->renderersReady = TRUE; } glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); context->renderContext->colorFilter = Vector4f(1, 1, 1, 1); if (gConfig->useShaders) { context->renderContext->projMatrix.identity(); context->renderContext->projMatrix.ortho(WORLD_LEFT, WORLD_RIGHT, WORLD_BOTTOM, WORLD_TOP, -1, 1); context->renderContext->mvMatrix.identity(); } else { // set up world projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(WORLD_LEFT, WORLD_RIGHT, WORLD_BOTTOM, WORLD_TOP, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_TEXTURE_2D); } glDisable(GL_BLEND); BOOL32 renderDebug = false; if (world->gameState == GAMESTATE_READY) { // render the main menuing bg //uiBGRenderer->render(WORLD_TOP, WORLD_RIGHT, WORLD_BOTTOM, WORLD_LEFT); } else if (world->gameState == GAMESTATE_RUNNING) { //uiBGRenderer->render(WORLD_TOP, WORLD_RIGHT, WORLD_BOTTOM, WORLD_LEFT); glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // pinball ballRenderer->render(world); glDisable(GL_BLEND); if (renderDebug) { // level editing and debugging b2DebugRenderer->render(world); } // BT UI context->menuRenderer->render(); // text overlay frameSampleTimeTotal += context->tickDelta; frameSamplesCollected++; if (frameSamplesCollected == 10) { if (frameSampleTimeTotal == 0) { fps = 0; } else { fps = 10 / frameSampleTimeTotal; } frameSamplesCollected = 0; frameSampleTimeTotal = 0; } if (context->showFPS) { char fpsText[10]; sprintf(fpsText, "FPS: %d", fps); if (gConfig->useShaders) { context->renderContext->projMatrix.identity(); context->renderContext->mvMatrix.identity(); context->renderContext->projMatrix.ortho(0, gConfig->width, gConfig->height, 0, -1, 1); } else { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0, gConfig->width, gConfig->height, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } glEnable(GL_BLEND); textRenderer->startText(); textRenderer->render(fpsText, 5, context->gConfig->height - 5); textRenderer->finishText(); } } }
static void CalculateUnderscan () { /* Setup libpad for our needs */ CellPadData data; uint32_t buttons = 0; /* Get the current button state */ if(CELL_OK == cellPadGetData(0, &data) && data.len >= 8) { buttons = data.button[2] | (data.button[3] << 8); } /* If we didn't get anything from the rcfile, or the user is holding select */ if(!GotUnderscanValues || buttons & 1) { UnderscanX = 0; UnderscanY = 0; /* Get the screen size */ uint32_t width, height; psglGetDeviceDimensions(psglGetCurrentDevice(), &width, &height); /* Generate image */ uint32_t* img = malloc((width / 10) * (height / 10) * 4); for(int i = 0; i != height / 10; i ++) { for(int j = 0; j != width / 10; j ++) { img[i * (width / 10) + j] = (i == 0 || j == 0 || i == (height / 10 - 1) || j == (width / 10 - 1)) ? 0xFF0000FF : 0xFF000000; } } CELL_IMAGE_Load(&overimage, 0, 0, width, height, img, width / 10, height / 10); free(img); CELL_IMAGE_Load(&helpimage, width / 2 - OVER_WIDTH / 2, height / 2 - OVER_HEIGHT / 2, OVER_WIDTH, OVER_HEIGHT, OverscanHelpImage, OVER_WIDTH, OVER_HEIGHT); /* Setup drawing */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0, width, height, 0, -1, 1); /* Loop */ while(1) { /* Draw screen */ float widthP = ((float)width) * (((float)(UnderscanX)) / 100.0f); float heightP = ((float)height) * (((float)(UnderscanY)) / 100.0f); glViewport(widthP, heightP, width - widthP * 2, height - heightP * 2); glClear(GL_COLOR_BUFFER_BIT); CELL_IMAGE_Draw(&overimage); CELL_IMAGE_Draw(&helpimage); psglSwap(); /* Update buttons */ if(CELL_OK == cellPadGetData(0, &data) && data.len >= 8) { buttons = data.button[2] | (data.button[3] << 8); } /* Update state */ if(buttons & 0x4000) break; if(buttons & 0x10) UnderscanY --; if(buttons & 0x40) UnderscanY ++; if(buttons & 0x20) UnderscanX --; if(buttons & 0x80) UnderscanX ++; UnderscanX = (UnderscanX < -5) ? -5 : UnderscanX; UnderscanY = (UnderscanY < -5) ? -5 : UnderscanY; UnderscanX = (UnderscanX > 25) ? 25 : UnderscanX; UnderscanY = (UnderscanY > 25) ? 25 : UnderscanY; SDL_Delay(50); } /* Release the image */ // CELL_IMAGE_Free(&overimage); CELL_IMAGE_Free(&helpimage); } CELL_PSGL_SetUnderscan(UnderscanX, UnderscanY); }
void CParticle::Render() { int hr = 0; // set up projection matrix in 3d pipeline float temp[16]={0}; float w, h; glGetFloatv(GL_VIEWPORT, temp); // get viewport to set the screen width and height. w = temp[2]; h = temp[3]; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof( 0.F, w , h, 0.F , 0.F, 1.F); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); hr = glGetError(); hr = glGetError(); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_TexID); glEnable(GL_BLEND); glDisable(GL_CULL_FACE); //glBlendFunc(GL_ONE, GL_ONE); glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); //Setup point sprites coordinate generation glEnable(GL_POINT_SPRITE_OES); glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE); glPointParameterf ( GL_POINT_SIZE_MAX , 135); glPointSize(24); char* pVtx = (char*)m_Ptc; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, sizeof(CParticle::Tptc), pVtx); pVtx += sizeof(Tvector2) * 2; glEnableClientState(GL_COLOR_ARRAY); glColorPointer (4, GL_FLOAT, sizeof(CParticle::Tptc), pVtx); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glDrawArrays(GL_POINTS, 0, m_PtcN); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_FALSE); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glDisable(GL_POINT_SPRITE_OES); glDisable(GL_BLEND); glColor4f(1, 1, 1, 1); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); }
static void soy_widgets_vscroll_real_render (soywidgetsWidget* base, gint x, gint y, gint width, gint height) { soywidgetsVScroll * self; gint _tmp0_; gint _x; gint _tmp1_; gint _y; gboolean _tmp23_; GLfloat* _tmp24_ = NULL; GLushort* _tmp25_ = NULL; gboolean _tmp26_ = FALSE; GLuint _tmp27_; gboolean _tmp29_; gdouble _posy; soyatomsSize* _tmp38_; gfloat _tmp39_; gfloat _tmp40_; gdouble _tmp41_; gint _tmp42_; soyatomsSize* _tmp43_; soyatomsSize* _tmp44_; soyatomsSize* _tmp45_; gfloat _tmp46_; gfloat _tmp47_; gdouble viewPort2Height; soyatomsSize* _tmp48_; soyatomsSize* _tmp49_; soyatomsSize* _tmp50_; gfloat _tmp51_; gfloat _tmp52_; gfloat _tmp53_; gboolean _tmp54_; soyatomsSize* _tmp66_; gfloat _tmp67_; gfloat _tmp68_; soyatomsPosition* _tmp69_; gfloat _tmp70_; gfloat _tmp71_; gint _tmp72_; gdouble _tmp73_; self = (soywidgetsVScroll*) base; _tmp0_ = x; _x = _tmp0_; _tmp1_ = y; _y = _tmp1_; { GeeLinkedList* _tmp2_; GeeLinkedList* _tmp3_; GeeLinkedList* _widget_list; GeeLinkedList* _tmp4_; gint _tmp5_; gint _tmp6_; gint _widget_size; gint _widget_index; _tmp2_ = ((soywidgetsContainer*) self)->children; _tmp3_ = _g_object_ref0 (_tmp2_); _widget_list = _tmp3_; _tmp4_ = _widget_list; _tmp5_ = gee_abstract_collection_get_size ((GeeCollection*) _tmp4_); _tmp6_ = _tmp5_; _widget_size = _tmp6_; _widget_index = -1; while (TRUE) { gint _tmp7_; gint _tmp8_; gint _tmp9_; GeeLinkedList* _tmp10_; gint _tmp11_; gpointer _tmp12_ = NULL; soywidgetsWidget* widget; soywidgetsWidget* _tmp13_; gint _tmp14_; gint _tmp15_; soywidgetsWidget* _tmp16_; gint _tmp17_; soywidgetsWidget* _tmp18_; gint _tmp19_; gint _tmp20_; soywidgetsWidget* _tmp21_; gint _tmp22_; _tmp7_ = _widget_index; _widget_index = _tmp7_ + 1; _tmp8_ = _widget_index; _tmp9_ = _widget_size; if (!(_tmp8_ < _tmp9_)) { break; } _tmp10_ = _widget_list; _tmp11_ = _widget_index; _tmp12_ = gee_abstract_list_get ((GeeAbstractList*) _tmp10_, _tmp11_); widget = (soywidgetsWidget*) _tmp12_; _tmp13_ = widget; _tmp14_ = _x; _tmp15_ = _y; _tmp16_ = widget; _tmp17_ = _tmp16_->width; _tmp18_ = widget; _tmp19_ = _tmp18_->height; soy_widgets_widget_render (_tmp13_, _tmp14_, _tmp15_, _tmp17_, _tmp19_); _tmp20_ = _y; _tmp21_ = widget; _tmp22_ = _tmp21_->height; _y = _tmp20_ + _tmp22_; _g_object_unref0 (widget); } _g_object_unref0 (_widget_list); } _tmp23_ = self->priv->_hasBar; if (!_tmp23_) { return; } _tmp24_ = g_new0 (GLfloat, 20); _tmp24_[0] = (GLfloat) 0.0f; _tmp24_[1] = (GLfloat) 0.0f; _tmp24_[2] = (GLfloat) 0.0f; _tmp24_[3] = (GLfloat) 0.0f; _tmp24_[4] = (GLfloat) 0.0f; _tmp24_[5] = (GLfloat) 1.0f; _tmp24_[6] = (GLfloat) 0.0f; _tmp24_[7] = (GLfloat) 0.0f; _tmp24_[8] = (GLfloat) 1.0f; _tmp24_[9] = (GLfloat) 0.0f; _tmp24_[10] = (GLfloat) 1.0f; _tmp24_[11] = (GLfloat) 1.0f; _tmp24_[12] = (GLfloat) 0.0f; _tmp24_[13] = (GLfloat) 1.0f; _tmp24_[14] = (GLfloat) 1.0f; _tmp24_[15] = (GLfloat) 0.0f; _tmp24_[16] = (GLfloat) 1.0f; _tmp24_[17] = (GLfloat) 0.0f; _tmp24_[18] = (GLfloat) 0.0f; _tmp24_[19] = (GLfloat) 1.0f; soy_widgets_vscroll__verts = (g_free (soy_widgets_vscroll__verts), NULL); soy_widgets_vscroll__verts = _tmp24_; soy_widgets_vscroll__verts_length1 = 20; _soy_widgets_vscroll__verts_size_ = soy_widgets_vscroll__verts_length1; _tmp25_ = g_new0 (GLushort, 6); _tmp25_[0] = (GLushort) 0; _tmp25_[1] = (GLushort) 1; _tmp25_[2] = (GLushort) 2; _tmp25_[3] = (GLushort) 2; _tmp25_[4] = (GLushort) 3; _tmp25_[5] = (GLushort) 0; soy_widgets_vscroll__faces = (g_free (soy_widgets_vscroll__faces), NULL); soy_widgets_vscroll__faces = _tmp25_; soy_widgets_vscroll__faces_length1 = 6; _soy_widgets_vscroll__faces_size_ = soy_widgets_vscroll__faces_length1; _tmp27_ = self->priv->_vbuffer; if (_tmp27_ == ((GLuint) 0)) { _tmp26_ = TRUE; } else { GLuint _tmp28_; _tmp28_ = self->priv->_ibuffer; _tmp26_ = _tmp28_ == ((GLuint) 0); } _tmp29_ = _tmp26_; if (_tmp29_) { GLuint _tmp30_ = 0U; GLuint _tmp31_; GLfloat* _tmp32_; gint _tmp32__length1; GLuint _tmp33_ = 0U; GLuint _tmp34_; GLushort* _tmp35_; gint _tmp35__length1; glGenBuffers ((GLsizei) 1, &_tmp30_); self->priv->_vbuffer = _tmp30_; _tmp31_ = self->priv->_vbuffer; glBindBuffer (GL_ARRAY_BUFFER, _tmp31_); _tmp32_ = soy_widgets_vscroll__verts; _tmp32__length1 = soy_widgets_vscroll__verts_length1; glBufferData (GL_ARRAY_BUFFER, ((GLsizei) sizeof (GLfloat)) * 20, _tmp32_, GL_STATIC_DRAW); glGenBuffers ((GLsizei) 1, &_tmp33_); self->priv->_ibuffer = _tmp33_; _tmp34_ = self->priv->_ibuffer; glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, _tmp34_); _tmp35_ = soy_widgets_vscroll__faces; _tmp35__length1 = soy_widgets_vscroll__faces_length1; glBufferData (GL_ELEMENT_ARRAY_BUFFER, ((GLsizei) sizeof (GLushort)) * 6, _tmp35_, GL_STATIC_DRAW); } else { GLuint _tmp36_; GLuint _tmp37_; _tmp36_ = self->priv->_vbuffer; glBindBuffer (GL_ARRAY_BUFFER, _tmp36_); _tmp37_ = self->priv->_ibuffer; glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, _tmp37_); } _posy = 0.0; _tmp38_ = self->priv->_viewPort; _tmp39_ = soy_atoms_size_get_width (_tmp38_); _tmp40_ = _tmp39_; _tmp41_ = _posy; _tmp42_ = ((soywidgetsScroller*) self)->scrollbarThickness; _tmp43_ = soy_widgets_widget_get_size ((soywidgetsWidget*) self); _tmp44_ = _tmp43_; _tmp45_ = _tmp44_; _tmp46_ = soy_atoms_size_get_height (_tmp45_); _tmp47_ = _tmp46_; glViewport ((GLint) _tmp40_, (GLint) _tmp41_, (GLsizei) ((GLint) _tmp42_), (GLsizei) ((GLint) _tmp47_)); _g_object_unref0 (_tmp45_); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrthof ((GLfloat) 0.0f, (GLfloat) 1.0f, (GLfloat) 1.0f, (GLfloat) 0.0f, (GLfloat) (-1.0f), (GLfloat) 1.0f); glMatrixMode (GL_MODELVIEW); glLoadIdentity (); glDisableClientState (GL_NORMAL_ARRAY); glVertexPointer ((GLint) 3, GL_FLOAT, (GLsizei) 20, (void*) 0); glDrawElements (GL_TRIANGLES, (GLsizei) 6, GL_UNSIGNED_SHORT, (void*) 0); glColor4f ((GLfloat) 0, (GLfloat) 1, (GLfloat) 0, (GLfloat) 1); viewPort2Height = 0.0; _tmp48_ = soy_widgets_widget_get_size ((soywidgetsWidget*) self); _tmp49_ = _tmp48_; _tmp50_ = _tmp49_; _tmp51_ = soy_atoms_size_get_height (_tmp50_); _tmp52_ = _tmp51_; _tmp53_ = self->priv->_totalHeight; _tmp54_ = _tmp52_ < _tmp53_; _g_object_unref0 (_tmp50_); if (_tmp54_) { soyatomsSize* _tmp55_; soyatomsSize* _tmp56_; soyatomsSize* _tmp57_; gfloat _tmp58_; gfloat _tmp59_; gfloat _tmp60_; soyatomsSize* _tmp61_; soyatomsSize* _tmp62_; soyatomsSize* _tmp63_; gfloat _tmp64_; gfloat _tmp65_; _tmp55_ = soy_widgets_widget_get_size ((soywidgetsWidget*) self); _tmp56_ = _tmp55_; _tmp57_ = _tmp56_; _tmp58_ = soy_atoms_size_get_height (_tmp57_); _tmp59_ = _tmp58_; _tmp60_ = self->priv->_totalHeight; _tmp61_ = soy_widgets_widget_get_size ((soywidgetsWidget*) self); _tmp62_ = _tmp61_; _tmp63_ = _tmp62_; _tmp64_ = soy_atoms_size_get_height (_tmp63_); _tmp65_ = _tmp64_; viewPort2Height = (gdouble) ((_tmp59_ / _tmp60_) * _tmp65_); _g_object_unref0 (_tmp63_); _g_object_unref0 (_tmp57_); } _tmp66_ = self->priv->_viewPort; _tmp67_ = soy_atoms_size_get_width (_tmp66_); _tmp68_ = _tmp67_; _tmp69_ = ((soywidgetsScroller*) self)->scrollPosition; _tmp70_ = soy_atoms_position_get_y (_tmp69_); _tmp71_ = _tmp70_; _tmp72_ = ((soywidgetsScroller*) self)->scrollbarThickness; _tmp73_ = viewPort2Height; glViewport ((GLint) _tmp68_, (GLint) _tmp71_, (GLsizei) ((GLint) _tmp72_), (GLsizei) ((GLint) _tmp73_)); glDrawElements (GL_TRIANGLES, (GLsizei) 6, GL_UNSIGNED_SHORT, (void*) 0); glColor4f ((GLfloat) 1, (GLfloat) 1, (GLfloat) 1, (GLfloat) 1); }
void FrameBuffer::DrawOnFrameBuffer(const std::function<void()>& fct, const ax::Size& size, const ax::Size& globalSize) { if(_custom_draw_on_fb_func) { return _custom_draw_on_fb_func(*this); } bool need_to_reactive_clip_test = false; if (glIsEnabled(GL_SCISSOR_TEST)) { glDisable(GL_SCISSOR_TEST); need_to_reactive_clip_test = true; } #ifdef ANDROID glBindFramebufferOES(GL_FRAMEBUFFER_OES, _frameBuffer); #else glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer); glPushAttrib(GL_DEPTH_BUFFER_BIT); #endif glClearColor(0.0, 0.0, 0.0, 0.0); #ifdef ANDROID glClearDepthf(1.0f); #else glClearDepth(1.0f); #endif glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); DrawingOnFrameBufferBlendFunction(); glViewport(0, 0, size.x, size.y); #ifdef ANDROID glOrthof(0.0f, size.x, 0.0f, size.y, 0.0f, 1.0f); #else // glOrtho(0.0, size.x, 0.0, size.y, 0.0, 1.0); #endif glMatrixMode(GL_MODELVIEW); ax::GL::Math::Matrix4 mv_matrix; mv_matrix.Identity().Load(); // Projection matrix. glm::mat4 projMat = glm::ortho(0.0f, (float)size.x, 0.0f, (float)size.y); // glm::mat4 view(1.0f); // glm::mat4 model(1.0f); ax::GC::mvp_matrix = projMat;// * view * model; if (fct) { fct(); } #ifdef ANDROID glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); #else glBindFramebuffer(GL_FRAMEBUFFER, 0); #endif // Reset old viewport. glViewport(0, 0, globalSize.x, globalSize.y); #ifndef ANDROID // WHEN ANDROID IS NOT DEFINE. glPopAttrib(); #endif if (need_to_reactive_clip_test) { glEnable(GL_SCISSOR_TEST); } }
JNIEXPORT void JNICALL JNIFUNCTION_NATIVE(nativeDrawFrame(JNIEnv* env, jobject obj, jint movieWidth, jint movieHeight, jint movieTextureID, jfloatArray movieTextureMtx)) { float width, height; // Get the array contents. //jsize movieTextureMtxLen = env->GetArrayLength(movieTextureMtx); float movieTextureMtxUnpacked[16]; env->GetFloatArrayRegion(movieTextureMtx, 0, /*movieTextureMtxLen*/ 16, movieTextureMtxUnpacked); if (!videoInited) { #ifdef DEBUG LOGI("nativeDrawFrame !VIDEO\n"); #endif return; // No point in trying to draw until video is inited. } if (!nftDataLoaded && nftDataLoadingThreadHandle) { // Check if NFT data loading has completed. if (threadGetStatus(nftDataLoadingThreadHandle) > 0) { nftDataLoaded = true; threadWaitQuit(nftDataLoadingThreadHandle); threadFree(&nftDataLoadingThreadHandle); // Clean up. } else { #ifdef DEBUG LOGI("nativeDrawFrame !NFTDATA\n"); #endif return; // No point in trying to draw until NFT data is loaded. } } #ifdef DEBUG LOGI("nativeDrawFrame\n"); #endif if (!gARViewInited) { if (!initARView()) return; } if (gARViewLayoutRequired) layoutARView(); // Upload new video frame if required. if (videoFrameNeedsPixelBufferDataUpload) { pthread_mutex_lock(&gVideoFrameLock); arglPixelBufferDataUploadBiPlanar(gArglSettings, gVideoFrame, gVideoFrame + videoWidth*videoHeight); videoFrameNeedsPixelBufferDataUpload = false; pthread_mutex_unlock(&gVideoFrameLock); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the buffers for new frame. // Display the current frame arglDispImage(gArglSettings); // Set up 3D mode. glMatrixMode(GL_PROJECTION); glLoadMatrixf(cameraLens); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glStateCacheEnableDepthTest(); // Set any initial per-frame GL state you require here. // ---> // Lighting and geometry that moves with the camera should be added here. // (I.e. should be specified before camera pose transform.) // ---> // Draw an object on all valid markers. for (int i = 0; i < markersNFTCount; i++) { if (markersNFT[i].valid) { glLoadMatrixf(markersNFT[i].pose.T); // // Draw a rectangular surface textured with the movie texture. // float w = 80.0f; float h = w * (float)movieHeight/(float)movieWidth; GLfloat vertices[4][2] = { {0.0f, 0.0f}, {w, 0.0f}, {w, h}, {0.0f, h} }; GLfloat normals[4][3] = { {0.0f, 0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}, {0.0f, 0.0f, 1.0f} }; GLfloat texcoords[4][2] = { {0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f} }; glStateCacheActiveTexture(GL_TEXTURE0); glMatrixMode(GL_TEXTURE); glPushMatrix(); glLoadMatrixf(movieTextureMtxUnpacked); glMatrixMode(GL_MODELVIEW); glVertexPointer(2, GL_FLOAT, 0, vertices); glNormalPointer(GL_FLOAT, 0, normals); glStateCacheClientActiveTexture(GL_TEXTURE0); glTexCoordPointer(2, GL_FLOAT, 0, texcoords); glStateCacheEnableClientStateVertexArray(); glStateCacheEnableClientStateNormalArray(); glStateCacheEnableClientStateTexCoordArray(); glStateCacheBindTexture2D(0); glStateCacheDisableTex2D(); glStateCacheDisableLighting(); glEnable(GL_TEXTURE_EXTERNAL_OES); glBindTexture(GL_TEXTURE_EXTERNAL_OES, movieTextureID); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glBindTexture(GL_TEXTURE_EXTERNAL_OES, 0); glDisable(GL_TEXTURE_EXTERNAL_OES); glMatrixMode(GL_TEXTURE); glPopMatrix(); glMatrixMode(GL_MODELVIEW); // // End. // } } if (cameraPoseValid) { glMultMatrixf(cameraPose); // All lighting and geometry to be drawn in world coordinates goes here. // ---> } // If you added external OpenGL code above, and that code doesn't use the glStateCache routines, // then uncomment the line below. //glStateCacheFlush(); // Set up 2D mode. glMatrixMode(GL_PROJECTION); glLoadIdentity(); width = (float)viewPort[viewPortIndexWidth]; height = (float)viewPort[viewPortIndexHeight]; glOrthof(0.0f, width, 0.0f, height, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glStateCacheDisableDepthTest(); // Add your own 2D overlays here. // ---> // If you added external OpenGL code above, and that code doesn't use the glStateCache routines, // then uncomment the line below. //glStateCacheFlush(); #ifdef DEBUG // Example of 2D drawing. It just draws a white border line. Change the 0 to 1 to enable. const GLfloat square_vertices [4][2] = { {0.5f, 0.5f}, {0.5f, height - 0.5f}, {width - 0.5f, height - 0.5f}, {width - 0.5f, 0.5f} }; glStateCacheDisableLighting(); glStateCacheDisableTex2D(); glVertexPointer(2, GL_FLOAT, 0, square_vertices); glStateCacheEnableClientStateVertexArray(); glColor4ub(255, 255, 255, 255); glDrawArrays(GL_LINE_LOOP, 0, 4); CHECK_GL_ERROR(); #endif }
void NoDice::Font:: print(GLfloat x, GLfloat y, GLfloat scale, const std::string& text) { GLfloat viewport[4]; glGetFloatv(GL_VIEWPORT, viewport); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); #ifdef HAVE_OPENGL_ES glOrthof(viewport[0], viewport[2], viewport[1], viewport[3], -1.0f, 1.0f); #else glOrtho(viewport[0], viewport[2], viewport[1], viewport[3], -1.0f, 1.0f); #endif glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glBindTexture(GL_TEXTURE_2D, m_texture); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); static const int coords_per_vertex = 2; static const int coords_per_texture = 2; static const int row_width = coords_per_vertex + coords_per_texture; // Two coords per vertex, two coords per texture, three vertexes for first // triangle, one for second triangle = (2 + 2) * (3 + 1) = 16. GLfloat varray[16]; for (std::string::const_iterator it = text.begin(); it != text.end(); ++it) { char c = *it; varray[0] = x + m_glyph[c].left * scale; varray[1] = y - (m_glyph[c].height - m_glyph[c].top) * scale; varray[2] = m_glyph[c].s; varray[3] = m_glyph[c].t + m_glyph[c].h; varray[4] = x + m_glyph[c].width * scale; varray[5] = y - (m_glyph[c].height - m_glyph[c].top) * scale; varray[6] = m_glyph[c].s + m_glyph[c].w; varray[7] = m_glyph[c].t + m_glyph[c].h; varray[8] = x + m_glyph[c].left * scale; varray[9] = y + m_glyph[c].top * scale; varray[10] = m_glyph[c].s; varray[11] = m_glyph[c].t; varray[12] = x + m_glyph[c].width * scale; varray[13] = y + m_glyph[c].top * scale; varray[14] = m_glyph[c].s + m_glyph[c].w; varray[15] = m_glyph[c].t; static const int stride = row_width * sizeof(varray[0]); glVertexPointer(coords_per_vertex, GL_FLOAT, stride, varray); glTexCoordPointer(coords_per_texture, GL_FLOAT, stride, ((char*)varray) + 2*sizeof(GLfloat)); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); check_gl_error("glDrawArrays"); x += m_glyph[c].advance * scale; } glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); }
void CLT3DEngine::DrawTangram() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); GLint width,height; width = iScreenWidth >> 1; height = iScreenHeight >> 1; glOrthof((float)-width, (float) width, (float)-height, (float) height, -1, 1); // set the same size as viewport glMatrixMode(GL_TEXTURE); glLoadIdentity(); glScalef(1.0f / 255.0f, 1.0f / 255.0f, 1.0f); glTranslatef(128.0f, 128.0f, 0.0f); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glVertexPointer(2, GL_BYTE, 0, verticesTangram); glTexCoordPointer(2, GL_BYTE, 0, nokTexCoordsTangram); /* Animate and draw box */ glColor4f(1.0f,1.0f,1.0f,1.0f); if (ETrue) { glPushMatrix(); // glTranslatex(0, 0, iCameraDistance << 16); glRotatex(iRotate[0] << 16, 0, 0, 1 << 16); glScalex(25 << 16, 25<<16 ,1 << 16); glTranslatex(iTranslate[0][0] << 16, 0, 0); glTranslatex(0, iTranslate[0][1] << 16, 0); // glTranslatex(0, 2<<16, 0); // glRotatex(iRotate[0] << 16, 0, 0, 1 << 16); // glTranslatex(0, -2<<16, 0); // glRotatex(0,iRotate<<16,0,0); // glRotatex(0,0,iRotate<<16,0); glBindTexture( GL_TEXTURE_2D, iOpenGLES.iID ); glDrawElements(GL_TRIANGLES, 1 * 3, GL_UNSIGNED_BYTE, STTtriangleBig1); glPopMatrix(); } if (ETrue) { glPushMatrix(); // glTranslatex(0, 0, iCameraDistance << 16); glScalex(25 << 16, 25<<16 ,1 << 16); glTranslatex(iTranslate[1][0] << 16, 0, 0); glTranslatex(0, iTranslate[1][1] << 16, 0); glTranslatex(-2<<16, 0, 0); glRotatex(iRotate[1] << 16, 0, 0, 1 << 16); glTranslatex(2<<16, 0, 0); glBindTexture( GL_TEXTURE_2D, iOpenGLES.iID ); glDrawElements(GL_TRIANGLES, 1 * 3, GL_UNSIGNED_BYTE, STTtriangleBig2); glPopMatrix(); } if (ETrue) { glPushMatrix(); // glTranslatex(0, 0, iCameraDistance << 16); glScalex(25 << 16, 25<<16 ,1 << 16); glTranslatex(iTranslate[2][0] << 16, 0, 0); glTranslatex(0, iTranslate[2][1] << 16, 0); glTranslatex(1<<16, 0, 0); glRotatex(iRotate[2] << 16, 0, 0, 1 << 16); glTranslatex(-1<<16, 0, 0); glBindTexture( GL_TEXTURE_2D, iOpenGLES.iID ); glDrawElements(GL_TRIANGLES, 1 * 3, GL_UNSIGNED_BYTE, STTtriangleSmall1); glPopMatrix(); } if (ETrue) { glPushMatrix(); // glTranslatex(0, 0, iCameraDistance << 16); glScalex(25 << 16, 25<<16 ,1 << 16); glTranslatex(iTranslate[3][0] << 16, 0, 0); glTranslatex(0, iTranslate[3][1] << 16, 0); glTranslatex(-2<<16, -3<<16, 0); glRotatex(iRotate[3] << 16, 0, 0, 1 << 16); glTranslatex(2<<16, 3<<16, 0); glBindTexture( GL_TEXTURE_2D, iOpenGLES.iID ); glDrawElements(GL_TRIANGLES, 1 * 3, GL_UNSIGNED_BYTE, STTtriangleSmall2); glPopMatrix(); } if (ETrue) { glPushMatrix(); // glTranslatex(0, 0, iCameraDistance << 16); glScalex(25 << 16, 25<<16 ,1 << 16); glTranslatex(iTranslate[4][0] << 16, 0, 0); glTranslatex(0, iTranslate[4][1] << 16, 0); glTranslatex(3<<16, -3<<16, 0); glRotatex(iRotate[4] << 16, 0, 0, 1 << 16); glTranslatex(-3<<16, 3<<16, 0); glBindTexture( GL_TEXTURE_2D, iOpenGLES.iID ); glDrawElements(GL_TRIANGLES, 1 * 3, GL_UNSIGNED_BYTE, STTtriangleMid); glPopMatrix(); } if (ETrue) { glPushMatrix(); // glTranslatex(0, 0, iCameraDistance << 16); glScalex(25 << 16, 25<<16 ,1 << 16); glTranslatex(iTranslate[5][0] << 16, 0, 0); glTranslatex(0, iTranslate[5][1] << 16, 0); glTranslatex(0, -2<<16, 0); glRotatex(iRotate[5] << 16, 0, 0, 1 << 16); glTranslatex(0, 2<<16, 0); glBindTexture( GL_TEXTURE_2D, iOpenGLES.iID ); glDrawElements(GL_TRIANGLES, 2 * 3, GL_UNSIGNED_BYTE, STSquare); glPopMatrix(); } if (ETrue) { glPushMatrix(); // glTranslatex(0, 0, iCameraDistance << 16); glScalex(25 << 16, 25<<16 ,1 << 16); glTranslatex(iTranslate[6][0] << 16, 0, 0); glTranslatex(0, iTranslate[6][1] << 16, 0); glTranslatex(3<<16, 1<<16, 0); glRotatex(iRotate[6] << 16, 0, 0, 1 << 16); glTranslatex(-3<<16, -1<<16, 0); glBindTexture( GL_TEXTURE_2D, iOpenGLES.iID ); glDrawElements(GL_TRIANGLES, 2 * 3, GL_UNSIGNED_BYTE, STRect); glPopMatrix(); } }
int initOpenGL(screen_context_t screen_cxt) { fprintf(stderr, "init openGL\n"); //Initialize vertex and color data vertices[0] = 0.0f; vertices[1] = 0.0f; vertices[2] = 1024.0f; vertices[3] = 0.0f; vertices[4] = 0.0f; vertices[5] = 600.0f; vertices[6] = 1024.0f; vertices[7] = 600.0f; verticesH[0] = 0.0f; verticesH[1] = 0.0f; verticesH[2] = 600.0f; verticesH[3] = 0.0f; verticesH[4] = 0.0f; verticesH[5] = 1024.0f; verticesH[6] = 600.0f; verticesH[7] = 1024.0f; verticesTouchpoint[0] = 0.0f; verticesTouchpoint[1] = 0.0f; verticesTouchpoint[2] = 120.0f; verticesTouchpoint[3] = 0.0f; verticesTouchpoint[4] = 0.0f; verticesTouchpoint[5] = 120.0f; verticesTouchpoint[6] = 120.0f; verticesTouchpoint[7] = 120.0f; //Query width and height of the window surface created by utility code EGLint surface_width, surface_height; eglQuerySurface(egl_disp, egl_surf, EGL_WIDTH, &surface_width); eglQuerySurface(egl_disp, egl_surf, EGL_HEIGHT, &surface_height); width = (float) surface_width; height = (float) surface_height; if (width < height) { oriention_side_up = 1; } //On initialize bbutil loads arial as a default font. We are going to load MyriadPro-Bold as it looks a little better and scale it //to fit out bubble nicely. dpi = bbutil_calculate_dpi(screen_cxt); font = bbutil_load_font( "/usr/fonts/font_repository/adobe/MyriadPro-Bold.otf", 9, dpi); if (!font) { return EXIT_FAILURE; } EGLint err = eglGetError(); if (err != 0x3000) { fprintf(stderr, "Unable to query egl surface dimensions\n"); return EXIT_FAILURE; } //Load background texture float tex_x, tex_y; if (EXIT_SUCCESS != bbutil_load_texture("app/native/bg.png", NULL, NULL, &tex_x, &tex_y, &background)) { fprintf(stderr, "Unable to load background texture\n"); } //Load background portrait texture float texH_x, texH_y; if (EXIT_SUCCESS != bbutil_load_texture("app/native/bg_hochformat.png", NULL, NULL, &texH_x, &texH_y, &backgroundH)) { fprintf(stderr, "Unable to load background portrait texture\n"); } //Load background texture float tex_x_touch, tex_y_touch; if (EXIT_SUCCESS != bbutil_load_texture("app/native/zeiger.png", NULL, NULL, &tex_x_touch, &tex_y_touch, &touchpoint)) { fprintf(stderr, "Unable to load zeiger texture\n"); } tex_coord[0] = 0.0f; tex_coord[1] = 0.0f; tex_coord[2] = tex_x; tex_coord[3] = 0.0f; tex_coord[4] = 0.0f; tex_coord[5] = tex_y; tex_coord[6] = tex_x; tex_coord[7] = tex_y; tex_coordH[0] = 0.0f; tex_coordH[1] = 0.0f; tex_coordH[2] = texH_x; tex_coordH[3] = 0.0f; tex_coordH[4] = 0.0f; tex_coordH[5] = texH_y; tex_coordH[6] = texH_x; tex_coordH[7] = texH_y; tex_coord_touchpoint[0] = 0.0f; tex_coord_touchpoint[1] = 0.0f; tex_coord_touchpoint[2] = tex_x_touch; tex_coord_touchpoint[3] = 0.0f; tex_coord_touchpoint[4] = 0.0f; tex_coord_touchpoint[5] = tex_y_touch; tex_coord_touchpoint[6] = tex_x_touch; tex_coord_touchpoint[7] = tex_y_touch; glShadeModel(GL_SMOOTH); //set clear color to white glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glViewport(0, 0, surface_width, surface_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0.0f, (float) (surface_width) / (float) (surface_height), 0.0f, 1.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glScalef(1.0f / surface_height, 1.0f / surface_height, 1.0f); //init texture glEnable(GL_TEXTURE_2D); return EXIT_SUCCESS; }
void llcv_gles_setup(llcv_gles_context* mz, int width, int height) { mz->pbufWidth = width; mz->pbufHeight = height; if (dmz_use_gles_warp() && mz->egl_display == NULL) { dmz_debug_log("setting up %i x %i rendering surface", mz->pbufWidth, mz->pbufHeight); mz->egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); EGLint major, minor, error; if (eglInitialize(mz->egl_display, &major, &minor) && mz->egl_display != EGL_NO_DISPLAY ) { dmz_debug_log("Initialized GLES and got version %i.%i", major, minor); } else { int n_err = llcv_gl_error_count(); dmz_debug_log("Failed to initialize GLES display with %i errors", n_err); // llcv_gl_supported = false; return; } int attribList[] = { EGL_DEPTH_SIZE, 0, EGL_STENCIL_SIZE, 0, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; EGLint max_configs = 5; EGLint num_configs = 0; EGLConfig configs[max_configs]; eglChooseConfig(mz->egl_display, attribList, configs, max_configs, &num_configs); if (num_configs == 0) { llcv_gl_error_count(); dmz_debug_log("didn't get any EGL configs!"); // llcv_gl_supported = false; return; } mz->egl_context = eglCreateContext(mz->egl_display, configs[0], EGL_NO_CONTEXT, NULL); if (mz->egl_context == EGL_NO_CONTEXT) { llcv_gl_error_count(); dmz_debug_log("Failed to create an EGL context"); // llcv_gl_supported = false; return; } int pbAttribList[] = { EGL_WIDTH, mz->pbufWidth, EGL_HEIGHT, mz->pbufHeight, EGL_NONE }; mz->egl_surface = eglCreatePbufferSurface(mz->egl_display, configs[0], pbAttribList); if (! eglMakeCurrent(mz->egl_display, mz->egl_surface, mz->egl_surface, mz->egl_context)) { llcv_gl_error_count(); dmz_debug_log("gles warp not available"); return; } // "onSurfaceCreated" glGenTextures(1, &(mz->gl_texture)); glBindTexture(GL_TEXTURE_2D, mz->gl_texture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glEnable(GL_TEXTURE_2D); //Enable Texture Mapping ( NEW ) glShadeModel(GL_SMOOTH); //Enable Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //Black Background if (llcv_gl_error_count()) return; glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // "onSurfaceChanged" glViewport(0, 0, mz->pbufWidth, mz->pbufHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(-1, 1, -1, 1, -1, 1); if (llcv_gl_error_count()) return; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // onetime setup GLfloat h = 1.0f; GLfloat w = 1.0f; // gl_verts = { // -w, -h, 0.0f, // V1 - bottom left // -w, h, 0.0f, // V2 - top left // w, -h, 0.0f, // V3 - bottom right // w, h, 0.0f // V4 - top right // }; // appease the compiler. GLfloat* gl_verts = mz->gl_verts; gl_verts[0] = gl_verts[3] = -w; gl_verts[1] = gl_verts[7] = -h; gl_verts[2] = gl_verts[5] = gl_verts[8] = gl_verts[11] = 0.0f; gl_verts[4] = gl_verts[10] = h; gl_verts[6] = gl_verts[9] = w; if (llcv_gl_error_count()) return; } }
void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far) { glOrthof(left, right, bottom, top, near, far); }
SDL_Surface *ANDROID_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags) { SDL_PixelFormat format; int bpp1; __android_log_print(ANDROID_LOG_INFO, "libSDL", "SDL_SetVideoMode(): application requested mode %dx%d OpenGL %d HW %d BPP %d", width, height, flags & SDL_OPENGL, flags & SDL_HWSURFACE, SDL_ANDROID_BITSPERPIXEL); if( ! SDL_ANDROID_InsideVideoThread() ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Error: calling %s not from the main thread!", __PRETTY_FUNCTION__); return NULL; } sdl_opengl = (flags & SDL_OPENGL) ? 1 : 0; SDL_ANDROID_sFakeWindowWidth = width; SDL_ANDROID_sFakeWindowHeight = height; current->flags = (flags & SDL_FULLSCREEN) | (flags & SDL_OPENGL) | SDL_DOUBLEBUF | ( flags & SDL_HWSURFACE ); current->w = width; current->h = height; current->pitch = SDL_ANDROID_sFakeWindowWidth * SDL_ANDROID_BYTESPERPIXEL; current->pixels = NULL; current->hwdata = NULL; HwSurfaceCount = 0; HwSurfaceList = NULL; DEBUGOUT("ANDROID_SetVideoMode() HwSurfaceCount %d HwSurfaceList %p", HwSurfaceCount, HwSurfaceList); if( ! sdl_opengl ) { SDL_DisplayMode mode; SDL_RendererInfo SDL_VideoRendererInfo; SDL_SelectVideoDisplay(0); SDL_VideoWindow = SDL_CreateWindow("", 0, 0, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL); SDL_memset(&mode, 0, sizeof(mode)); mode.format = PixelFormatEnum; SDL_SetWindowDisplayMode(SDL_VideoWindow, &mode); if (SDL_CreateRenderer(SDL_VideoWindow, -1, 0) < 0) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "SDL_SetVideoMode(): Error creating renderer"); return NULL; } SDL_GetRendererInfo(&SDL_VideoRendererInfo); current->hwdata = NULL; if( ! (flags & SDL_HWSURFACE) ) { current->pixels = SDL_malloc(width * height * SDL_ANDROID_BYTESPERPIXEL); if ( ! current->pixels ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Couldn't allocate buffer for requested mode"); SDL_SetError("Couldn't allocate buffer for requested mode"); return(NULL); } SDL_memset(current->pixels, 0, width * height * SDL_ANDROID_BYTESPERPIXEL); current->hwdata = (struct private_hwdata *)SDL_CreateTexture(PixelFormatEnum, SDL_TEXTUREACCESS_STATIC, width, height); if( !current->hwdata ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Couldn't allocate texture for SDL_CurrentVideoSurface"); SDL_free(current->pixels); current->pixels = NULL; SDL_OutOfMemory(); return(NULL); } if( SDL_ANDROID_SmoothVideo ) SDL_SetTextureScaleMode((SDL_Texture *)current->hwdata, SDL_SCALEMODE_SLOW); // Register main video texture to be recreated when needed HwSurfaceCount++; HwSurfaceList = SDL_realloc( HwSurfaceList, HwSurfaceCount * sizeof(SDL_Surface *) ); HwSurfaceList[HwSurfaceCount-1] = current; DEBUGOUT("ANDROID_SetVideoMode() HwSurfaceCount %d HwSurfaceList %p", HwSurfaceCount, HwSurfaceList); } glViewport(0, 0, SDL_ANDROID_sRealWindowWidth, SDL_ANDROID_sRealWindowHeight); glOrthof(0.0, (GLfloat) SDL_ANDROID_sWindowWidth, (GLfloat) SDL_ANDROID_sWindowHeight, 0.0, 0.0, 1.0); } /* Allocate the new pixel format for the screen */ SDL_memset(&format, 0, sizeof(format)); SDL_PixelFormatEnumToMasks( PixelFormatEnum, &bpp1, &format.Rmask, &format.Gmask, &format.Bmask, &format.Amask ); format.BitsPerPixel = bpp1; format.BytesPerPixel = SDL_ANDROID_BYTESPERPIXEL; if ( ! SDL_ReallocFormat(current, SDL_ANDROID_BITSPERPIXEL, format.Rmask, format.Gmask, format.Bmask, format.Amask) ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Couldn't allocate new pixel format for requested mode"); SDL_SetError("Couldn't allocate new pixel format for requested mode"); return(NULL); } /* Set up the new mode framebuffer */ SDL_CurrentVideoSurface = current; /* We're done */ return(current); }
status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, uint32_t sw, uint32_t sh) { LOGI("captureScreenImplLocked"); status_t result = PERMISSION_DENIED; // only one display supported for now if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) return BAD_VALUE; if (!GLExtensions::getInstance().haveFramebufferObject()) return INVALID_OPERATION; // get screen geometry const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); const uint32_t hw_w = hw.getWidth(); const uint32_t hw_h = hw.getHeight(); if ((sw > hw_w) || (sh > hw_h)) return BAD_VALUE; sw = (!sw) ? hw_w : sw; sh = (!sh) ? hw_h : sh; const size_t size = sw * sh * 4; // make sure to clear all GL error flags while ( glGetError() != GL_NO_ERROR ) ; // create a FBO GLuint name, tname; glGenRenderbuffersOES(1, &tname); glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname); glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh); glGenFramebuffersOES(1, &name); glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname); GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); if (status == GL_FRAMEBUFFER_COMPLETE_OES) { // invert everything, b/c glReadPixel() below will invert the FB glViewport(0, 0, sw, sh); glScissor(0, 0, sw, sh); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrthof(0, hw_w, 0, hw_h, 0, 1); glMatrixMode(GL_MODELVIEW); // redraw the screen entirely... glClearColor(0,0,0,1); glClear(GL_COLOR_BUFFER_BIT); const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); const size_t count = layers.size(); for (size_t i=0 ; i<count ; ++i) { const sp<LayerBase>& layer(layers[i]); layer->drawForSreenShot(); } // XXX: this is needed on tegra glScissor(0, 0, sw, sh); // check for errors and return screen capture if (glGetError() != GL_NO_ERROR) { // error while rendering result = INVALID_OPERATION; } else { // allocate shared memory large enough to hold the // screen capture sp<MemoryHeapBase> base( new MemoryHeapBase(size, 0, "screen-capture") ); void* const ptr = base->getBase(); if (ptr) { // capture the screen with glReadPixels() glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr); if (glGetError() == GL_NO_ERROR) { *heap = base; *w = sw; *h = sh; *f = PIXEL_FORMAT_RGBA_8888; result = NO_ERROR; } } else { result = NO_MEMORY; } } glEnable(GL_SCISSOR_TEST); glViewport(0, 0, hw_w, hw_h); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } else { result = BAD_VALUE; } // release FBO resources glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); glDeleteRenderbuffersOES(1, &tname); glDeleteFramebuffersOES(1, &name); hw.compositionComplete(); return result; }
void video_init_ex(uint width, uint height, uint v_width, uint v_height, const char* name, bool fullscreen) { assert(width != 0 && height != 0); assert(v_width != 0 && v_height != 0); if(!_sys_video_initialized) _sys_video_init(); _sys_set_title(name); screen_widthf = v_width; screen_heightf = v_height; touch_scale_x = (float)v_width / (float)width; touch_scale_y = (float)v_height / (float)height; LOG_INFO("Vendor : %s", glGetString(GL_VENDOR)); LOG_INFO("Renderer : %s", glGetString(GL_RENDERER)); LOG_INFO("Version : %s", glGetString(GL_VERSION)); LOG_INFO("Extensions : %s", glGetString(GL_EXTENSIONS)); has_discard_extension = _check_extension("GL_EXT_discard_framebuffer"); glEnable(GL_TEXTURE_2D); glShadeModel(GL_FLAT); glClearDepthf(1.0f); glEnable(GL_BLEND); glDisable(GL_ALPHA_TEST); _set_blendmode(BM_NORMAL); last_blend_mode = BM_NORMAL; glMatrixMode(GL_TEXTURE); glScalef(1.0f/tex_mul, 1.0f/tex_mul, 1.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); #ifdef TARGET_IOS if(width > height) { glViewport(0, 0, height, width); // Some tricky transformations to properly turn view sideways glOrthof(0.0f, (float)v_width, (float)v_height, 0.0f, -1.0f, 1.0f); glTranslatef((float)v_width/2.0f, (float)v_height/2.0f, 0.0f); glRotatef(90.0f, 0.0f, 0.0f, 1.0f); glTranslatef((float)v_height/-2.0f, (float)v_width/-2.0f, 0.0f); glScalef((float)v_height/(float)v_width, (float)v_width/(float)v_height, 1.0f); } else #endif { glViewport(0, 0, width, height); glOrthof(0.0f, (float)v_width, (float)v_height, 0.0f, -1.0f, 1.0f); //glScalef((float)v_width/(float)v_height, (float)v_height/(float)v_width, 1.0f); //glTranslatef(0.0f, (float)v_width/-2.0f, 0.0f); } frame = 0; x_size_factor = (float)v_width / (float)width; y_size_factor = (float)v_height / (float)height; #ifndef NO_DEVMODE memset(&v_stats, 0, sizeof(v_stats)); v_stats.n_layers = bucket_count; v_stats.layer_rects = (uint*)MEM_ALLOC(sizeof(uint) * bucket_count); v_stats.layer_lines = (uint*)MEM_ALLOC(sizeof(uint) * bucket_count); #endif // Init render buckets & blend modes memset(rect_buckets, 0, sizeof(rect_buckets)); memset(line_buckets, 0, sizeof(line_buckets)); for(uint i = 0; i < bucket_count; ++i) { blend_modes[i] = BM_NORMAL; } // Temp bucket for sorting rects_out = darray_create(sizeof(TexturedRectDesc), 32); textures = darray_create(sizeof(Texture), 16); // Generate index buffer for(uint i = 0; i < max_vertices/4; ++i) { index_buffer[i*6 + 0] = i*4 + 0; index_buffer[i*6 + 1] = i*4 + 1; index_buffer[i*6 + 2] = i*4 + 3; index_buffer[i*6 + 3] = i*4 + 2; index_buffer[i*6 + 4] = i*4 + 1; index_buffer[i*6 + 5] = i*4 + 3; } vertex_buffer = darray_create(sizeof(Vertex), max_vertices); LOG_INFO("Video initialized"); }
void GLAPIENTRY gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top) { glOrthof(left, right, bottom, top, -1, 1); }
int main(int argc, char *argv[]) { int fsaa, accel; int value; int i, done; SDL_DisplayMode mode; SDL_Event event; Uint32 then, now, frames; int status; /* Initialize parameters */ fsaa = 0; accel = 0; /* Initialize test framework */ state = CommonCreateState(argv, SDL_INIT_VIDEO); if (!state) { return 1; } for (i = 1; i < argc;) { int consumed; consumed = CommonArg(state, i); if (consumed == 0) { if (SDL_strcasecmp(argv[i], "--fsaa") == 0) { ++fsaa; consumed = 1; } else if (SDL_strcasecmp(argv[i], "--accel") == 0) { ++accel; consumed = 1; } else if (SDL_strcasecmp(argv[i], "--zdepth") == 0) { i++; if (!argv[i]) { consumed = -1; } else { depth = SDL_atoi(argv[i]); consumed = 1; } } else { consumed = -1; } } if (consumed < 0) { fprintf(stderr, "Usage: %s %s [--fsaa] [--accel] [--zdepth %%d]\n", argv[0], CommonUsage(state)); quit(1); } i += consumed; } /* Set OpenGL parameters */ state->window_flags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS; state->gl_red_size = 5; state->gl_green_size = 5; state->gl_blue_size = 5; state->gl_depth_size = depth; if (fsaa) { state->gl_multisamplebuffers=1; state->gl_multisamplesamples=fsaa; } if (accel) { state->gl_accelerated=1; } if (!CommonInit(state)) { quit(2); } context = SDL_calloc(state->num_windows, sizeof(context)); if (context == NULL) { fprintf(stderr, "Out of memory!\n"); quit(2); } /* Create OpenGL ES contexts */ for (i = 0; i < state->num_windows; i++) { context[i] = SDL_GL_CreateContext(state->windows[i]); if (!context[i]) { fprintf(stderr, "SDL_GL_CreateContext(): %s\n", SDL_GetError()); quit(2); } } if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) { SDL_GL_SetSwapInterval(1); } else { SDL_GL_SetSwapInterval(0); } SDL_GetCurrentDisplayMode(0, &mode); printf("Screen bpp: %d\n", SDL_BITSPERPIXEL(mode.format)); printf("\n"); printf("Vendor : %s\n", glGetString(GL_VENDOR)); printf("Renderer : %s\n", glGetString(GL_RENDERER)); printf("Version : %s\n", glGetString(GL_VERSION)); printf("Extensions : %s\n", glGetString(GL_EXTENSIONS)); printf("\n"); status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value); if (!status) { printf("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value); } else { fprintf(stderr, "Failed to get SDL_GL_RED_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value); if (!status) { printf("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value); } else { fprintf(stderr, "Failed to get SDL_GL_GREEN_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value); if (!status) { printf("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value); } else { fprintf(stderr, "Failed to get SDL_GL_BLUE_SIZE: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value); if (!status) { printf("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", depth, value); } else { fprintf(stderr, "Failed to get SDL_GL_DEPTH_SIZE: %s\n", SDL_GetError()); } if (fsaa) { status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value); if (!status) { printf("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value); } else { fprintf(stderr, "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n", SDL_GetError()); } status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value); if (!status) { printf("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa, value); } else { fprintf(stderr, "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n", SDL_GetError()); } } if (accel) { status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value); if (!status) { printf("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value); } else { fprintf(stderr, "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n", SDL_GetError()); } } /* Set rendering settings for each context */ for (i = 0; i < state->num_windows; ++i) { float aspectAdjust; status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); /* Continue for next window */ continue; } aspectAdjust = (4.0f / 3.0f) / ((float)state->window_w / state->window_h); glViewport(0, 0, state->window_w, state->window_h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(-2.0, 2.0, -2.0 * aspectAdjust, 2.0 * aspectAdjust, -20.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); } /* Main render loop */ frames = 0; then = SDL_GetTicks(); done = 0; int isPause = 0; while (!done) { SDL_Delay(1000); LOGI("in process"); /* Check for events */ ++frames; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: for (i = 0; i < state->num_windows; ++i) { if (event.window.windowID == SDL_GetWindowID(state->windows[i])) { status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); break; } /* Change view port to the new window dimensions */ glViewport(0, 0, event.window.data1, event.window.data2); /* Update window content */ Render(); SDL_GL_SwapWindow(state->windows[i]); break; } } break; case SDL_WINDOWEVENT_FOCUS_LOST: LOGI("in SDL_WINDOWEVENT_FOCUS_LOST"); isPause = 1; break; case SDL_WINDOWEVENT_FOCUS_GAINED: LOGI("in SDL_WINDOWEVENT_FOCUS_GAINED"); isPause = 0; break; } } CommonEvent(state, &event, &done); } if (isPause == 0) { for (i = 0; i < state->num_windows; ++i) { status = SDL_GL_MakeCurrent(state->windows[i], context[i]); if (status) { printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError()); /* Continue for next window */ continue; } Render(); SDL_GL_SwapWindow(state->windows[i]); } } } /* Print out some timing information */ now = SDL_GetTicks(); if (now > then) { printf("%2.2f frames per second\n", ((double) frames * 1000) / (now - then)); } quit(0); return 0; }
// this function is called each frame void glutDisplay (void) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup the OpenGL viewpoint glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); // Check if Registration is done for Depth and RGB Images - Brandyn, Sravanthi g_DepthGenerator.GetAlternativeViewPointCap().SetViewPoint(g_ImageGenerator); // g_DepthGenerator.GetAlternativeViewPointCap().ResetViewPoint(); xn::SceneMetaData sceneMD; xn::DepthMetaData depthMD; xn::ImageMetaData imageMD; g_DepthGenerator.GetMetaData(depthMD); g_ImageGenerator.GetMetaData(imageMD); #ifdef USE_GLUT glOrtho(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0); #else glOrthof(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0); #endif glDisable(GL_TEXTURE_2D); if (!g_bPause) { // Read next available data g_Context.WaitAndUpdateAll(); } // Process the data //DRAW // Check if Registration is done for Depth and RGB Images - Brandyn, Sravanthi g_DepthGenerator.GetAlternativeViewPointCap().SetViewPoint(g_ImageGenerator); // g_DepthGenerator.GetAlternativeViewPointCap().ResetViewPoint(); g_DepthGenerator.GetMetaData(depthMD); g_ImageGenerator.GetMetaData(imageMD); g_UserGenerator.GetUserPixels(0, sceneMD); DrawDepthMap(depthMD, imageMD, sceneMD, g_nPlayer); if (g_nPlayer != 0) { XnPoint3D com; g_UserGenerator.GetCoM(g_nPlayer, com); if (com.Z == 0) { g_nPlayer = 0; FindPlayer(); } } #ifdef USE_GLUT glutSwapBuffers(); #endif }
void CameraRenderNode::orthographic(double zNear, double zFar) { Vector2 screenBounds = scene->getSettingsManager()->getPixelViewportBounds(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0,0, screenBounds.X(),screenBounds.Y()); if(guiCamera) { Vector2 worldBounds = scene->getSettingsManager()->getPointViewportBounds(); glOrthof(0, worldBounds.X(), 0, worldBounds.Y(), zNear, zFar); glMatrixMode(GL_MODELVIEW); //glPushMatrix(); glLoadIdentity(); glDepthMask(GL_FALSE); Vector2 screenCenter = Vector2(worldBounds.X()/2, worldBounds.Y()/2); switch(scene->getSettingsManager()->getRotation()) { case ROTATION_PORTRAIT: break; case ROTATION_LANDSCAPE_COUNTERCLOCKWISE: glTranslatef(screenCenter.X(),screenCenter.Y(),0.0f); glRotatef(-90.0f, 0.0f, 0.0f, 1.0f); glTranslatef(-screenCenter.Y(),-screenCenter.X(),0.0f); break; case ROTATION_PORTRAIT_UPSIDEDOWN: glTranslatef(screenCenter.X(),screenCenter.Y(),0.0f); glRotatef(-180.0f, 0.0f, 0.0f, 1.0f); glTranslatef(-screenCenter.X(),-screenCenter.Y(),0.0f); break; case ROTATION_LANDSCAPE_CLOCKWISE: glTranslatef(screenCenter.X(),screenCenter.Y(),0.0f); glRotatef(-270.0f, 0.0f, 0.0f, 1.0f); glTranslatef(-screenCenter.Y(),-screenCenter.X(),0.0f); break; } } else { Rect2D cameraBounds = getCameraBounds(); glOrthof(cameraBounds.min.X(), cameraBounds.max.X(), cameraBounds.min.Y(), cameraBounds.max.Y(), zNear, zFar); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDepthMask(GL_FALSE); switch(scene->getSettingsManager()->getRotation()) { case ROTATION_PORTRAIT: break; case ROTATION_LANDSCAPE_COUNTERCLOCKWISE: glRotatef(-90.0f, 0.0f, 0.0f, 1.0f); break; case ROTATION_PORTRAIT_UPSIDEDOWN: glRotatef(-180.0f, 0.0f, 0.0f, 1.0f); break; case ROTATION_LANDSCAPE_CLOCKWISE: glRotatef(-270.0f, 0.0f, 0.0f, 1.0f); break; } // translate view so camera moves based on game object's position Vector3* pos = owner->getTransform()->getPosition(); glTranslatef(-pos->X(), -pos->Y(), -pos->Z()); } }