Пример #1
0
void RenderSystem::setDrawBuffer(RenderSystem::DrawBufferTarget target) {

    glDrawBuffer(GL_NONE);
}
    void GLFrameBufferObject::initialise()
    {
		// Release depth and stencil, if they were bound
        mManager->releaseRenderBuffer(mDepth);
        mManager->releaseRenderBuffer(mStencil);
		mManager->releaseRenderBuffer(mMultisampleColourBuffer);
        // First buffer must be bound
        if(!mColour[0].buffer)
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
            "Attachment 0 must have surface attached",
		 	"GLFrameBufferObject::initialise");
        }

		// If we're doing multisampling, then we need another FBO which contains a
		// renderbuffer which is set up to multisample, and we'll blit it to the final 
		// FBO afterwards to perform the multisample resolve. In that case, the 
		// mMultisampleFB is bound during rendering and is the one with a depth/stencil

        // Store basic stats
        uint32 width = mColour[0].buffer->getWidth();
        uint32 height = mColour[0].buffer->getHeight();
        GLuint format = mColour[0].buffer->getGLFormat();
        ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets();

		// Bind simple buffer to add colour attachments
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB);

        // Bind all attachment points to frame buffer
        for(unsigned int x=0; x<maxSupportedMRTs; ++x)
        {
            if(mColour[x].buffer)
            {
                if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height)
                {
                    StringStream ss;
                    ss << "Attachment " << x << " has incompatible size ";
                    ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight();
                    ss << ". It must be of the same as the size of surface 0, ";
                    ss << width << "x" << height;
                    ss << ".";
                    OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise");
                }
                if(mColour[x].buffer->getGLFormat() != format)
                {
                    StringStream ss;
                    ss << "Attachment " << x << " has incompatible format.";
                    OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise");
                }
	            mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT+x, mColour[x].zoffset);
            }
            else
            {
                // Detach
                glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+x,
                    GL_RENDERBUFFER_EXT, 0);
            }
        }

		// Now deal with depth / stencil
		if (mMultisampleFB)
		{
			// Bind multisample buffer
			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB);

			// Create AA render buffer (colour)
			// note, this can be shared too because we blit it to the final FBO
			// right after the render is finished
			mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples);

			// Attach it, because we won't be attaching below and non-multisample has
			// actually been attached to other FBO
			mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT, 
				mMultisampleColourBuffer.zoffset);

			// depth & stencil will be dealt with below

		}

        // Depth buffer is not handled here anymore.
		// See GLFrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor()

		// Do glDrawBuffer calls
		GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS];
		GLsizei n=0;
		for(unsigned int x=0; x<OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x)
		{
			// Fill attached colour buffers
			if(mColour[x].buffer)
			{
				bufs[x] = GL_COLOR_ATTACHMENT0_EXT + x;
				// Keep highest used buffer + 1
				n = x+1;
			}
			else
			{
				bufs[x] = GL_NONE;
			}
		}
		if(glDrawBuffers)
		{
			// Drawbuffer extension supported, use it
			glDrawBuffers(n, bufs);
		}
		else
		{
			// In this case, the capabilities will not show more than 1 simultaneaous render target.
			glDrawBuffer(bufs[0]);
		}
		if (mMultisampleFB)
		{
			// we need a read buffer because we'll be blitting to mFB
			glReadBuffer(bufs[0]);
		}
		else
		{
			// No read buffer, by default, if we want to read anyway we must not forget to set this.
			glReadBuffer(GL_NONE);
		}
        
        // Check status
        GLuint status;
        status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
        
        // Bind main buffer
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
        
        switch(status)
        {
        case GL_FRAMEBUFFER_COMPLETE_EXT:
            // All is good
            break;
        case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
            "All framebuffer formats with this texture internal format unsupported",
		 	"GLFrameBufferObject::initialise");
        default:
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
            "Framebuffer incomplete or other FBO status error",
		 	"GLFrameBufferObject::initialise");
        }
        
    }
Пример #3
0
/* ARGSUSED5 */  /* Only Win32 uses gameMode parameter. */
GLUTwindow *
__glutCreateWindow(GLUTwindow * parent,
  int x, int y, int width, int height, int gameMode)
{
  GLUTwindow *window;
  XSetWindowAttributes wa;
  unsigned long attribMask;
  int winnum;
  int i;
  void *fbc;

#if defined(_WIN32)
  WNDCLASS wc;
  int style;

  if (!GetClassInfo(GetModuleHandle(NULL), TEXT("GLUT"), &wc)) {
    __glutOpenWin32Connection(NULL);
  }
#else
  if (!__glutDisplay) {
    __glutOpenXConnection(NULL);
  }
#endif
  if (__glutGameModeWindow) {
    __glutFatalError("cannot create windows in game mode.");
  }
  winnum = getUnusedWindowSlot();
  window = (GLUTwindow *) malloc(sizeof(GLUTwindow));
  if (!window) {
    __glutFatalError("out of memory.");
  }
  window->num = winnum;

#if !defined(_WIN32)
  window->vis = __glutDetermineWindowVisual(&window->treatAsSingle,
    &window->visAlloced, &fbc);
  if (!window->vis) {
    __glutFatalError(
      "visual with necessary capabilities not found.");
  }
  __glutSetupColormap(window->vis, &window->colormap, &window->cmap);
#endif
  window->eventMask = StructureNotifyMask | ExposureMask;

  attribMask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
  wa.background_pixmap = None;
  wa.border_pixel = 0;
  wa.colormap = window->cmap;
  wa.event_mask = window->eventMask;
  if (parent) {
    if (parent->eventMask & GLUT_HACK_STOP_PROPAGATE_MASK)
      wa.event_mask |= GLUT_HACK_STOP_PROPAGATE_MASK;
    attribMask |= CWDontPropagate;
    wa.do_not_propagate_mask = parent->eventMask & GLUT_DONT_PROPAGATE_FILTER_MASK;
  } else {
    wa.do_not_propagate_mask = 0;
  }

  /* Stash width and height before Win32's __glutAdjustCoords
     possibly overwrites the values. */
  window->width = width;
  window->height = height;
  window->forceReshape = True;
  window->ignoreKeyRepeat = False;

#if defined(_WIN32)
  __glutAdjustCoords(parent ? parent->win : NULL,
    &x, &y, &width, &height);
  if (parent) {
    style = WS_CHILD;
  } else {
    if (gameMode) {
      /* Game mode window should be a WS_POPUP window to
         ensure that the taskbar is hidden by it.  A standard
         WS_OVERLAPPEDWINDOW does not hide the task bar. */
      style = WS_POPUP | WS_MAXIMIZE;
    } else {
      /* A standard toplevel window with borders and such. */
      style = WS_OVERLAPPEDWINDOW;
    }
  }
  window->win = CreateWindow(TEXT("GLUT"), TEXT("GLUT"),
    WS_CLIPSIBLINGS | WS_CLIPCHILDREN | style,
    x, y, width, height, parent ? parent->win : __glutRoot,
    NULL, GetModuleHandle(NULL), 0);
  window->hdc = GetDC(window->win);
  /* Must set the XHDC for fake glXChooseVisual & fake
     glXCreateContext & fake XAllocColorCells. */
  XHDC = window->hdc;
  window->vis = __glutDetermineWindowVisual(&window->treatAsSingle,
    &window->visAlloced, &fbc);
  if (!window->vis) {
    __glutFatalError(
      "pixel format with necessary capabilities not found.");
  }
  if (!SetPixelFormat(window->hdc,
      ChoosePixelFormat(window->hdc, window->vis),
      window->vis)) {
    __glutFatalError("SetPixelFormat failed during window create.");
  }
  __glutSetupColormap(window->vis, &window->colormap, &window->cmap);
  /* Make sure subwindows get a windowStatus callback. */
  if (parent) {
    PostMessage(parent->win, WM_ACTIVATE, 0, 0);
  }
  window->renderDc = window->hdc;
#else
  window->win = XCreateWindow(__glutDisplay,
    parent == NULL ? __glutRoot : parent->win,
    x, y, width, height, 0,
    window->vis->depth, InputOutput, window->vis->visual,
    attribMask, &wa);
#endif
  window->renderWin = window->win;
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_fbconfig)
  if (fbc) {
    window->ctx = __glut_glXCreateContextWithConfigSGIX(__glutDisplay, fbc,
      GLX_RGBA_TYPE_SGIX, None, __glutTryDirect);
  } else
#endif
  {
    window->ctx = glXCreateContext(__glutDisplay, window->vis,
      None, __glutTryDirect);
  }
  if (!window->ctx) {
    __glutFatalError(
      "failed to create OpenGL rendering context.");
  }
  window->renderCtx = window->ctx;
#if !defined(_WIN32)
  window->isDirect = glXIsDirect(__glutDisplay, window->ctx);
  if (__glutForceDirect) {
    if (!window->isDirect)
      __glutFatalError("direct rendering not possible.");
  }
#endif

  window->parent = parent;
  if (parent) {
    window->siblings = parent->children;
    parent->children = window;
  } else {
    window->siblings = NULL;
  }
  window->overlay = NULL;
  window->children = NULL;
  window->display = __glutDefaultDisplay;
  window->reshape = __glutDefaultReshape;
  window->mouse = NULL;
  window->motion = NULL;
  window->passive = NULL;
  window->entry = NULL;
  window->keyboard = NULL;
  window->keyboardUp = NULL;
  window->windowStatus = NULL;
  window->visibility = NULL;
  window->special = NULL;
  window->specialUp = NULL;
  window->buttonBox = NULL;
  window->dials = NULL;
  window->spaceMotion = NULL;
  window->spaceRotate = NULL;
  window->spaceButton = NULL;
  window->tabletMotion = NULL;
  window->tabletButton = NULL;
#ifdef _WIN32
  window->joystick = NULL;
  window->joyPollInterval = 0;
#endif
  window->tabletPos[0] = -1;
  window->tabletPos[1] = -1;
  window->shownState = 0;
  window->visState = -1;  /* not VisibilityUnobscured,
                             VisibilityPartiallyObscured, or
                             VisibilityFullyObscured */
  window->entryState = -1;  /* not EnterNotify or LeaveNotify */

  window->desiredConfMask = 0;
  window->buttonUses = 0;
  window->cursor = GLUT_CURSOR_INHERIT;

  /* Setup window to be mapped when glutMainLoop starts. */
  window->workMask = GLUT_MAP_WORK;
#ifdef _WIN32
  if (gameMode) {
    /* When mapping a game mode window, just show
       the window.  We have already created the game
       mode window with a maximize flag at creation
       time.  Doing a ShowWindow(window->win, SW_SHOWNORMAL)
       would be wrong for a game mode window since it
       would unmaximize the window. */
    window->desiredMapState = GameModeState;
  } else {
    window->desiredMapState = NormalState;
  }
#else
  window->desiredMapState = NormalState;
#endif
  window->prevWorkWin = __glutWindowWorkList;
  __glutWindowWorkList = window;

  /* Initially, no menus attached. */
  for (i = 0; i < GLUT_MAX_MENUS; i++) {
    window->menu[i] = 0;
  }

  /* Add this new window to the window list. */
  __glutWindowList[winnum] = window;

  /* Make the new window the current window. */
  __glutSetWindow(window);

  __glutDetermineMesaSwapHackSupport();

  if (window->treatAsSingle) {
    /* We do this because either the window really is single
       buffered (in which case this is redundant, but harmless,
       because this is the initial single-buffered context
       state); or we are treating a double buffered window as a
       single-buffered window because the system does not appear
       to export any suitable single- buffered visuals (in which
       the following are necessary). */
    glDrawBuffer(GL_FRONT);
    glReadBuffer(GL_FRONT);
  }
  return window;
}
Пример #4
0
//
// This function is called when the window needs redrawing.
//
static void Display(void)
{
    ARdouble p[16];
    ARdouble m[16];

#ifdef ARDOUBLE_IS_FLOAT
    GLdouble p0[16];
    GLdouble m0[16];
#endif
    int                 i, j, k;
    GLfloat             w, bw, bh, vertices[6][2];
    GLubyte             pixels[300];
    char                text[256];
    GLdouble            winX, winY, winZ;
    int                 showMErr[CHECK_ID_MULTIMARKERS_MAX];
    GLdouble            MX[CHECK_ID_MULTIMARKERS_MAX];
    GLdouble            MY[CHECK_ID_MULTIMARKERS_MAX];
    int                 pattDetectMode;
    AR_MATRIX_CODE_TYPE matrixCodeType;


    // Select correct buffer for this context.
    glDrawBuffer(GL_BACK);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     // Clear the buffers for new frame.

    arglPixelBufferDataUpload(gArglSettings, gARTImage);
    arglDispImage(gArglSettings);

    if (gMultiConfigCount)
    {
        arglCameraFrustumRH(&(gCparamLT->param), VIEW_DISTANCE_MIN, VIEW_DISTANCE_MAX, p);
        glMatrixMode(GL_PROJECTION);
#ifdef ARDOUBLE_IS_FLOAT
        glLoadMatrixf(p);
#else
        glLoadMatrixd(p);
#endif
        glMatrixMode(GL_MODELVIEW);
        glEnable(GL_DEPTH_TEST);

        // If we have multi-configs, show their origin onscreen.
        for (k = 0; k < gMultiConfigCount; k++)
        {
            showMErr[k] = FALSE;
            if (gMultiConfigs[k]->prevF != 0)
            {
                arglCameraViewRH((const ARdouble (*)[4])gMultiConfigs[k]->trans, m, 1.0);
#ifdef ARDOUBLE_IS_FLOAT
                glLoadMatrixf(m);
#else
                glLoadMatrixd(m);
#endif
                drawAxes();
#ifdef ARDOUBLE_IS_FLOAT
                for (i = 0; i < 16; i++)
                    m0[i] = (GLdouble)m[i];

                for (i = 0; i < 16; i++)
                    p0[i] = (GLdouble)p[i];

                if (gluProject(0, 0, 0, m0, p0, gViewport, &winX, &winY, &winZ) == GL_TRUE)
#else
                if (gluProject(0, 0, 0, m, p, gViewport, &winX, &winY, &winZ) == GL_TRUE)
#endif
                {
                    showMErr[k] = TRUE;
                    MX[k]       = winX; MY[k] = winY;
                }
            }
        } // for k
    }

    // Any 2D overlays go here.
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, (GLdouble)windowWidth, 0, (GLdouble)windowHeight, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glDisable(GL_LIGHTING);
    glDisable(GL_DEPTH_TEST);

    arGetPatternDetectionMode(gARHandle, &pattDetectMode);
    arGetMatrixCodeType(gARHandle, &matrixCodeType);

    // For all markers, draw onscreen position.
    // Colour based on cutoffPhase.
    glLoadIdentity();
    glVertexPointer(2, GL_FLOAT, 0, vertices);
    glEnableClientState(GL_VERTEX_ARRAY);
    glLineWidth(2.0f);

    for (j = 0; j < gARHandle->marker_num; j++)
    {
        glColor3ubv(cutoffPhaseColours[gARHandle->markerInfo[j].cutoffPhase].colour);

        for (i = 0; i < 5; i++)
        {
            int dir = gARHandle->markerInfo[j].dir;
            vertices[i][0] = (float)gARHandle->markerInfo[j].vertex[(i + 4 - dir) % 4][0] * (float)windowWidth / (float)gARHandle->xsize;
            vertices[i][1] = ((float)gARHandle->ysize - (float)gARHandle->markerInfo[j].vertex[(i + 4 - dir) % 4][1]) * (float)windowHeight / (float)gARHandle->ysize;
        }

        vertices[i][0] = (float)gARHandle->markerInfo[j].pos[0] * (float)windowWidth / (float)gARHandle->xsize;
        vertices[i][1] = ((float)gARHandle->ysize - (float)gARHandle->markerInfo[j].pos[1]) * (float)windowHeight / (float)gARHandle->ysize;
        glDrawArrays(GL_LINE_STRIP, 0, 6);
        // For markers that have been identified, draw the ID number.
        if (gARHandle->markerInfo[j].id >= 0)
        {
            glColor3ub(255, 0, 0);
            if (matrixCodeType == AR_MATRIX_CODE_GLOBAL_ID && (pattDetectMode == AR_MATRIX_CODE_DETECTION || pattDetectMode == AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX || pattDetectMode == AR_TEMPLATE_MATCHING_MONO_AND_MATRIX))
                snprintf(text, sizeof(text), "%llu (err=%d)", gARHandle->markerInfo[j].globalID, gARHandle->markerInfo[j].errorCorrected);
            else
                snprintf(text, sizeof(text), "%d", gARHandle->markerInfo[j].id);

            print(text, (float)gARHandle->markerInfo[j].pos[0] * (float)windowWidth / (float)gARHandle->xsize, ((float)gARHandle->ysize - (float)gARHandle->markerInfo[j].pos[1]) * (float)windowHeight / (float)gARHandle->ysize, 0, 0);
        }
    }

    glDisableClientState(GL_VERTEX_ARRAY);

    // For matrix mode, draw the pattern image of the largest marker.
    if (pattDetectMode == AR_MATRIX_CODE_DETECTION || pattDetectMode == AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX || pattDetectMode == AR_TEMPLATE_MATCHING_MONO_AND_MATRIX)
    {
        int area = 0, biggestMarker = -1;

        for (j = 0; j < gARHandle->marker_num; j++)
            if (gARHandle->markerInfo[j].area > area)
            {
                area          = gARHandle->markerInfo[j].area;
                biggestMarker = j;
            }

        if (area >= AR_AREA_MIN)
        {
            int      imageProcMode;
            ARdouble pattRatio;
            ARUint8  ext_patt[AR_PATT_SIZE2_MAX * AR_PATT_SIZE2_MAX * 3]; // Holds unwarped pattern extracted from image.
            int      size;
            int      zoom = 4;
            ARdouble vertexUpright[4][2];

            // Reorder vertices based on dir.
            for (i = 0; i < 4; i++)
            {
                int dir = gARHandle->markerInfo[biggestMarker].dir;
                vertexUpright[i][0] = gARHandle->markerInfo[biggestMarker].vertex[(i + 4 - dir) % 4][0];
                vertexUpright[i][1] = gARHandle->markerInfo[biggestMarker].vertex[(i + 4 - dir) % 4][1];
            }

            arGetImageProcMode(gARHandle, &imageProcMode);
            arGetPattRatio(gARHandle, &pattRatio);
            if (matrixCodeType == AR_MATRIX_CODE_GLOBAL_ID)
            {
                size = 14;
                arPattGetImage2(imageProcMode, AR_MATRIX_CODE_DETECTION, size, size * AR_PATT_SAMPLE_FACTOR2,
                                gARTImage, gARHandle->xsize, gARHandle->ysize, gARHandle->arPixelFormat, &gCparamLT->paramLTf, vertexUpright, (ARdouble)14 / (ARdouble)(14 + 2), ext_patt);
            }
            else
            {
                size = matrixCodeType & AR_MATRIX_CODE_TYPE_SIZE_MASK;
                arPattGetImage2(imageProcMode, AR_MATRIX_CODE_DETECTION, size, size * AR_PATT_SAMPLE_FACTOR2,
                                gARTImage, gARHandle->xsize, gARHandle->ysize, gARHandle->arPixelFormat, &gCparamLT->paramLTf, vertexUpright, pattRatio, ext_patt);
            }

            glRasterPos2f((float)(windowWidth - size * zoom) - 4.0f, (float)(size * zoom) + 4.0f);
            glPixelZoom((float)zoom, (float)-zoom);
            glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
            glDrawPixels(size, size, GL_LUMINANCE, GL_UNSIGNED_BYTE, ext_patt);
            glPixelZoom(1.0f, 1.0f);
        }
    }


    // Draw error value for multimarker pose.
    for (k = 0; k < gMultiConfigCount; k++)
    {
        if (showMErr[k])
        {
            snprintf(text, sizeof(text), "err=%0.3f", gMultiErrs[k]);
            print(text, MX[k], MY[k], 0, 0);
        }
    }

    //
    // Draw help text and mode.
    //
    glLoadIdentity();
    if (gShowMode)
    {
        printMode();
    }

    if (gShowHelp)
    {
        if (gShowHelp == 1)
        {
            printHelpKeys();
        }
        else if (gShowHelp == 2)
        {
            bw = 0.0f;

            for (i = 0; i < AR_MARKER_INFO_CUTOFF_PHASE_DESCRIPTION_COUNT; i++)
            {
                w = (float)glutBitmapLength(GLUT_BITMAP_HELVETICA_10, (unsigned char*)arMarkerInfoCutoffPhaseDescriptions[cutoffPhaseColours[i].cutoffPhase]);
                if (w > bw)
                    bw = w;
            }

            bw += 12.0f; // Space for color block.
            bh  = AR_MARKER_INFO_CUTOFF_PHASE_DESCRIPTION_COUNT * 10.0f /* character height */ + (AR_MARKER_INFO_CUTOFF_PHASE_DESCRIPTION_COUNT - 1) * 2.0f /* line spacing */;
            drawBackground(bw, bh, 2.0f, 2.0f);

            // Draw the colour block and text, line by line.
            for (i = 0; i < AR_MARKER_INFO_CUTOFF_PHASE_DESCRIPTION_COUNT; i++)
            {
                for (j = 0; j < 300; j += 3)
                {
                    pixels[j]     = cutoffPhaseColours[i].colour[0];
                    pixels[j + 1] = cutoffPhaseColours[i].colour[1];
                    pixels[j + 2] = cutoffPhaseColours[i].colour[2];
                }

                glRasterPos2f(2.0f, (AR_MARKER_INFO_CUTOFF_PHASE_DESCRIPTION_COUNT - 1 - i) * 12.0f + 2.0f);
                glPixelZoom(1.0f, 1.0f);
                glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
                glDrawPixels(10, 10, GL_RGB, GL_UNSIGNED_BYTE, pixels);
                print(arMarkerInfoCutoffPhaseDescriptions[cutoffPhaseColours[i].cutoffPhase], 14.0f, (AR_MARKER_INFO_CUTOFF_PHASE_DESCRIPTION_COUNT - 1 - i) * 12.0f + 2.0f, 0, 0);
            }
        }
    }

    glutSwapBuffers();
}
Пример #5
0
void R_InitFBOs(void)
{
	int i;
	int width, height;

	Ren_Developer("------- R_InitFBOs -------\n");

	if (!glConfig2.framebufferObjectAvailable)
	{
		return;
	}

	R_CheckDefaultBuffer();

	tr.numFBOs = 0;

	GL_CheckErrors();

	// make sure the render thread is stopped
	R_IssuePendingRenderCommands();

	{
		// forward shading
		if (glConfig2.textureNPOTAvailable)
		{
			width  = glConfig.vidWidth;
			height = glConfig.vidHeight;
		}
		else
		{
			width  = NearestPowerOfTwo(glConfig.vidWidth);
			height = NearestPowerOfTwo(glConfig.vidHeight);
		}

		// deferredRender FBO for the HDR or LDR context
		tr.deferredRenderFBO = R_CreateFBO("_deferredRender", width, height);
		R_BindFBO(tr.deferredRenderFBO);

		if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
		{
			R_CreateFBOColorBuffer(tr.deferredRenderFBO, GL_RGBA16F_ARB, 0);
		}
		else
		{
			R_CreateFBOColorBuffer(tr.deferredRenderFBO, GL_RGBA, 0);
		}
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.deferredRenderFBOImage->texnum, 0);

		R_CreateFBODepthBuffer(tr.deferredRenderFBO, GL_DEPTH_COMPONENT24_ARB);
		R_AttachFBOTextureDepth(tr.depthRenderImage->texnum);

		R_CheckFBO(tr.deferredRenderFBO);
	}

	if (glConfig2.framebufferBlitAvailable)
	{
		if (glConfig2.textureNPOTAvailable)
		{
			width  = glConfig.vidWidth;
			height = glConfig.vidHeight;
		}
		else
		{
			width  = NearestPowerOfTwo(glConfig.vidWidth);
			height = NearestPowerOfTwo(glConfig.vidHeight);
		}

		tr.occlusionRenderFBO = R_CreateFBO("_occlusionRender", width, height);
		R_BindFBO(tr.occlusionRenderFBO);

#if 0
		if (glConfig2.framebufferPackedDepthStencilAvailable)
		{
			//R_CreateFBOColorBuffer(tr.occlusionRenderFBO, GL_ALPHA32F_ARB, 0);
			R_CreateFBOPackedDepthStencilBuffer(tr.occlusionRenderFBO, GL_DEPTH24_STENCIL8);
		}
		else
		{
			//R_CreateFBOColorBuffer(tr.occlusionRenderFBO, GL_RGBA, 0);
			R_CreateFBODepthBuffer(tr.occlusionRenderFBO, GL_DEPTH_COMPONENT24);
		}
#else
		R_CreateFBODepthBuffer(tr.occlusionRenderFBO, GL_DEPTH_COMPONENT24);
#endif

		R_CreateFBOColorBuffer(tr.occlusionRenderFBO, GL_RGBA, 0);
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.occlusionRenderFBOImage->texnum, 0);

		R_CheckFBO(tr.occlusionRenderFBO);
	}

	if (r_shadows->integer >= SHADOWING_ESM16 && glConfig2.textureFloatAvailable)
	{
		// shadowMap FBOs for shadow mapping offscreen rendering
		for (i = 0; i < MAX_SHADOWMAPS; i++)
		{
			width = height = shadowMapResolutions[i];

			tr.shadowMapFBO[i] = R_CreateFBO(va("_shadowMap%d", i), width, height);
			R_BindFBO(tr.shadowMapFBO[i]);


			if (r_shadows->integer == SHADOWING_ESM32)
			{
				R_CreateFBOColorBuffer(tr.shadowMapFBO[i], GL_ALPHA32F_ARB, 0);
			}
			else if (r_shadows->integer == SHADOWING_VSM32)
			{
				R_CreateFBOColorBuffer(tr.shadowMapFBO[i], GL_LUMINANCE_ALPHA32F_ARB, 0);
			}
			else if (r_shadows->integer == SHADOWING_EVSM32)
			{
				if (r_evsmPostProcess->integer)
				{
					R_CreateFBOColorBuffer(tr.shadowMapFBO[i], GL_ALPHA32F_ARB, 0);
				}
				else
				{
					R_CreateFBOColorBuffer(tr.shadowMapFBO[i], GL_RGBA32F_ARB, 0);
				}
			}
			else
			{
				R_CreateFBOColorBuffer(tr.shadowMapFBO[i], GL_RGBA16F_ARB, 0);
			}

			R_CreateFBODepthBuffer(tr.shadowMapFBO[i], GL_DEPTH_COMPONENT24_ARB);

			R_CheckFBO(tr.shadowMapFBO[i]);
		}

		// sun requires different resolutions
		for (i = 0; i < MAX_SHADOWMAPS; i++)
		{
			width = height = sunShadowMapResolutions[i];

			tr.sunShadowMapFBO[i] = R_CreateFBO(va("_sunShadowMap%d", i), width, height);
			R_BindFBO(tr.sunShadowMapFBO[i]);

			if (r_shadows->integer == SHADOWING_ESM32)
			{
				R_CreateFBOColorBuffer(tr.sunShadowMapFBO[i], GL_ALPHA32F_ARB, 0);
			}
			else if (r_shadows->integer == SHADOWING_VSM32)
			{
				R_CreateFBOColorBuffer(tr.sunShadowMapFBO[i], GL_LUMINANCE_ALPHA32F_ARB, 0);
			}
			else if (r_shadows->integer == SHADOWING_EVSM32)
			{
				if (!r_evsmPostProcess->integer)
				{
					R_CreateFBOColorBuffer(tr.sunShadowMapFBO[i], GL_RGBA32F_ARB, 0);
				}
			}
			else
			{
				R_CreateFBOColorBuffer(tr.sunShadowMapFBO[i], GL_RGBA16F_ARB, 0);
			}

			R_CreateFBODepthBuffer(tr.sunShadowMapFBO[i], GL_DEPTH_COMPONENT24_ARB);

			if (r_shadows->integer == SHADOWING_EVSM32 && r_evsmPostProcess->integer)
			{
				R_AttachFBOTextureDepth(tr.sunShadowMapFBOImage[i]->texnum);

				/*
				Since we don't have a color attachment the framebuffer will be considered incomplete.
				Consequently, we must inform the driver that we do not wish to render to the color buffer.
				We do this with a call to set the draw-buffer and read-buffer to GL_NONE:
				*/
				glDrawBuffer(GL_NONE);
				glReadBuffer(GL_NONE);
			}

			R_CheckFBO(tr.sunShadowMapFBO[i]);
		}
	}

	{
		if (glConfig2.textureNPOTAvailable)
		{
			width  = glConfig.vidWidth;
			height = glConfig.vidHeight;
		}
		else
		{
			width  = NearestPowerOfTwo(glConfig.vidWidth);
			height = NearestPowerOfTwo(glConfig.vidHeight);
		}

		// portalRender FBO for portals, mirrors, water, cameras et cetera
		tr.portalRenderFBO = R_CreateFBO("_portalRender", width, height);
		R_BindFBO(tr.portalRenderFBO);

		if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
		{
			R_CreateFBOColorBuffer(tr.portalRenderFBO, GL_RGBA16F_ARB, 0);
		}
		else
		{
			R_CreateFBOColorBuffer(tr.portalRenderFBO, GL_RGBA, 0);
		}
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.portalRenderImage->texnum, 0);

		R_CheckFBO(tr.portalRenderFBO);
	}


	{
		if (glConfig2.textureNPOTAvailable)
		{
			width  = glConfig.vidWidth * 0.25f;
			height = glConfig.vidHeight * 0.25f;
		}
		else
		{
			width  = NearestPowerOfTwo(glConfig.vidWidth * 0.25f);
			height = NearestPowerOfTwo(glConfig.vidHeight * 0.25f);
		}

		tr.downScaleFBO_quarter = R_CreateFBO("_downScale_quarter", width, height);
		R_BindFBO(tr.downScaleFBO_quarter);
		if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_quarter, GL_RGBA16F_ARB, 0);
		}
		else
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_quarter, GL_RGBA, 0);
		}
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.downScaleFBOImage_quarter->texnum, 0);
		R_CheckFBO(tr.downScaleFBO_quarter);


		tr.downScaleFBO_64x64 = R_CreateFBO("_downScale_64x64", 64, 64);
		R_BindFBO(tr.downScaleFBO_64x64);
		if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_64x64, GL_RGBA16F_ARB, 0);
		}
		else
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_64x64, GL_RGBA, 0);
		}
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.downScaleFBOImage_64x64->texnum, 0);
		R_CheckFBO(tr.downScaleFBO_64x64);

#if 0
		tr.downScaleFBO_16x16 = R_CreateFBO("_downScale_16x16", 16, 16);
		R_BindFBO(tr.downScaleFBO_16x16);
		if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_16x16, GL_RGBA16F_ARB, 0);
		}
		else
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_16x16, GL_RGBA, 0);
		}
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.downScaleFBOImage_16x16->texnum, 0);
		R_CheckFBO(tr.downScaleFBO_16x16);


		tr.downScaleFBO_4x4 = R_CreateFBO("_downScale_4x4", 4, 4);
		R_BindFBO(tr.downScaleFBO_4x4);
		if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_4x4, GL_RGBA16F_ARB, 0);
		}
		else
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_4x4, GL_RGBA, 0);
		}
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.downScaleFBOImage_4x4->texnum, 0);
		R_CheckFBO(tr.downScaleFBO_4x4);


		tr.downScaleFBO_1x1 = R_CreateFBO("_downScale_1x1", 1, 1);
		R_BindFBO(tr.downScaleFBO_1x1);
		if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_1x1, GL_RGBA16F_ARB, 0);
		}
		else
		{
			R_CreateFBOColorBuffer(tr.downScaleFBO_1x1, GL_RGBA, 0);
		}
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.downScaleFBOImage_1x1->texnum, 0);
		R_CheckFBO(tr.downScaleFBO_1x1);
#endif

		if (glConfig2.textureNPOTAvailable)
		{
			width  = glConfig.vidWidth * 0.25f;
			height = glConfig.vidHeight * 0.25f;
		}
		else
		{
			width  = NearestPowerOfTwo(glConfig.vidWidth * 0.25f);
			height = NearestPowerOfTwo(glConfig.vidHeight * 0.25f);
		}

		tr.contrastRenderFBO = R_CreateFBO("_contrastRender", width, height);
		R_BindFBO(tr.contrastRenderFBO);

		if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
		{
			R_CreateFBOColorBuffer(tr.contrastRenderFBO, GL_RGBA16F_ARB, 0);
		}
		else
		{
			R_CreateFBOColorBuffer(tr.contrastRenderFBO, GL_RGBA, 0);
		}
		R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.contrastRenderFBOImage->texnum, 0);

		R_CheckFBO(tr.contrastRenderFBO);


		for (i = 0; i < 2; i++)
		{
			tr.bloomRenderFBO[i] = R_CreateFBO(va("_bloomRender%d", i), width, height);
			R_BindFBO(tr.bloomRenderFBO[i]);

			if (r_hdrRendering->integer && glConfig2.textureFloatAvailable)
			{
				R_CreateFBOColorBuffer(tr.bloomRenderFBO[i], GL_RGBA16F_ARB, 0);
			}
			else
			{
				R_CreateFBOColorBuffer(tr.bloomRenderFBO[i], GL_RGBA, 0);
			}
			R_AttachFBOTexture2D(GL_TEXTURE_2D, tr.bloomRenderFBOImage[i]->texnum, 0);

			R_CheckFBO(tr.bloomRenderFBO[i]);
		}
	}

	GL_CheckErrors();

	R_BindNullFBO();
}
Пример #6
0
//
// This function is called when the window needs redrawing.
//
static void Display(void)
{
    int i;
    GLdouble p[16];
    GLdouble m[16];

    // Select correct buffer for this context.
    glDrawBuffer(GL_BACK);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the buffers for new frame.

    arglDispImage(gARTImage, &(gCparamLT->param), 1.0, gArglSettings);	// zoom = 1.0.
    gARTImage = NULL; // Invalidate image data.

    // Projection transformation.
    arglCameraFrustumRH(&(gCparamLT->param), VIEW_DISTANCE_MIN, VIEW_DISTANCE_MAX, p);
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixd(p);
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_DEPTH_TEST);

    // Viewing transformation.
    glLoadIdentity();
    // Lighting and geometry that moves with the camera should go here.
    // (I.e. must be specified before viewing transformations.)
    //none

    for (i = 0; i < gObjectDataCount; i++) {

        if ((gObjectData[i].visible != 0) && (gObjectData[i].vrml_id >= 0)) {

            // Calculate the camera position for the object and draw it.
            // Replace VIEW_SCALEFACTOR with 1.0 to make one drawing unit equal to 1.0 ARToolKit units (usually millimeters).
            arglCameraViewRH(gObjectData[i].trans, m, VIEW_SCALEFACTOR);
            glLoadMatrixd(m);

            // All lighting and geometry to be drawn relative to the marker goes here.
            //ARLOGe("About to draw object %i\n", i);
            arVrmlDraw(gObjectData[i].vrml_id);
        }
    }

    // Any 2D overlays go here.
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, (GLdouble)windowWidth, 0, (GLdouble)windowHeight, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glDisable(GL_LIGHTING);
    glDisable(GL_DEPTH_TEST);

    //
    // Draw help text and mode.
    //
    if (gShowMode) {
        printMode();
    }
    if (gShowHelp) {
        if (gShowHelp == 1) {
            printHelpKeys();
        }
    }

    glutSwapBuffers();
}
Пример #7
0
void GLGSRender::ExecCMD()
{
	if(!LoadProgram())
	{
		ConLog.Error("LoadProgram failed.");
		Emu.Pause();
		return;
	}

	if(!m_fbo.IsCreated() || RSXThread::m_width != last_width || RSXThread::m_height != last_height || last_depth_format != m_surface_depth_format)
	{
		ConLog.Warning("New FBO (%dx%d)", RSXThread::m_width, RSXThread::m_height);
		last_width = RSXThread::m_width;
		last_height = RSXThread::m_height;
		last_depth_format = m_surface_depth_format;

		m_fbo.Create();
		checkForGlError("m_fbo.Create");
		m_fbo.Bind();

		m_rbo.Create(4 + 1);
		checkForGlError("m_rbo.Create");

		for(int i=0; i<4; ++i)
		{
			m_rbo.Bind(i);
			m_rbo.Storage(GL_RGBA, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_RGBA)");
		}

		m_rbo.Bind(4);

		switch(m_surface_depth_format)
		{
		case 1:
			m_rbo.Storage(GL_DEPTH_COMPONENT16, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH_COMPONENT16)");
		break;

		case 2:
			m_rbo.Storage(GL_DEPTH24_STENCIL8, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH24_STENCIL8)");
		break;

		default:
			ConLog.Error("Bad depth format! (%d)", m_surface_depth_format);
			assert(0);
		break;
		}

		for(int i=0; i<4; ++i)
		{
			m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT0 + i, m_rbo.GetId(i));
			checkForGlError(wxString::Format("m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT%d)", i));
		}

		m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT, m_rbo.GetId(4));
		checkForGlError("m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT)");

		if(m_surface_depth_format == 2)
		{
			m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT, m_rbo.GetId(4));
			checkForGlError("m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT)");
		}
	}

	if(!m_set_surface_clip_horizontal)
	{
		m_surface_clip_x = 0;
		m_surface_clip_w = RSXThread::m_width;
	}

	if(!m_set_surface_clip_vertical)
	{
		m_surface_clip_y = 0;
		m_surface_clip_h = RSXThread::m_height;
	}
		
	m_fbo.Bind();
	if(Ini.GSDumpDepthBuffer.GetValue())
		WriteDepthBuffer();
	static const GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };

	switch(m_surface_colour_target)
	{
	case 0x0:
		break;

	case 0x1:
		glDrawBuffer(draw_buffers[0]);
	break;

	case 0x2:
		glDrawBuffer(draw_buffers[1]);
	break;

	case 0x13:
		glDrawBuffers(2, draw_buffers);
	break;

	case 0x17:
		glDrawBuffers(3, draw_buffers);
	break;

	case 0x1f:
		glDrawBuffers(4, draw_buffers);
	break;

	default:
		ConLog.Error("Bad surface colour target: %d", m_surface_colour_target);
	break;
	}

	if(m_set_color_mask)
	{
		glColorMask(m_color_mask_r, m_color_mask_g, m_color_mask_b, m_color_mask_a);
		checkForGlError("glColorMask");
	}

	if(m_set_viewport_horizontal && m_set_viewport_vertical)
	{
		glViewport(m_viewport_x, RSXThread::m_height-m_viewport_y-m_viewport_h, m_viewport_w, m_viewport_h);
		checkForGlError("glViewport");
	}

	if(m_set_scissor_horizontal && m_set_scissor_vertical)
	{
		glScissor(m_scissor_x, RSXThread::m_height-m_scissor_y-m_scissor_h, m_scissor_w, m_scissor_h);
		checkForGlError("glScissor");
	}

	if(m_clear_surface_mask)
	{
		GLbitfield f = 0;

		if (m_clear_surface_mask & 0x1)
		{
			glClearDepth(m_clear_surface_z / (float)0xffffff);

			f |= GL_DEPTH_BUFFER_BIT;
		}

		if (m_clear_surface_mask & 0x2)
		{
			glClearStencil(m_clear_surface_s);

			f |= GL_STENCIL_BUFFER_BIT;
		}

		if (m_clear_surface_mask & 0xF0)
		{
			glClearColor(
				m_clear_surface_color_r / 255.0f,
				m_clear_surface_color_g / 255.0f,
				m_clear_surface_color_b / 255.0f,
				m_clear_surface_color_a / 255.0f);

			f |= GL_COLOR_BUFFER_BIT;
		}

		glClear(f);
	}

	if(m_set_front_polygon_mode)
	{
		glPolygonMode(GL_FRONT, m_front_polygon_mode);
		checkForGlError("glPolygonMode");
	}

	Enable(m_depth_test_enable, GL_DEPTH_TEST);
	Enable(m_set_alpha_test, GL_ALPHA_TEST);
	Enable(m_set_depth_bounds_test, GL_DEPTH_BOUNDS_TEST_EXT);
	Enable(m_set_blend, GL_BLEND);
	Enable(m_set_logic_op, GL_LOGIC_OP);
	Enable(m_set_cull_face_enable, GL_CULL_FACE);
	Enable(m_set_dither, GL_DITHER);
	Enable(m_set_stencil_test, GL_STENCIL_TEST);
	Enable(m_set_line_smooth, GL_LINE_SMOOTH);
	Enable(m_set_poly_smooth, GL_POLYGON_SMOOTH);
	Enable(m_set_poly_offset_fill, GL_POLYGON_OFFSET_FILL);
	Enable(m_set_poly_offset_line, GL_POLYGON_OFFSET_LINE);
	Enable(m_set_poly_offset_point, GL_POLYGON_OFFSET_POINT);
	//Enable(m_set_restart_index, GL_PRIMITIVE_RESTART); //Requires OpenGL 3.1+

	if(m_set_clip_plane)
	{
		Enable(m_clip_plane_0, GL_CLIP_PLANE0);
		Enable(m_clip_plane_1, GL_CLIP_PLANE1);
		Enable(m_clip_plane_2, GL_CLIP_PLANE2);
		Enable(m_clip_plane_3, GL_CLIP_PLANE3);
		Enable(m_clip_plane_4, GL_CLIP_PLANE4);
		Enable(m_clip_plane_5, GL_CLIP_PLANE5);

		checkForGlError("m_set_clip_plane");
	}

	checkForGlError("glEnable");

	if(m_set_two_sided_stencil_test_enable)
	{
		if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass)
		{
			glStencilOpSeparate(GL_FRONT, m_stencil_fail, m_stencil_zfail, m_stencil_zpass);
			checkForGlError("glStencilOpSeparate");
		}

		if(m_set_stencil_mask)
		{
			glStencilMaskSeparate(GL_FRONT, m_stencil_mask);
			checkForGlError("glStencilMaskSeparate");
		}

		if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask)
		{
			glStencilFuncSeparate(GL_FRONT, m_stencil_func, m_stencil_func_ref, m_stencil_func_mask);
			checkForGlError("glStencilFuncSeparate");
		}

		if(m_set_back_stencil_fail && m_set_back_stencil_zfail && m_set_back_stencil_zpass)
		{
			glStencilOpSeparate(GL_BACK, m_back_stencil_fail, m_back_stencil_zfail, m_back_stencil_zpass);
			checkForGlError("glStencilOpSeparate(GL_BACK)");
		}

		if(m_set_back_stencil_mask)
		{
			glStencilMaskSeparate(GL_BACK, m_back_stencil_mask);
			checkForGlError("glStencilMaskSeparate(GL_BACK)");
		}

		if(m_set_back_stencil_func && m_set_back_stencil_func_ref && m_set_back_stencil_func_mask)
		{
			glStencilFuncSeparate(GL_BACK, m_back_stencil_func, m_back_stencil_func_ref, m_back_stencil_func_mask);
			checkForGlError("glStencilFuncSeparate(GL_BACK)");
		}
	}
	else
	{
		if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass)
		{
			glStencilOp(m_stencil_fail, m_stencil_zfail, m_stencil_zpass);
			checkForGlError("glStencilOp");
		}

		if(m_set_stencil_mask)
		{
			glStencilMask(m_stencil_mask);
			checkForGlError("glStencilMask");
		}

		if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask)
		{
			glStencilFunc(m_stencil_func, m_stencil_func_ref, m_stencil_func_mask);
			checkForGlError("glStencilFunc");
		}
	}

	if(m_set_shade_mode)
	{
		glShadeModel(m_shade_mode);
		checkForGlError("glShadeModel");
	}

	if(m_set_depth_mask)
	{
		glDepthMask(m_depth_mask);
		checkForGlError("glDepthMask");
	}

	if(m_set_depth_func)
	{
		glDepthFunc(m_depth_func);
		//ConLog.Warning("glDepthFunc(0x%x)", m_depth_func);
		checkForGlError("glDepthFunc");
	}

	if(m_set_depth_bounds)
	{
		//ConLog.Warning("glDepthBounds(%f, %f)", m_depth_bounds_min, m_depth_bounds_max);
		glDepthBounds(m_depth_bounds_min, m_depth_bounds_max);
		checkForGlError("glDepthBounds");
	}

	if(m_set_clip)
	{
		//ConLog.Warning("glDepthRangef(%f, %f)", m_clip_min, m_clip_max);
		glDepthRangef(m_clip_min, m_clip_max);
		checkForGlError("glDepthRangef");
	}

	if(m_set_line_width)
	{
		glLineWidth(m_line_width / 255.f);
		checkForGlError("glLineWidth");
	}

	if(m_set_blend_equation)
	{
		glBlendEquationSeparate(m_blend_equation_rgb, m_blend_equation_alpha);
		checkForGlError("glBlendEquationSeparate");
	}

	if(m_set_blend_sfactor && m_set_blend_dfactor)
	{
		glBlendFuncSeparate(m_blend_sfactor_rgb, m_blend_dfactor_rgb, m_blend_sfactor_alpha, m_blend_dfactor_alpha);
		checkForGlError("glBlendFuncSeparate");
	}

	if(m_set_blend_color)
	{
		glBlendColor(m_blend_color_r, m_blend_color_g, m_blend_color_b, m_blend_color_a);
		checkForGlError("glBlendColor");
	}

	if(m_set_cull_face)
	{
		glCullFace(m_cull_face);
		checkForGlError("glCullFace");
	}

	if(m_set_alpha_func && m_set_alpha_ref)
	{
		glAlphaFunc(m_alpha_func, m_alpha_ref);
		checkForGlError("glAlphaFunc");
	}

	if(m_set_fog_mode)
	{
		glFogi(GL_FOG_MODE, m_fog_mode);
		checkForGlError("glFogi(GL_FOG_MODE)");
	}

	if(m_set_fog_params)
	{
		glFogf(GL_FOG_START, m_fog_param0);
		checkForGlError("glFogf(GL_FOG_START)");
		glFogf(GL_FOG_END, m_fog_param1);
		checkForGlError("glFogf(GL_FOG_END)");
	}

	if(m_set_restart_index)
	{
		ConLog.Warning("m_set_restart_index requires glPrimitiveRestartIndex()");
		//glPrimitiveRestartIndex(m_restart_index); //Requires OpenGL 3.1+
		//checkForGlError("glPrimitiveRestartIndex");
	}

	if(m_indexed_array.m_count && m_draw_array_count)
	{
		ConLog.Warning("m_indexed_array.m_count && draw_array_count");
	}

	for(u32 i=0; i<m_textures_count; ++i)
	{
		if(!m_textures[i].IsEnabled()) continue;

		glActiveTexture(GL_TEXTURE0 + i);
		checkForGlError("glActiveTexture");
		m_gl_textures[i].Create();
		m_gl_textures[i].Bind();
		checkForGlError(wxString::Format("m_gl_textures[%d].Bind", i));
		m_program.SetTex(i);
		m_gl_textures[i].Init(m_textures[i]);
		checkForGlError(wxString::Format("m_gl_textures[%d].Init", i));
	}

	m_vao.Bind();
	if(m_indexed_array.m_count)
	{
		LoadVertexData(m_indexed_array.index_min, m_indexed_array.index_max - m_indexed_array.index_min + 1);
	}

	EnableVertexData(m_indexed_array.m_count ? true : false);

	InitVertexData();
	InitFragmentData();

	if(m_indexed_array.m_count)
	{
		switch(m_indexed_array.m_type)
		{
		case 0:
			glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_INT, nullptr);
			checkForGlError("glDrawElements #4");
		break;

		case 1:
			glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_SHORT, nullptr);
			checkForGlError("glDrawElements #2");
		break;

		default:
			ConLog.Error("Bad indexed array type (%d)", m_indexed_array.m_type);
		break;
		}

		DisableVertexData();
		m_indexed_array.Reset();
	}

	if(m_draw_array_count)
	{
		//ConLog.Warning("glDrawArrays(%d,%d,%d)", m_draw_mode - 1, m_draw_array_first, m_draw_array_count);
		glDrawArrays(m_draw_mode - 1, 0, m_draw_array_count);
		checkForGlError("glDrawArrays");
		DisableVertexData();
	}

	if(Ini.GSDumpColorBuffers.GetValue())
		WriteBuffers();
}
Пример #8
0
ENTRYPOINT void init_hypertorus(ModeInfo *mi)
{
  hypertorusstruct *hp;

  MI_INIT(mi, hyper, NULL);
  hp = &hyper[MI_SCREEN(mi)];

  
  hp->trackballs[0] = gltrackball_init(True);
  hp->trackballs[1] = gltrackball_init(True);
  hp->current_trackball = 0;
  hp->button_pressed = False;

  /* Set the display mode. */
  if (!strcasecmp(mode,"wireframe") || !strcasecmp(mode,"0"))
  {
    display_mode = DISP_WIREFRAME;
  }
  else if (!strcasecmp(mode,"surface") || !strcasecmp(mode,"1"))
  {
    display_mode = DISP_SURFACE;
  }
  else if (!strcasecmp(mode,"transparent") || !strcasecmp(mode,"2"))
  {
    display_mode = DISP_TRANSPARENT;
  }
  else
  {
    display_mode = DISP_SURFACE;
  }

  /* Set the appearance. */
  if (!strcasecmp(appear,"solid") || !strcasecmp(appear,"0"))
  {
    appearance = APPEARANCE_SOLID;
  }
  else if (!strcasecmp(appear,"bands") || !strcasecmp(appear,"1"))
  {
    appearance = APPEARANCE_BANDS;
    num_spirals = 0;
  }
  else if (!strcasecmp(appear,"spirals-1") || !strcasecmp(appear,"3"))
  {
    appearance = APPEARANCE_SPIRALS;
    num_spirals = 1;
  }
  else if (!strcasecmp(appear,"spirals-2") || !strcasecmp(appear,"4"))
  {
    appearance = APPEARANCE_SPIRALS;
    num_spirals = 2;
  }
  else if (!strcasecmp(appear,"spirals-4") || !strcasecmp(appear,"5"))
  {
    appearance = APPEARANCE_SPIRALS;
    num_spirals = 4;
  }
  else if (!strcasecmp(appear,"spirals-8") || !strcasecmp(appear,"6"))
  {
    appearance = APPEARANCE_SPIRALS;
    num_spirals = 8;
  }
  else if (!strcasecmp(appear,"spirals-16") || !strcasecmp(appear,"7"))
  {
    appearance = APPEARANCE_SPIRALS;
    num_spirals = 16;
  }
  else
  {
    appearance = APPEARANCE_BANDS;
    num_spirals = 0;
  }

  /* Set the color mode. */
  if (!strcasecmp(color_mode,"twosided"))
  {
    colors = COLORS_TWOSIDED;
  }
  else if (!strcasecmp(color_mode,"colorwheel"))
  {
    colors = COLORS_COLORWHEEL;
  }
  else
  {
    colors = COLORS_COLORWHEEL;
  }

  /* Set the 3d projection mode. */
  if (!strcasecmp(proj_3d,"perspective") || !strcasecmp(proj_3d,"0"))
  {
    projection_3d = DISP_3D_PERSPECTIVE;
  }
  else if (!strcasecmp(proj_3d,"orthographic") || !strcasecmp(proj_3d,"1"))
  {
    projection_3d = DISP_3D_ORTHOGRAPHIC;
  }
  else
  {
    projection_3d = DISP_3D_PERSPECTIVE;
  }

  /* Set the 4d projection mode. */
  if (!strcasecmp(proj_4d,"perspective") || !strcasecmp(proj_4d,"0"))
  {
    projection_4d = DISP_4D_PERSPECTIVE;
  }
  else if (!strcasecmp(proj_4d,"orthographic") || !strcasecmp(proj_4d,"1"))
  {
    projection_4d = DISP_4D_ORTHOGRAPHIC;
  }
  else
  {
    projection_4d = DISP_4D_PERSPECTIVE;
  }

  /* make multiple screens rotate at slightly different rates. */
  hp->speed_scale = 0.9 + frand(0.3);

  if ((hp->glx_context = init_GL(mi)) != NULL)
  {
    reshape_hypertorus(mi,MI_WIDTH(mi),MI_HEIGHT(mi));
    glDrawBuffer(GL_BACK);
    init(mi);
  }
  else
  {
    MI_CLEARWINDOW(mi);
  }
}
Пример #9
0
static void Draw( void )
{

   /* draw to user framebuffer */
   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, MyFB);
   glDrawBuffer(GL_COLOR_ATTACHMENT1_EXT);
   glReadBuffer(GL_COLOR_ATTACHMENT1_EXT);

   
   glViewport(0, 0, Width, Height);
   CheckError();

   glClearColor(0.5, 0.5, 1.0, 0.0);
   glClear(GL_COLOR_BUFFER_BIT);
   CheckError();

   if (0) {
      glBegin(GL_TRIANGLES);
      glColor3f(0,0,.7); 
      glVertex3f( 0.9, -0.9, -30.0);
      glColor3f(.8,0,0); 
      glVertex3f( 0.9,  0.9, -30.0);
      glColor3f(0,.9,0); 
      glVertex3f(-0.9,  0.0, -30.0);
      glEnd();
   }

   {
      GLubyte *buffer = malloc(Width * Height * 4);

      /* read from user framebuffer */
      glReadPixels(0, 0, Width-60, Height-60, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
      CheckError();

      /* draw to window */
      glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
      glViewport(0, 0, Width, Height);

      /* Try to clear the window, but will overwrite:
       */
      glClearColor(0.8, 0.8, 0, 0.0);
      glClear(GL_COLOR_BUFFER_BIT);

      glWindowPos2iARB(30, 30);
      glDrawPixels(Width-60, Height-60, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
      
      free(buffer);
   }
   
   /* Bind normal framebuffer */
   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
   glViewport(0, 0, Width, Height);

   if (0) {
      glBegin(GL_TRIANGLES);
      glColor3f(0,.7,0); 
      glVertex3f( 0.5, -0.5, -30.0);
      glColor3f(0,0,.8); 
      glVertex3f( 0.5,  0.5, -30.0);
      glColor3f(.9,0,0); 
      glVertex3f(-0.5,  0.0, -30.0);
      glEnd();
   }

   if (doubleBuffer)
      glutSwapBuffers();
   else
      glFinish();

   CheckError();
}
Пример #10
0
/*!
* \brief
* Display function to be called from main which draws on the screen
* 
* 
* The function firstly defines the viewport and the viewing way according to the state of the game and then draws the board
* 
* \remarks
* States are handled through this function, can be used for split screen 
* 
*/
void display()
{
	switch(state)
	{
	case STATE_BOARD_PLACE_STRIKER : glViewport (0, 0, (GLsizei) w, (GLsizei) h);
		glMatrixMode (GL_PROJECTION);
		glLoadIdentity ();
		glOrtho(-(BOARD_BREADTH /2 + 4 * BOARD_BOUNDARY_BREADTH) /100, (BOARD_BREADTH /2 + 4 * BOARD_BOUNDARY_BREADTH) /100,-(BOARD_BREADTH /2 + 4 * BOARD_BOUNDARY_BREADTH) /100,(BOARD_BREADTH /2 + 4 * BOARD_BOUNDARY_BREADTH) /100, -1, 10);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glDrawBuffer(GL_BACK);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		//glPushMatrix();
		////glScalef(10,10,0);
		//glColor3f(1,1,1);
		//glRasterPos3f(0, 0,1);
		//for (char *c="Press Enter Or Click to Start Game"; *c != '\0'; c++)
		//{
		//	//glutStrokeCharacter(GLUT_STROKE_ROMAN, *c);

		//	glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);
		//}
		//glPopMatrix();
		glPushMatrix();
		boardDisplay();
		glPopMatrix();
		glFlush();
		glutSwapBuffers();
		break;

	case STATE_BOARD_SIMULATION : 
		glViewport (0, 0, (GLsizei) w, (GLsizei) h);
		glMatrixMode (GL_PROJECTION);
		glLoadIdentity ();
		gluPerspective(65.0, (GLfloat) w/(GLfloat) h, 1.0, 500.0);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		gluLookAt (0.0, -2.0,8.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
		glDrawBuffer(GL_BACK);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		boardDisplay();

		glFlush();
		glutSwapBuffers();
		break;

	case STATE_BOARD_STRIKER_DIRECTION :
		glViewport (0, 0, (GLsizei) w, (GLsizei) h);
		glMatrixMode (GL_PROJECTION);
		glLoadIdentity ();
		gluPerspective(65.0, (GLfloat) w/(GLfloat) h, 1.0, 500.0);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		gluLookAt (0.0, -2.0,6.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
		glDrawBuffer(GL_BACK);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		boardDisplay();
		//gluLookAt (15.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
		glFlush();
		glutSwapBuffers();
		break;

	case STATE_BOARD_STRIKER_POWER :

		glViewport (0, 0, (GLsizei) w, (GLsizei) h);
		glMatrixMode (GL_PROJECTION);
		glLoadIdentity ();
		gluPerspective(65.0, (GLfloat) w/(GLfloat) h, 1.0, 500.0);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		gluLookAt (0.0, -1.0,10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
		glDrawBuffer(GL_BACK);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glPushMatrix();//code for power bar
		/**/
		if(strikerSpeed >= 5)
		{   //setting speed of the striker 
			strikerSpeed = 0;
			//playing sound again form starting 
			alSourcePlay(AudioSource[SOUND_POWER_BAR]);
		}
		else strikerSpeed += 0.04;

		glTranslatef(5.5,-5+(strikerSpeed),0);
		createBoardBoundary(.5,strikerSpeed*2,1);
		glPopMatrix();//end code for power bar

		boardDisplay();
		//gluLookAt (15.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
		glFlush();
		glutSwapBuffers();
		break;
	}

}
Пример #11
0
void MovableLight::render_shadow_map(const Camera &camera, std::function<void()> render_geometry) {
	if(shadow_map.fbo == nullptr) shadow_map.create_fbo();

	float near, far;
	near = camera.near();
	far = camera.far() * shadowmap_far_factor;

	glm::mat4 view_matrix, projection_matrix;

	switch(type) {
		case DIRECTIONAL_LIGHT:
			{
				glm::vec3 lightv[3];
				lightv[0] = glm::normalize(position());

				glm::vec3 hint;
				if(abs(lightv[0].x) <= abs(lightv[0].y)) {
					if(abs(lightv[0].x) <= abs(lightv[0].z)) {
						hint = glm::vec3(1.f, 0.f, 0.f);
					} else {
						hint = glm::vec3(0.f, 0.f, 1.f);
					}
				} else {
					if(abs(lightv[0].y) <= abs(lightv[0].z)) {
						hint = glm::vec3(0.f, 1.f, 0.f);
					} else {
						hint = glm::vec3(0.f, 0.f, 1.f);
					}
				}

				lightv[1] = glm::normalize(glm::cross(lightv[0], hint));
				lightv[2] = glm::normalize(glm::cross(lightv[1], lightv[0]));

				glm::vec3 frustrum_corners[8];
				glm::vec3 frustrum_center = calculateFrustrumData(camera, near, far, frustrum_corners);

				float min_v[3] = { FLT_MAX, FLT_MAX, FLT_MAX };
				float max_v[3] = { -FLT_MAX, -FLT_MAX, -FLT_MAX };
				for(glm::vec3 &corner : frustrum_corners) {
					for(int i=0; i < 3; ++i) {
						float l = glm::dot(corner, lightv[i]);
						if(l < min_v[i]) min_v[i] = l;
						if(l > max_v[i]) max_v[i] = l;
					}
				}
				float center[3];
				for(int i=0; i < 3; ++i) {
					center[i] = glm::dot(frustrum_center, lightv[i]);
					min_v[i] -= 5.f;
					max_v[i] += 5.f;
				}

				glm::vec3 eye = frustrum_center + lightv[0] * (min_v[0] - center[0]);
				float left, right, bottom, top, far_dist;

				left = min_v[1];
				right = max_v[1];
				bottom = min_v[2];
				top = max_v[2];
				far_dist = max_v[0] - min_v[0];

				float halfw, halfh;
				halfw = (right - left)/2.f;
				halfh = (top - bottom)/2.f;

				view_matrix = glm::lookAt(eye, frustrum_center, lightv[2]);
				projection_matrix = glm::ortho(-halfw, halfw, halfh, -halfh, 0.f, far_dist);

				/*glm::vec4 test4 = projection_matrix * view_matrix * glm::vec4(frustrum_center, 1.f);
				glm::vec3 test = glm::vec3(test4.x, test4.y, test4.z) / test4.w;

				printf("%f, %f, %f\n", test.x, test.y, test.z);*/

				break;
			}
		case POINT_LIGHT:
			{
				view_matrix = glm::lookAt(position(), position() + local_z(), local_y());
				projection_matrix = glm::perspective(90.f, 1.f, 0.1f, 100.f);
				break;
			}
		default:
			printf("Shadowmaps are only implemented for directional lights at the moment\n");
			util_abort();
	}

	shadow_map.matrix = glm::translate(glm::mat4(1.f), glm::vec3(0.5f))
		* glm::scale(glm::mat4(1.f),glm::vec3(0.5f))
		* projection_matrix * view_matrix;

	Shader::upload_projection_view_matrices(projection_matrix, view_matrix);

	shadow_map.fbo->bind();

	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	shaders[SHADER_PASSTHRU]->bind();

	glDrawBuffer(GL_NONE);
	glReadBuffer(GL_NONE);

	render_geometry();

	shadow_map.fbo->unbind();
}
void
wesTriangleRateBenchmark(AppState *as)
{
	int startTime, endTime;
	size_t totalTris=0, totalVerts=0;
	float elapsedTimeMS, trisPerSecond, vertsPerSecond;
	Vertex2D *baseVerts;
	Color3D *baseColors;
	Vertex3D *baseNormals;
	Vertex2D *baseTCs;
	GLuint trianglesListIndx = 0;

	int nVertsPerAxis;
	int nFrames=0;

	Vertex2D *dispatchVerts=NULL;
	Color3D *dispatchColors=NULL;
	Vertex3D *dispatchNormals=NULL;
	Vertex2D *dispatchTCs=NULL;
	GLuint   *dispatchIndices=NULL;
	int dispatchVertexCount, dispatchTriangles;

	int screenWidth = as->imgWidth;
	GLfloat r=screenWidth;
	int screenHeight = as->imgHeight;
	int testDurationMS = as->testDurationMS;
	size_t triangleLimit = as->triangleLimit;
	double triangleAreaPixels = as->triangleAreaInPixels;
	int lighting=as->enableLighting;
	int colorMaterial = as->enableColorMaterial;
	int texturingEnabled = (as->textureSize > 0) ? 1 : 0;
	int textureSize = as->textureSize;


	/* 
	 * Objective(s): 
	 * 1. Want triangles with a specified area (e.g., 8sq pixels) for the
	 * purpose of generating a graphics load with reasonably precise
	 * characteristics .
	 * 2. Want triangles to *all* remain on-screen so that triangle rate
	 * reflects the cost of rendering visible triangles/fragments.
	 *
	 * Approach:
	 * 1. build a base mesh of vertices. This set of verts is positioned
	 * so that it will remain entirely within the view frustum no matter
	 * how we rotate it (in 2D)
	 * 2. dispatch off the mesh vertices as disjoint triangles using
	 * vertex arrays. This approach is not the most efficient way to
	 * represent densely packed triangles, but has a couple of benefits:
	 * - It allows us to easily set the maximum number of triangles per
	 *   frame to be dispatched off to the renderer w/o having to resort
	 *   to tricks like inserting degenerate triangles in strips to connect
	 *   up two disjoint strips.
	 * - It allows us to glDrawArrays rather than glDrawElements. The latter
	 *   uses one level of indirection, and will be less efficient.
	 * - In the end, we care about vertex rate, not triangle rate.
	 *
	 * An early version of this code used the glDrawElements with indices.
	 * Rather than insert compile-time switches, this old code is simply
	 * cut-n-pasted and commented out at the end of this file.
	 */

	/* Make sure we are drawing to the front buffer */
	glDrawBuffer(GL_FRONT);
	glDisable(GL_DEPTH_TEST);

	/* Clear the screen */
	glClear(GL_COLOR_BUFFER_BIT);  

	if (as->outlineMode != 0)
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);       
	else
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	/* Load identities */
	glMatrixMode( GL_PROJECTION );
	glPushMatrix();
	glLoadIdentity( );

	glMatrixMode( GL_MODELVIEW );
	glPushMatrix();
	glLoadIdentity();

	/* change range from -1..1 to 0..[screenWidth, screenHeight] */
	glTranslatef(-1.0, -1.0, 0.0);
	glScalef(2.0/r, 2.0/r, 1.0F);


	if (lighting)
	{
		/* turn on OpenGL lighting stuff */
		GLfloat lightPosition[] = {(float)screenWidth*0.5F, (float)screenHeight*0.5F, 200.0F, 1.0F};
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

		if (colorMaterial)
		{
			glEnable(GL_COLOR_MATERIAL);
			glColorMaterial(GL_FRONT, GL_DIFFUSE);
		}
		/* just use OpenGL's default light values: directional light source */
	}
	else
	{
		glDisable(GL_LIGHTING);
		glDisable(GL_COLOR_MATERIAL);
	}

	if (texturingEnabled)
	{
		buildAndDownloadTexture(textureSize);
		glEnable(GL_TEXTURE_2D);
		glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
	}
	else
		glDisable(GL_TEXTURE_2D);

	/* build the base quadmesh vertex array */
	buildBaseArrays(triangleAreaPixels, as->imgWidth, as->imgHeight,
			&nVertsPerAxis, 
			&baseVerts, &baseColors, &baseNormals, &baseTCs);

	/* now, repackage that information into bundles suitable for submission
to GL using the specified primitive type */
	if (as->triangleType == DISJOINT_TRIANGLES)
	{
		int triangleLimit;

		if ((as->triangleLimit*3) > as->vertexBufLimit)
			triangleLimit = as->vertexBufLimit/3;
		else
			triangleLimit = as->triangleLimit;

		buildDisjointTriangleArrays(nVertsPerAxis,
				triangleLimit,
				&dispatchTriangles,
				&dispatchVertexCount,
				baseVerts, baseColors, 
				baseNormals, baseTCs,
				&dispatchVerts,
				&dispatchColors,
				&dispatchNormals,
				&dispatchTCs);
		as->computedVertsPerArrayCall = dispatchVertexCount;
		as->computedIndicesPerArrayCall = 0;
	}
	else if (as->triangleType == TRIANGLE_STRIPS)
	{

		if ((as->triangleLimit+2) > as->vertexBufLimit)
			triangleLimit = as->vertexBufLimit-2;
		else
			triangleLimit = as->triangleLimit;


		buildTriangleStripArrays(nVertsPerAxis,
				triangleLimit,
				&dispatchTriangles,
				&dispatchVertexCount,
				baseVerts, baseColors, 
				baseNormals, baseTCs,
				&dispatchVerts,
				&dispatchColors,
				&dispatchNormals,
				&dispatchTCs);
		as->computedVertsPerArrayCall = dispatchVertexCount;
		as->computedIndicesPerArrayCall = 0;
	}
	else if (as->triangleType == INDEXED_DISJOINT_TRIANGLES)
	{
		if ((as->triangleLimit*3) > as->vertexBufLimit)
			triangleLimit = as->vertexBufLimit/3;
		else
			triangleLimit = as->triangleLimit;

		buildIndexedDisjointTriangleArrays(nVertsPerAxis,
				triangleLimit,
				&dispatchTriangles,
				&dispatchVertexCount,
				baseVerts, baseColors, 
				baseNormals, baseTCs,
				&dispatchVerts,
				&dispatchColors,
				&dispatchNormals,
				&dispatchTCs,
				&dispatchIndices);
		as->computedVertsPerArrayCall = (nVertsPerAxis+1)*(nVertsPerAxis+1);
		as->computedIndicesPerArrayCall = dispatchVertexCount;
	}
	else if (as->triangleType == INDEXED_TRIANGLE_STRIPS)
	{

		if ((as->triangleLimit+2) > as->vertexBufLimit)
			triangleLimit = as->vertexBufLimit-2;
		else
			triangleLimit = as->triangleLimit;

		buildIndexedTriangleStripArrays(nVertsPerAxis,
				triangleLimit,
				&dispatchTriangles,
				&dispatchVertexCount,
				baseVerts, baseColors, 
				baseNormals, baseTCs,
				&dispatchVerts,
				&dispatchColors,
				&dispatchNormals,
				&dispatchTCs,
				&dispatchIndices);
		as->computedVertsPerArrayCall = (nVertsPerAxis+1)*(nVertsPerAxis+1);
		as->computedIndicesPerArrayCall = dispatchVertexCount;
	}


	/* Set up the pointers */
	glVertexPointer(2, GL_FLOAT, 0, (const GLvoid *)dispatchVerts);
	glEnableClientState(GL_VERTEX_ARRAY);
	glColorPointer(3, GL_FLOAT, 0, (const GLvoid *)dispatchColors);
	glEnableClientState(GL_COLOR_ARRAY);

	if (lighting)
	{
		glNormalPointer(GL_FLOAT, 0, (const GLvoid *)dispatchNormals);
		glEnableClientState(GL_NORMAL_ARRAY);
	}

	if (texturingEnabled)
	{
		glTexCoordPointer(2, GL_FLOAT, 0, (const GLvoid *)dispatchTCs);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	}

	glFinish();                 /* make sure all setup is finished */
	startTime = endTime = glutGet(GLUT_ELAPSED_TIME);

	while ((endTime - startTime) < testDurationMS)
	{

		int buildingList=0;

		if (as->clearPerFrame != 0)
			glClear(GL_COLOR_BUFFER_BIT); /* tmp for debug */

#if SCREENSHOT_MODE
		/* screenshot mode won't work with -retained */
		/* Clear the screen */
		glClear(GL_COLOR_BUFFER_BIT); 
		glClear(GL_COLOR_BUFFER_BIT); 
		glDrawArrays(GL_TRIANGLES, 0, dispatchVertexCount);
		glDrawArrays(GL_TRIANGLES, 0, dispatchVertexCount);
		fprintf(stderr," You have screenshot mode enabled! \n");
		fflush(stderr);
		sleep(5);
		break;
#endif


		if (as->retainedModeEnabled != 0)
		{
			if (trianglesListIndx == 0) /* no list yet, build one */
			{
				trianglesListIndx = glGenLists(1);
				/*              glNewList(trianglesListIndx, GL_COMPILE_AND_EXECUTE); */
				glNewList(trianglesListIndx, GL_COMPILE);
				buildingList = 1;
			}
			else
				glCallList(trianglesListIndx);
		}

		if ((buildingList == 0) || (as->retainedModeEnabled != 0))
		{
			switch (as->triangleType)
			{
			case DISJOINT_TRIANGLES:
				glDrawArrays(GL_TRIANGLES, 0, dispatchVertexCount);
				break;
			case TRIANGLE_STRIPS:
				glDrawArrays(GL_TRIANGLE_STRIP, 0, dispatchVertexCount);
				break;
			case INDEXED_DISJOINT_TRIANGLES:
				glDrawElements(GL_TRIANGLES, dispatchVertexCount, GL_UNSIGNED_INT, dispatchIndices);
				break;
			case INDEXED_TRIANGLE_STRIPS:
				glDrawElements(GL_TRIANGLE_STRIP, dispatchVertexCount, GL_UNSIGNED_INT, dispatchIndices);
				break;
			default:
				break;
			}
		}

		glTranslatef(r/2.0, r/2.0, 0.0F);
		glRotatef(0.01F, 0.0F, 0.0F, 1.0F);
		glTranslatef(-r/2.0, -r/2.0, 0.0F);

		if (buildingList == 1)
		{
			glEndList();
			glCallList(trianglesListIndx); 

			/* cheat - reset the clock to eliminate the time required
					   for creating the display list from the frame rate computation */
			startTime = endTime = glutGet(GLUT_ELAPSED_TIME);
		}

		endTime = glutGet(GLUT_ELAPSED_TIME);

		nFrames++;
		totalTris += dispatchTriangles;
		totalVerts += as->computedVertsPerArrayCall;

	}
	/* TODO: Ask about how to get it to draw */

	glFinish();

	endTime = glutGet(GLUT_ELAPSED_TIME);

	/* Restore the gl stack */
	glMatrixMode( GL_MODELVIEW );
	glPopMatrix();

	glMatrixMode( GL_PROJECTION );
	glPopMatrix();

	/* Before printing the results, make sure we didn't have
	 ** any GL related errors. */
	check_gl_errors();

	/* the pause that refreshes -- */
#ifdef _WIN32
	Sleep(250);
#else  
	usleep(250000);
#endif  

	elapsedTimeMS = endTime - startTime;
	float elapsedTimeS = elapsedTimeMS / 1000;
	printf("Elapsed Time: %f s\n", elapsedTimeS);
	printf("Total Triangles: %d\n", (int) totalTris);
	printf("Total Verticies: %d\n", (int) totalVerts);
	printf("Frames per Second (FPS): %f\n", nFrames / elapsedTimeS);


	/*
	 * myAppState.appName,
	 * myAppState.triangleAreaInPixels,
	 * myAppState.computedMTrisPerSecond,
	 * myAppState.computedMVertexOpsPerSecond,
	 * myAppState.computedVertsPerArrayCall,
	 * myAppState.computedMFragsPerSecond,
	 * (int) myAppState.computedIndicesPerArrayCall);
	 */

	myAppState.computedMTrisPerSecond = (totalTris / 1000000.0f) / elapsedTimeS;
	myAppState.computedMVertexOpsPerSecond = (totalVerts / 1000000.0f) / elapsedTimeS;
	myAppState.computedMFragsPerSecond = myAppState.computedMTrisPerSecond * myAppState.triangleAreaInPixels;


	printf("verts/frame = %d \n", dispatchVertexCount);
	printf("nframes = %d \n", nFrames);

	free((void *)baseVerts);
	free((void *)baseColors);
	free((void *)baseNormals);
	free((void *)baseTCs);
	free((void *)dispatchVerts);
	free((void *)dispatchColors);
	free((void *)dispatchNormals);
	free((void *)dispatchTCs);

	if (dispatchIndices != NULL)
		free((void *)dispatchIndices);

	if (texturingEnabled)
		cleanupTexture();
}
Пример #13
0
void OpenGLViewer::open(int w, int h)
{
   //OpenGLViewer window created

   //Always use the output width when set for hidden window
   fbo_enabled = !visible; //Always use fbo for hidden window
   if (!visible && outwidth > 0 && outwidth != w)
   {
      h = outheight;
      w = outwidth;
   }
   width = w;
   height = h;

   GLboolean b;
   GLint i, d, s, u, a, sb, ss;

   glGetBooleanv(GL_RGBA_MODE, &b);
   glGetIntegerv(GL_ALPHA_BITS, &i);
   glGetIntegerv(GL_STENCIL_BITS, &s);
   glGetIntegerv(GL_DEPTH_BITS, &d);
   glGetIntegerv(GL_ACCUM_RED_BITS, &a);
   glGetIntegerv(GL_MAX_TEXTURE_UNITS, &u);
   glGetIntegerv(GL_SAMPLE_BUFFERS, &sb);
   glGetIntegerv(GL_SAMPLES, &ss);
   glGetBooleanv(GL_STEREO, &stereoBuffer);
   glGetBooleanv(GL_DOUBLEBUFFER, &doubleBuffer);

   //Set buffers
   if (doubleBuffer) renderBuffer = GL_BACK; else renderBuffer = GL_FRONT;

   debug_print("Stereo %d Double-buffer %d RGBA Mode = %d, Alpha bits = %d, Depth bits = %d, Stencil bits = %d, Accum bits = %d, Texture units %d, SampleBuffers %d, Samples %d\n", stereoBuffer, doubleBuffer, b, i, d, s, a, u, sb, ss);

   //Load OpenGL extensions
   OpenGL_Extensions_Init();

   //Depth testing
   glEnable(GL_DEPTH_TEST);

   //Transparency
   glEnable(GL_BLEND);

   //Smooth shading
   glShadeModel(GL_SMOOTH);

   //Font textures (bitmap fonts)
   lucSetupRasterFont();

   //Setup lighting
   light();

   //Enable scissor test
   glEnable(GL_SCISSOR_TEST);

   //Init fbo
   if (fbo_enabled) fbo(width, height);

   // Clear full window buffer 
   glViewport(0, 0, width, height);
   glScissor(0, 0, width, height);
   glDrawBuffer(renderBuffer);
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

   //Call the application open function
   app->open(width, height);

   //Flag window opened
   if (!isopen)
   {
      isopen = true;
      //Begin polling for input
      animate(TIMER_INC);
   }

   //Call open on any output interfaces
   for (int o=0; o<outputs.size(); o++)
     outputs[o]->open(w, h);
}
Пример #14
0
void
Display( )
{
	if( DebugOn != 0 )
	{
		fprintf( stderr, "Display\n" );
	}


	// set which window we want to do the graphics into:

	glutSetWindow( MainWindow );


	// erase the background:

	glDrawBuffer( GL_BACK );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	glEnable( GL_DEPTH_TEST );


	// specify shading to be flat:

	glShadeModel( GL_SMOOTH );


	// set the viewport to a square centered in the window:

	GLsizei vx = glutGet( GLUT_WINDOW_WIDTH );
	GLsizei vy = glutGet( GLUT_WINDOW_HEIGHT );
	GLsizei v = vx < vy ? vx : vy;			// minimum dimension
	GLint xl = ( vx - v ) / 2;
	GLint yb = ( vy - v ) / 2;
	glViewport( xl, yb,  v, v );


	// set the viewing volume:
	// remember that the Z clipping  values are actually
	// given as DISTANCES IN FRONT OF THE EYE
	// USE gluOrtho2D( ) IF YOU ARE DOING 2D !

	glMatrixMode( GL_PROJECTION );
	glLoadIdentity( );
	//if( WhichProjection == ORTHO )
	//	glOrtho( -3., 3.,     -3., 3.,     0.1, 1000. );
	//else
		gluPerspective( 90., 1.,	0.1, 1000. );


	// place the objects into the scene:

	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity( );


	// set the eye position, look-at position, and up-vector:
	if (InLook == 0){
		gluLookAt(0., 0., 20., 0., 0., 0., 0., 1., 0.);
		glRotatef((GLfloat)Yrot, 0., 1., 0.);
		glRotatef((GLfloat)Xrot, 1., 0., 0.);
		if (Scale < MINSCALE)
			Scale = MINSCALE;
		glScalef((GLfloat)Scale, (GLfloat)Scale, (GLfloat)Scale);


	}
		

	else if (InLook == 1)
		gluLookAt(-0.4, 1.8, -4.9, 0., 2., -14., 0., 1., 0.);

	// rotate the scene:




	// uniformly scale the scene:


	// set the fog parameters:

	if( DepthCueOn != 0 )
	{
		glFogi( GL_FOG_MODE, FOGMODE );
		glFogfv( GL_FOG_COLOR, FOGCOLOR );
		glFogf( GL_FOG_DENSITY, FOGDENSITY );
		glFogf( GL_FOG_START, FOGSTART );
		glFogf( GL_FOG_END, FOGEND );
		glEnable( GL_FOG );
	}
	else
	{
		glDisable( GL_FOG );
	}


	// possibly draw the axes:

	if( AxesOn != 0 )
	{
		glColor3fv( &Colors[WhichColor][0] );
		glCallList(AxesList);
	}

	if (ObjOn != 0)
	{
		glCallList(BoxList);
	}

	//draw the big 2 blades
	glPushMatrix();
	
	glTranslatef(0., 2.9, -2.);			//4
	glRotatef(BladeAngle, 0., 1.,0.);	//3
	glScalef(5., 1., 1.);				//2
	glRotatef(90., 1., 0., 0.);			//1
	

	glBegin(GL_TRIANGLES);
	glVertex2f(BLADE_RADIUS, BLADE_WIDTH / 2. );
	glVertex2f(0., 0.);
	glVertex2f(BLADE_RADIUS , -BLADE_WIDTH / 2.);

	glVertex2f(-BLADE_RADIUS , -BLADE_WIDTH / 2.);
	glVertex2f(0., 0.);
	glVertex2f(-BLADE_RADIUS , BLADE_WIDTH / 2.);
	glEnd();
	glPopMatrix();

	//draw  small2 blades
	glPushMatrix();
	glTranslatef(.5, 2.5, 9.);
	glRotated(3.*BladeAngle, 1., 0., 0.);
	glScalef(1.5, 1., 1.);
	glRotatef(90., 0., 1., 0.);

	glBegin(GL_TRIANGLES);
	glVertex2f(BLADE_RADIUS, BLADE_WIDTH / 2.);
	glVertex2f(0., 0.);
	glVertex2f(BLADE_RADIUS, -BLADE_WIDTH / 2.);

	glVertex2f(-BLADE_RADIUS, -BLADE_WIDTH / 2.);
	glVertex2f(0., 0.);
	glVertex2f(-BLADE_RADIUS, BLADE_WIDTH / 2.);
	glEnd();
	glPopMatrix();

	//Project2 draw the helicopter herer by inputting the heli.550 file
	if (WireframeOn == 1)
	{
		int i;
		struct edge *ep;
		struct point *p0, *p1;

		glPushMatrix();
		glTranslatef(0., -1., 0.);
		glRotatef(97., 0., 1., 0.);
		glRotatef(-15., 0., 0., 1.);
		glBegin(GL_LINES);
		for (i = 0, ep = Heliedges; i < Helinedges; i++, ep++)
		{
			p0 = &Helipoints[ep->p0];
			p1 = &Helipoints[ep->p1];
			glVertex3f(p0->x, p0->y, p0->z);
			glVertex3f(p1->x, p1->y, p1->z);
		}
		glEnd();
		glPopMatrix();
	}
	
	else
	{
		int i;
		struct point *p0, *p1, *p2;
		struct tri *tp;
		float p01[3], p02[3], n[3];

		glPushMatrix();
		glTranslatef(0., -1., 0.);
		glRotatef(97., 0., 1., 0.);
		glRotatef(-15., 0., 0., 1.);
		glBegin(GL_TRIANGLES);
		for (i = 0, tp = Helitris; i < Helintris; i++, tp++)
		{
			p0 = &Helipoints[tp->p0];
			p1 = &Helipoints[tp->p1];
			p2 = &Helipoints[tp->p2];

			/* fake "lighting" from above:			*/

			p01[0] = p1->x - p0->x;
			p01[1] = p1->y - p0->y;
			p01[2] = p1->z - p0->z;
			p02[0] = p2->x - p0->x;
			p02[1] = p2->y - p0->y;
			p02[2] = p2->z - p0->z;
			Cross(p01, p02, n);
			Unit(n, n);
			n[1] = fabs(n[1]);
			n[1] += .25;
			if (n[1] > 1.)
				n[1] = 1.;
			glColor3f(0., n[1], 0.);

			glVertex3f(p0->x, p0->y, p0->z);
			glVertex3f(p1->x, p1->y, p1->z);
			glVertex3f(p2->x, p2->y, p2->z);

		}
		glEnd();
		glPopMatrix();
	}
	
	// draw the current object:

	//glCallList(BoxList);


	// draw some gratuitous text that just rotates on top of the scene:

	glDisable(GL_DEPTH_TEST);
	glColor3f(0., 1., 1.);

	// since we are using glScalef( ), be sure normals get unitized:

	glEnable( GL_NORMALIZE );

	// draw some gratuitous text that is fixed on the screen:
	//
	// the projection matrix is reset to define a scene whose
	// world coordinate system goes from 0-100 in each axis
	//
	// this is called "percent units", and is just a convenience
	//
	// the modelview matrix is reset to identity as we don't
	// want to transform these coordinates

	glDisable( GL_DEPTH_TEST );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity( );
	gluOrtho2D( 0., 100.,     0., 100. );
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity( );
	glColor3f( 1., 1., 1. );
	


	// swap the double-buffered framebuffers:

	glutSwapBuffers( );


	// be sure the graphics buffer has been sent:
	// note: be sure to use glFlush( ) here, not glFinish( ) !

	glFlush( );
}
Пример #15
0
void GBuffer::unbind() {
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glDrawBuffer(GL_BACK);
}
Пример #16
0
bool FrameBufferObject::Create(FBO_TYPE type, GLuint width, GLuint height)
{
	Destroy();


	m_nWidth = width;
	m_nHeight = height;
	m_bUseFBO = glInfo::getInstance().isExtensionSupported("GL_EXT_framebuffer_object");
	m_bUseDepthBuffer = true;
	m_eTextureType = type==FBO_CUBE_COLOR? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;


	// Texture
	glGenTextures( 1, &m_nTexId );
	glBindTexture(m_eTextureType, m_nTexId);
	glTexParameterf(m_eTextureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameterf(m_eTextureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(m_eTextureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameterf(m_eTextureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

//	if(type==FBO_2D_DEPTH)
//		glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);

	GLenum eTarget;
	GLuint nFrames;
	if(type!=FBO_CUBE_COLOR) {
		eTarget = GL_TEXTURE_2D;
		nFrames = 1;
	}
	else {
		eTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
		nFrames = 6;
	}

	for(GLuint i=0; i<nFrames; i++)
	{
		if(type==FBO_2D_DEPTH)
			glTexImage2D(eTarget+i, 0, GL_DEPTH_COMPONENT24, m_nWidth, m_nHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
		else
			glTexImage2D(eTarget+i, 0, GL_RGB, m_nWidth, m_nHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
	}



	if(m_bUseFBO)
	{
		// Frame buffer
		glGenFramebuffersEXT(1, &m_nFrameBufferHandle);
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_nFrameBufferHandle);

		if(m_bUseDepthBuffer /*&& format!=GL_DEPTH_COMPONENT*/)
		{
			// Depth buffer
			glGenRenderbuffersEXT(1, &m_nDepthBufferHandle);
			glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_nDepthBufferHandle);
			glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, m_nWidth, m_nHeight);

			// attache le frame buffer avec le depth buffer
			glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_nDepthBufferHandle);
		}


		//  attach the framebuffer to our texture, which may be a depth texture
		if(type==FBO_2D_DEPTH) {
			m_eAttachment = GL_DEPTH_ATTACHMENT_EXT;
			glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, eTarget, m_nTexId, 0);
			//  disable drawing to any buffers, we only want the depth
			glDrawBuffer(GL_NONE);
			glReadBuffer(GL_NONE);
		} else {
			m_eAttachment = GL_COLOR_ATTACHMENT0_EXT;
			glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, eTarget, m_nTexId, 0);
		}

		m_bUseFBO = CheckStatus();
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	}

	return true;
}
Пример #17
0
void
Display( )
{
	if( DebugOn != 0 )
	{
		fprintf( stderr, "Display\n" );
	}


	// set which window we want to do the graphics into:

	glutSetWindow( MainWindow );


	// erase the background:

	glDrawBuffer( GL_BACK );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	glEnable( GL_DEPTH_TEST );


	// specify shading to be flat:

	glShadeModel( GL_FLAT );


	// set the viewport to a square centered in the window:

	GLsizei vx = glutGet( GLUT_WINDOW_WIDTH );
	GLsizei vy = glutGet( GLUT_WINDOW_HEIGHT );
	GLsizei v = vx < vy ? vx : vy;			// minimum dimension
	GLint xl = ( vx - v ) / 2;
	GLint yb = ( vy - v ) / 2;
	glViewport( xl, yb,  v, v );


	// set the viewing volume:
	// remember that the Z clipping  values are actually
	// given as DISTANCES IN FRONT OF THE EYE
	// USE gluOrtho2D( ) IF YOU ARE DOING 2D !

	glMatrixMode( GL_PROJECTION );
	glLoadIdentity( );
	if( WhichProjection == ORTHO )
		glOrtho( -3., 3.,     -3., 3.,     0.1, 1000. );
	else
		gluPerspective( 90., 1.,	0.1, 1000. );


	// place the objects into the scene:

	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity( );


	// set the eye position, look-at position, and up-vector:

	gluLookAt( 0., 0., 3.,     0., 0., 0.,     0., 1., 0. );


	// rotate the scene:

	glRotatef( (GLfloat)Yrot, 0., 1., 0. );
	glRotatef( (GLfloat)Xrot, 1., 0., 0. );


	// uniformly scale the scene:

	if( Scale < MINSCALE )
		Scale = MINSCALE;
	glScalef( (GLfloat)Scale, (GLfloat)Scale, (GLfloat)Scale );


	// set the fog parameters:

	if( DepthCueOn != 0 )
	{
		glFogi( GL_FOG_MODE, FOGMODE );
		glFogfv( GL_FOG_COLOR, FOGCOLOR );
		glFogf( GL_FOG_DENSITY, FOGDENSITY );
		glFogf( GL_FOG_START, FOGSTART );
		glFogf( GL_FOG_END, FOGEND );
		glEnable( GL_FOG );
	}
	else
	{
		glDisable( GL_FOG );
	}


	// possibly draw the axes:

	if( AxesOn != 0 )
	{
		glColor3fv( &Colors[WhichColor][0] );
		glCallList( AxesList );
	}


	// since we are using glScalef( ), be sure normals get unitized:

	glEnable( GL_NORMALIZE );


	// draw the current object:
	//glCallList( BoxList );

	//draw a green sphere:

	glColor3f(0., 1., 0.);


	//Texture mapping:
	if (BlobOn) {
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glEnable(GL_TEXTURE_2D);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
		glBindTexture(GL_TEXTURE_2D, TEX);
		MjbSphere(RADIUS, SLICES, STACKS);

		glDisable(GL_TEXTURE_2D);
	}
	else
		MjbSphere(RADIUS, SLICES, STACKS);

	// draw some gratuitous text that just rotates on top of the scene:

	
	// draw some gratuitous text that is fixed on the screen:
	//
	// the projection matrix is reset to define a scene whose
	// world coordinate system goes from 0-100 in each axis
	//
	// this is called "percent units", and is just a convenience
	//
	// the modelview matrix is reset to identity as we don't
	// want to transform these coordinates

	glDisable( GL_DEPTH_TEST );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity( );
	gluOrtho2D( 0., 100.,     0., 100. );
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity( );



	// swap the double-buffered framebuffers:

	glutSwapBuffers( );


	// be sure the graphics buffer has been sent:
	// note: be sure to use glFlush( ) here, not glFinish( ) !

	glFlush( );
}
Пример #18
0
enum piglit_result
piglit_display(void)
{
	bool pass = true;
	bool pixel_probe = true;
	int i;
	GLfloat probe[4];
	for ( i = 0; i < ARRAY_SIZE(bufferlist); i++) {
		glDrawBuffer(bufferlist[i]);
		glClear(GL_COLOR_BUFFER_BIT);
		glColor4fv(color[i]);
		piglit_draw_rect(20, 20, 50, 50);
		pass = piglit_check_gl_error(GL_NO_ERROR)
		       && pass;
		switch (bufferlist[i]) {
		case GL_FRONT_AND_BACK:
			glReadBuffer(GL_BACK_LEFT);
			pass = piglit_probe_rect_rgba(20, 20, 50, 50,
						      color[i])
			       && pass;
			glReadBuffer(GL_FRONT_LEFT);
			pass = pass &&
			       piglit_probe_rect_rgba(20, 20, 50, 50,
						      color[i]);
			break;
		case GL_LEFT:
			glReadBuffer(GL_BACK_LEFT);
			pass = piglit_probe_rect_rgba(20, 20, 50, 50,
						      color[i])
			       && pass;
			glReadBuffer(GL_FRONT_LEFT);
			pass = piglit_probe_rect_rgba(20, 20, 50, 50,
						      color[i])
			       && pass;
			break;
		case GL_BACK:
		case GL_BACK_LEFT:
			glReadBuffer(bufferlist[i]);
			pass = piglit_probe_rect_rgba(20, 20, 50, 50,
						      color[i])
			       && pass;
			/* This should not modify GL_FRONT_LEFT buffer */
			glReadBuffer(GL_FRONT_LEFT);
			pixel_probe = piglit_probe_pixel_rgba_silent(25, 25,
								     color[i],
								     probe);
			pass = !pixel_probe && pass;
			if(pixel_probe)
				printf("glDrawBuffer(GL_BACK) modifies"
				       " GL_FRONT_LEFT buffer\n");
			break;
		case GL_FRONT:
		case GL_FRONT_LEFT:
			glReadBuffer(bufferlist[i]);
			pass = piglit_probe_rect_rgba(20, 20, 50, 50,
						      color[i])
			       && pass;
			/* This should not modify GL_BACK_LEFT buffer */
			glReadBuffer(GL_BACK_LEFT);
			pixel_probe = piglit_probe_pixel_rgba_silent(25, 25,
								     color[i],
								     probe);
			pass = !pixel_probe && pass;
			if(pixel_probe)
				printf("glDrawBuffer(GL_FRONT) modifies"
				       " GL_BACK_LEFT buffer\n");
			break;
		case GL_NONE:
			/* Drawing to a buffer GL_NONE should not
			 * modify any existing buffers
			 */
			glReadBuffer(GL_BACK_LEFT);
			pixel_probe = piglit_probe_pixel_rgba_silent(25, 25,
								     color[i],
								     probe);
			pass = !pixel_probe && pass;
			if(pixel_probe)
				printf("glDrawBuffer(GL_NONE) modifies"
				       " GL_BACK_LEFT buffer\n");
			glReadBuffer(GL_FRONT_LEFT);
			pixel_probe = piglit_probe_pixel_rgba_silent(25, 25,
								     color[i],
								     probe);
			pass = !pixel_probe && pass;
			if (pixel_probe)
				printf("glDrawBuffer(GL_NONE) modifies"
				       " GL_FRONT_LEFT buffer\n");
			break;
		}
		pass = piglit_check_gl_error(GL_NO_ERROR)
		       && pass;
	}
	return (pass ? PIGLIT_PASS : PIGLIT_FAIL);
}
Пример #19
0
void
piglit_init(int argc, char **argv)
{
	GLint max_samples, sample_buffers, samples, rb_samples;
	GLuint rb, fb;
	GLenum status;
	bool pass = true;
	int i;

	piglit_require_extension("GL_EXT_framebuffer_multisample");

	glGetIntegerv(GL_MAX_SAMPLES, &max_samples);

	glGenFramebuffersEXT(1, &fb);
	glBindFramebufferEXT(GL_FRAMEBUFFER, fb);

	glDrawBuffer(GL_COLOR_ATTACHMENT0);
	glReadBuffer(GL_COLOR_ATTACHMENT0);

	for (i = 0; i < max_samples; i++) {
		glGenRenderbuffersEXT(1, &rb);
		glBindRenderbufferEXT(GL_RENDERBUFFER, rb);
		glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER,
						    max_samples,
						    GL_RGBA, 1, 1);

		glFramebufferRenderbufferEXT(GL_FRAMEBUFFER,
					     GL_COLOR_ATTACHMENT0,
					     GL_RENDERBUFFER, rb);

		status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
		if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
			fprintf(stderr, "FBO incomplete\n");
			piglit_report_result(PIGLIT_FAIL);
		}

		glGetRenderbufferParameterivEXT(GL_RENDERBUFFER,
						GL_RENDERBUFFER_SAMPLES,
						&rb_samples);

		glGetIntegerv(GL_SAMPLES, &samples);
		if (rb_samples != samples) {
			fprintf(stderr,
				"FBO reported GL_SAMPLES %d for "
				"rb samples %d\n",
				samples, rb_samples);
			pass = false;
		}

		glGetIntegerv(GL_SAMPLE_BUFFERS, &sample_buffers);
		if ((rb_samples != 0) != (sample_buffers == 1)) {
			fprintf(stderr,
				"FBO reported GL_SAMPLE_BUFFERS %d for "
				"rb samples %d\n",
				sample_buffers, samples);
			pass = false;
		}

		glDeleteRenderbuffersEXT(1, &rb);
	}

	glDeleteFramebuffersEXT(1, &fb);

	piglit_report_result(pass ? PIGLIT_PASS : PIGLIT_FAIL);
}
Пример #20
0
ENTRYPOINT void init_antmaze(ModeInfo * mi) 
{
  double rot_speed = 0.3;
  int i;

  antmazestruct *mp;
  
  if (antmaze == NULL) {
	if ((antmaze = (antmazestruct *) calloc(MI_NUM_SCREENS(mi),
						sizeof (antmazestruct))) == NULL)
	  return;
  }
  mp = &antmaze[MI_SCREEN(mi)];
  mp->step = NRAND(90);
  mp->ant_position = NRAND(90);


  mp->antdirection[0] = PI/2.0;
  mp->antdirection[1] = PI/2.0;
  mp->antdirection[2] = 0;
  mp->antdirection[3] = PI/2.0;
  mp->antdirection[4] = PI/2.0;

  mp->antposition[0][0] = -4.0;
  mp->antposition[0][1] =  5.0;
  mp->antposition[0][1] =  0.15;

  mp->antposition[1][0] = -4.0;
  mp->antposition[1][1] =  3.0;
  mp->antposition[1][1] =  0.15;

  mp->antposition[2][0] = -1.0;
  mp->antposition[2][1] = -2.0;
  mp->antposition[2][1] =  0.15;

  mp->antposition[3][0] = -3.9;
  mp->antposition[3][1] =  6.0;
  mp->antposition[3][1] =  0.15;

  mp->antposition[4][0] =  2.0;
  mp->antposition[4][1] = -2.0;
  mp->antposition[4][1] =  0.15;

  

  for (i = 0; i < ANTCOUNT; i++) {
    mp->antvelocity[i] = 0.02;
    mp->antsize[i] = 1.0;
    mp->anton[i] = 0;
  }

  mp->bposition[0][0] = 0;
  mp->bposition[0][1] = 8;

  mp->bposition[1][0] = 9;
  mp->bposition[1][1] = 1;

  mp->bposition[2][0] = 1;
  mp->bposition[2][1] = 1;

  mp->bposition[3][0] = 4;
  mp->bposition[3][1] = 8;

  mp->bposition[4][0] = 2;
  mp->bposition[4][1] = 1;

  mp->part[0] = 0;
  mp->part[1] = 1;
  mp->part[2] = 5;
  mp->part[3] = 1;
  mp->part[4] = 3;

  mp->introduced = 0;
  mp->entroducing = 12;
  mp->fadeout = 1.0;
  mp->mag = 4.0;

  mp->rot = make_rotator (rot_speed, rot_speed, rot_speed, 1, 0, True);
  mp->trackball = gltrackball_init ();
  
  if ((mp->glx_context = init_GL(mi)) != NULL) {
    reshape_antmaze(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
    glDrawBuffer(GL_BACK);
    pinit(mp);
  } 
  else
    MI_CLEARWINDOW(mi);
}
Пример #21
0
void PaintView::draw()
{
	#ifndef MESA
	// To avoid flicker on some machines.
	glDrawBuffer(GL_BACK);
	#endif // !MESA

	if(!valid())
	{


		glClearColor(0.7f, 0.7f, 0.7f, 1.0);

		// We're only using 2-D, so turn off depth 
		glDisable( GL_DEPTH_TEST );

		ortho();

		int	cx	= m_nWindowWidth = w();
		int	cy	= m_nWindowHeight = h();



		// Tell openGL to read from the front buffer when capturing
		// out paint strokes 
		glReadBuffer( GL_FRONT );

		glViewport( 0, 0, cx, cy );

		glMatrixMode( GL_PROJECTION );
		glLoadIdentity();
		gluOrtho2D( 0, cx, 0, cy );

		glMatrixMode( GL_MODELVIEW );
		glLoadIdentity();

		// This translation is needed to make the image pixels line up with
		// the screen's pixels.  For details, visit:
		// http://www.opengl.org/resources/faq/technical/transformations.htm#tran0030
		glTranslatef( 0.375, 0.375, 0.0 );


		glClear( GL_COLOR_BUFFER_BIT );
	}

	ImpBrush::Point scrollpos;// = GetScrollPosition();
	scrollpos.x = 0;
	scrollpos.y	= 0;

	m_nWindowWidth	= w();
	m_nWindowHeight	= h();

	int drawWidth, drawHeight;
	drawWidth = min( m_nWindowWidth, m_pDoc->m_nPaintWidth );
	drawHeight = min( m_nWindowHeight, m_pDoc->m_nPaintHeight );

	int startrow = m_pDoc->m_nPaintHeight - (scrollpos.y + drawHeight);
	if ( startrow < 0 ) startrow = 0;

	m_pPaintBitstart = m_pDoc->m_ucPainting + 
		3 * ((m_pDoc->m_nPaintWidth * startrow) + scrollpos.x);

	m_nDrawWidth	= drawWidth;
	m_nDrawHeight	= drawHeight;

	m_nStartRow		= startrow;
	m_nEndRow		= startrow + drawHeight;
	m_nStartCol		= scrollpos.x;
	m_nEndCol		= m_nStartCol + drawWidth;

	if ( m_pDoc->m_ucPainting && !isAnEvent) 
	{
		RestoreContent();

	}

	if ( m_pDoc->m_ucPainting && isAnEvent) 
	{

		// Clear it after processing.
		isAnEvent	= 0;	

		ImpBrush::Point source( coord.x + m_nStartCol, m_nEndRow - coord.y );
		ImpBrush::Point target( coord.x, m_nWindowHeight - coord.y );
		
		// This is the event handler
		switch (eventToDo) 
		{
		case LEFT_MOUSE_DOWN:
			m_pDoc->m_pCurrentBrush->BrushBegin( source, target );
			break;
		case LEFT_MOUSE_DRAG:
			m_pDoc->m_pCurrentBrush->BrushMove( source, target );
			break;
		case LEFT_MOUSE_UP:
			m_pDoc->m_pCurrentBrush->BrushEnd( source, target );

			SaveCurrentBackContent();
			RestoreContent();
			break;
		case RIGHT_MOUSE_DOWN:

			break;
		case RIGHT_MOUSE_DRAG:

			break;
		case RIGHT_MOUSE_UP:

			break;

		default:
			printf("Unknown event!!\n");		
			break;
		}
	}

	glFlush();

	#ifndef MESA
	// To avoid flicker on some machines.
	glDrawBuffer(GL_BACK);
	#endif // !MESA
}
Пример #22
0
/*
==============
XY_Overlay
==============
*/
void XY_Overlay (void)
{
	int	w, h;
	int	r[4];
	static	vec3_t	lastz;
	static	vec3_t	lastcamera;


	glViewport(0, 0, g_qeglobals.d_xy.width, g_qeglobals.d_xy.height);

	//
	// set up viewpoint
	//
	glMatrixMode(GL_PROJECTION);
    glLoadIdentity ();

	w = g_qeglobals.d_xy.width/2 / g_qeglobals.d_xy.scale;
	h = g_qeglobals.d_xy.height/2 / g_qeglobals.d_xy.scale;
	glOrtho (g_qeglobals.d_xy.origin[0] - w, g_qeglobals.d_xy.origin[0] + w
		, g_qeglobals.d_xy.origin[1] - h, g_qeglobals.d_xy.origin[1] + h, -8000, 8000);
	//
	// erase the old camera and z checker positions
	// if the entire xy hasn't been redrawn
	//
	if (g_qeglobals.d_xy.d_dirty)
	{
		glReadBuffer (GL_BACK);
		glDrawBuffer (GL_FRONT);

		glRasterPos2f (lastz[0]-9, lastz[1]-9);
		glGetIntegerv (GL_CURRENT_RASTER_POSITION,r);
		glCopyPixels(r[0], r[1], 18,18, GL_COLOR);

		glRasterPos2f (lastcamera[0]-50, lastcamera[1]-50);
		glGetIntegerv (GL_CURRENT_RASTER_POSITION,r);
		glCopyPixels(r[0], r[1], 100,100, GL_COLOR);
	}
	g_qeglobals.d_xy.d_dirty = true;

	//
	// save off underneath where we are about to draw
	//
	VectorCopy (z.origin, lastz);
	VectorCopy (camera.origin, lastcamera);

	glReadBuffer (GL_FRONT);
	glDrawBuffer (GL_BACK);

	glRasterPos2f (lastz[0]-9, lastz[1]-9);
	glGetIntegerv (GL_CURRENT_RASTER_POSITION,r);
	glCopyPixels(r[0], r[1], 18,18, GL_COLOR);

	glRasterPos2f (lastcamera[0]-50, lastcamera[1]-50);
	glGetIntegerv (GL_CURRENT_RASTER_POSITION,r);
	glCopyPixels(r[0], r[1], 100,100, GL_COLOR);

	//
	// draw the new icons
	//
	glDrawBuffer (GL_FRONT);

    glShadeModel (GL_FLAT);
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_TEXTURE_1D);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_BLEND);
	glColor3f(0, 0, 0);

	DrawCameraIcon ();
	DrawZIcon ();

	glDrawBuffer (GL_BACK);
    glFinish();
}
Пример #23
0
bool
do_blit_test(bool use_es2, bool from_missing_to_complete)
{
    GLuint rb[3];
    GLuint fb[2];
    GLenum status;
    GLenum err;
    const unsigned src = from_missing_to_complete ? 0 : 1;
    const unsigned dst = 1 - src;
    const char *const names[] = {
        "buffer with missing attachment",
        "complete buffer"
    };
    bool pass = true;

    printf("Testing blit from %s to %s...\n", names[src], names[dst]);

    /* Create a depth-only FBO and a depth/color FBO.
     */
    glGenRenderbuffers(ARRAY_SIZE(rb), rb);

    glBindRenderbuffer(GL_RENDERBUFFER, rb[0]);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24,
                          piglit_width, piglit_height);
    glBindRenderbuffer(GL_RENDERBUFFER, rb[1]);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24,
                          piglit_width, piglit_height);
    glBindRenderbuffer(GL_RENDERBUFFER, rb[2]);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA,
                          piglit_width, piglit_height);

    glGenFramebuffers(ARRAY_SIZE(fb), fb);
    glBindFramebuffer(GL_FRAMEBUFFER, fb[0]);
    glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                              GL_RENDERBUFFER, rb[0]);
    if (!use_es2) {
        glDrawBuffer(GL_NONE);
        glReadBuffer(GL_NONE);
    }

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb[1]);
    glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                              GL_RENDERBUFFER, rb[1]);
    glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                              GL_RENDERBUFFER, rb[2]);

    err = glGetError();
    if (err != 0) {
        fprintf(stderr, "Unexpected GL error state 0x%04x\n", err);
        return false;
    }

    /* Check completeness of the source surface.
     */
    glBindFramebuffer(GL_READ_FRAMEBUFFER, fb[src]);
    status = glCheckFramebufferStatus(GL_READ_FRAMEBUFFER);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        fprintf(stderr, "Read FBO erroneously incomplete: 0x%04x\n",
                status);
        return false;
    }

    /* In the source surface, clear the depth buffer and draw a single
     * rectangle with a constant depth value.  The depth test setting here
     * is correct.
     */
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb[src]);
    glClearDepth(0.0);
    glClear(GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_ALWAYS);

    piglit_draw_rect_z(0.5, -0.5, -0.5, 1.0, 1.0);

    /* Check completeness of the destination surface.
     */
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb[dst]);
    status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);

    if (status != GL_FRAMEBUFFER_COMPLETE) {
        fprintf(stderr, "Draw FBO erroneously incomplete: 0x%04x\n",
                status);
        return false;
    }

    glBlitFramebuffer(0, 0, piglit_width, piglit_height,
                      0, 0, piglit_width, piglit_height,
                      GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT,
                      GL_NEAREST);
    err = glGetError();
    if (err != 0) {
        fprintf(stderr, "Unexpected GL error state 0x%04x\n", err);
        return false;
    }

    /* Probe depth values from the destination buffer to make sure the
     * depth part of the blit actually happened.
     */
    glBindFramebuffer(GL_READ_FRAMEBUFFER, fb[dst]);
    pass = piglit_probe_rect_depth(0.25 * piglit_width,
                                   0.25 * piglit_height,
                                   0.4 * piglit_width,
                                   0.4 * piglit_height,
                                   0.75);
    pass = piglit_probe_rect_depth(0,
                                   0,
                                   piglit_width,
                                   0.2 * piglit_height,
                                   0.0)
           && pass;

    glBindFramebuffer(GL_READ_FRAMEBUFFER, piglit_winsys_fbo);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, piglit_winsys_fbo);
    glDeleteFramebuffers(ARRAY_SIZE(fb), fb);
    glDeleteRenderbuffers(ARRAY_SIZE(rb), rb);

    return pass;
}
Пример #24
0
void Desenha(){
	float fps;
	char msg[40+1];



	
	/*glPushMatrix();  
	iluminacao();
	glPopMatrix();*/

	glEnable(GL_CULL_FACE); // habilita remoção de superficies escondidas.
	glCullFace(GL_BACK);
	
	glDrawBuffer(GL_BACK);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	//glOrtho(-20.0, 20.0, -20.0, 20.0, 1, 1000.0);

	gluPerspective(angle,fAspect,0.1,1200);

	glMatrixMode(GL_VIEWPORT);
	glViewport(0, 50, width_window, height_window);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glClearColor(0.0, 0.0, 0.0, 0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


	
	glEnable(GL_DEPTH_TEST);  

	if(habilita_desenho){
		glPushMatrix();
		glTranslated(0, 0, -60);
		
		

		if(habilitar_linhas){
			glBegin(GL_LINES);

			glColor3d(1, 0, 0);//x
			glVertex3d(-20,0,0);
			glVertex3d(20,0,0);
			
			glColor3d(0, 1, 0);//y
			glVertex3d(0,-20,0);
			glVertex3d(0,20,0);
			
			glColor3d(0, 0, 1);//Z
			glVertex3d(0,0,-20);
			glVertex3d(0,0,20);
			glEnd();
		}		
		glPushMatrix();
		glTranslated(0,0,-30);
		glScaled(20,20,20);
		glRotated(90,1,0,0);
		glCallList(GLM_background_list);
		glPopMatrix();
		Esferas();
		desenha_aviao();
		misseis();
		glPopMatrix();  
	}else{
		glPushMatrix();
		glTranslated(0, 0, -60);
		Texto2(); 
		glPopMatrix(); 
	}

	fps = CalculaQPS();
	sprintf(msg,"fps: %f\n",fps);
	//printf(msg);
	Escreve2D(0, 0.005, (unsigned char *)msg);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-20.0, 20.0, -20.0, 20.0, 1, 60.0);

	glViewport(0, 0, width_window, 50);
	glPushMatrix();
	glTranslated(0, 0, -20);

	//glDisable(GL_DEPTH_TEST); 
	glMatrixMode(GL_MODELVIEW);

	glDisable(GL_LIGHTING);

	barravida();
	chances();
	//Texto();

	glBegin(GL_QUAD_STRIP);
	//glNormal3d(0.0, 0.0, 1.0);
	glColor3d(0.5, 0.4, 0.3);//vida vermelha
	glVertex3d(-20,20,-10);
	glVertex3d(-20,-20,-10);
	glVertex3d(20,20,-10);
	glVertex3d(20,-20,-10);
	glEnd();

	glEnable(GL_LIGHTING);
	glEnable(GL_DEPTH_TEST);
	glPopMatrix(); 

	glDisable(GL_CULL_FACE);
}
/**
 * Test one cube map face to see if glGetTexImage from a cube face into
 * a PBO works correctly.
 */
static bool
test_face(GLuint face)
{
	const GLenum cubeFaceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face;
	const GLuint expectedColor = Colors[face];
	GLuint texData[TEX_NUMPIXELS];
	GLuint cubeTex, fbo, packPBO;
	GLuint f, i;
	void *ptr;

	/* Create the cubemap texture. */
	glGenTextures(1, &cubeTex);
	glActiveTextureARB(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_CUBE_MAP, cubeTex);
	glPixelStorei(GL_UNPACK_ROW_LENGTH, TEX_WIDTH);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	for (f = 0; f < 6; ++f) {
		for (i = 0; i < TEX_NUMPIXELS; ++i) {
			texData[i] = Colors[f];
		}
		glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, 0,
			     GL_SRGB8_ALPHA8, TEX_WIDTH, TEX_HEIGHT, 0, GL_BGRA,
			     GL_UNSIGNED_INT_8_8_8_8_REV, texData);
	}

	/* Setup the FBO. */
	glGenFramebuffers(1, &fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, fbo);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
			       cubeFaceTarget, cubeTex, 0);
	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) !=
	    GL_FRAMEBUFFER_COMPLETE) {
		printf("Incomplete framebuffer object\n");
		return false;
	}
	glDrawBuffer(GL_COLOR_ATTACHMENT0);

	/* Read back cubemap face into PBO */
	glGenBuffers(1, &packPBO);
	glBindBuffer(GL_PIXEL_PACK_BUFFER, packPBO);
	glBufferData(GL_PIXEL_PACK_BUFFER, TEX_NUMPIXELS * sizeof(GLuint),
						NULL, GL_STREAM_READ);
	glPixelStorei(GL_PACK_ROW_LENGTH, TEX_WIDTH);
	glPixelStorei(GL_PACK_ALIGNMENT, 1);
	glGetTexImage(cubeFaceTarget, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV,
		      NULL);

	/* Map pack PBO to get results. */
	ptr = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
	if (!ptr) {
		printf("failed to map PBO\n");
		return false;
	}
	for (i = 0; i < TEX_NUMPIXELS; ++i) {
		texData[i] = Colors[6];	 /* gray */
	}

	memcpy(texData, ptr, TEX_NUMPIXELS * sizeof(GLuint));

	glUnmapBuffer(GL_PIXEL_PACK_BUFFER);

	if (expectedColor != texData[0]) {
		printf("Colors don't match for face %u\n", face);
		printf("Expected 0x%08x but found 0x%08x \n",
		       expectedColor, texData[0]);
		return false;
	}

	glDeleteTextures(1, &cubeTex);
	glDeleteFramebuffers(1, &fbo);
	glDeleteBuffers(1, &packPBO);

	/* if we get here we passed */
	return true;
}
Пример #26
0
void
derp (void)
{
  const struct aiScene *csc;
  struct aiScene *sc;
  struct aiMesh *me;
  GLuint vb, nb, tb;
  GLuint ctex;
  GLuint dtex;
  GLuint fbo;
  GLuint dpp;
  GLint dpp_cat0_loc;

  csc = aiImportFile ("../data/n1.dae",
                      aiProcess_Triangulate | aiProcess_PreTransformVertices);
  sc = (struct aiScene *)csc;
  
  g_xassert (sc);
  g_xassert (sc->mNumMeshes >= 1);
  g_xassert (sc->mNumMaterials >= 1);

  me = sc->mMeshes[0];

  g_xassert (aiPrimitiveType_TRIANGLE == me->mPrimitiveTypes);

  mesh_buffers_extract (me, &vb, &nb, &tb);

  /* Save Viewport, Modelview, Projection.
   * Then set them to sane defaults.
   *
   * Empirical test indicates projection set to Ortho,
   * Modelview set to Identity, Viewport set to 0,0,w,h.
   *
   * ModelView and Viewport are fine but Projection has to go,
   * as I plan setting it myself.
   */

  allegro_ffp_restore (RESTORE_MODE_SAVE, RESTORE_SUB_ALLEGRO);

  /*
   * Do not do this...
   * While it is useful to play it safe and save & restore viewport/mst,
   * I am not actually supposed to set over allegro's stuff, right?
   * Actually:
   *    Need to use allegro's original settings when using the
   *    drawing routines targeting framebuffer 0. (eg debug_draw_tex_quad)
   * It is correct to LoadIdentity the projection stack,
   * but fix said routines to use allegro state.
   */

  glMatrixMode (GL_PROJECTION);
  glLoadIdentity ();
  glMatrixMode (GL_MODELVIEW);

  /* Clear the default framebuffer (Optional) */

  glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, 0);
  glClearColor (0, 0, 1, 1);
  glClear (GL_COLOR_BUFFER_BIT);

  /* Create two textures, a color and a depth. */

  glGenTextures (1, &ctex);
  glActiveTexture (GL_TEXTURE0);
  glBindTexture (GL_TEXTURE_2D, ctex);
  glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8,
		640, 480, 0,
		GL_RGBA, GL_UNSIGNED_BYTE,
		NULL);

  glGenTextures (1, &dtex);
  glActiveTexture (GL_TEXTURE0);
  glBindTexture (GL_TEXTURE_2D, dtex);
  glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24_ARB,
		640, 480, 0,
		GL_DEPTH_COMPONENT, GL_UNSIGNED_INT,
		NULL);

  check_gl_error ();

  /* Create a FBO and attach the newly created textures */

  glGenFramebuffersEXT (1, &fbo);
  glBindFramebufferEXT (GL_FRAMEBUFFER, fbo);
  glFramebufferTexture2DEXT (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
			     GL_TEXTURE_2D, ctex, 0);
  glFramebufferTexture2DEXT (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
			     GL_TEXTURE_2D, dtex, 0);
  
  g_xassert (GL_FRAMEBUFFER_COMPLETE ==
	   glCheckFramebufferStatusEXT (GL_FRAMEBUFFER));

  check_gl_error ();

  /* Create the depth pass program. (Vertex shader only, do nothing) */

  dpp = depth_pass_program ();

  check_gl_error ();

  struct DepthData ds;
  ds.fbo = fbo;
  ds.ab = vb;
  ds.dpp = dpp;

  depth_bind (&ds);

  {
    glMatrixMode (GL_PROJECTION);
    glPushMatrix ();
    glLoadIdentity ();
    //glOrtho (-2.5, 2.5, -2.5, 2.5, -5, 5);
    gluPerspective (90.0f, 1.0f, 1.0f, 5.0f);

    glMatrixMode (GL_MODELVIEW);
    glPushMatrix ();
    glLoadIdentity ();
    glTranslatef (0.0f, 0.0f, -2.5f);

    glDrawBuffer (GL_COLOR_ATTACHMENT0);
    glClear (GL_DEPTH_BUFFER_BIT);

    glBindBuffer (GL_ARRAY_BUFFER, ds.ab);
    glVertexAttribPointer (ds._cat0_loc, 3, GL_FLOAT, GL_FALSE, 0, 0);

    glUseProgram (ds.dpp);
    glDrawArrays (GL_TRIANGLES, 0, me->mNumFaces * 3);
    glUseProgram (0);

    glMatrixMode (GL_PROJECTION);
    glPopMatrix ();

    glMatrixMode (GL_MODELVIEW);
    glPopMatrix ();
  }

  depth_unbind (&ds);

  debug_draw_tex_quad (ctex, 100, 0, 100, 100);
  debug_draw_tex_quad (dtex, 100, 150, 100, 100);

  /**
   * Material stuff, move elsewhere or something.
   */
  struct aiMaterial *mat;
  struct aiColor4D col_diff;
  struct aiColor4D col_spec;

  g_xassert (sc->mNumMaterials >= 1);

  mat = sc->mMaterials[me->mMaterialIndex];

  g_xassert (AI_SUCCESS ==
             aiGetMaterialColor (mat, AI_MATKEY_COLOR_DIFFUSE, &col_diff));

  g_xassert (AI_SUCCESS ==
             aiGetMaterialColor (mat, AI_MATKEY_COLOR_SPECULAR, &col_spec));

  struct MaterialFbo mf = {0};
  mf.tdep = dtex;

  material_create_fbo (&mf);

  /**
   * Warning:
   * Remember to unbind the depth texture (dtex) from depth_stage fbo,
   * Rebind it as texture for rendering. (Don't need to unbind?)
   * (4.4.2) ""A single framebuffer-attachable image may be attached
   * to multiple framebuffer objects""
   * Not sure about whether unbind required.
   * (4.4.3) Warns about Feedback loops, which do apply.
   */
  struct MaterialData ms = {0};
  ms.fbo = mf._fbo;
  ms.ctex = blender_tex;
  ms.dtex = dtex;
  ms.mpp = material_pass_program ();
  ms.vb = vb;
  ms.nb = nb;
  ms.tb = tb;

  material_bind (&ms);

  {
    glMatrixMode (GL_PROJECTION);
    glPushMatrix ();
    glLoadIdentity ();
    //glOrtho (-2.5, 2.5, -2.5, 2.5, -5, 5);
    gluPerspective (90.0f, 1.0f, 1.0f, 5.0f);

    glMatrixMode (GL_MODELVIEW);
    glPushMatrix ();
    glLoadIdentity ();
    glTranslatef (0.0f, 0.0f, -2.5f);

    GLenum material_draw_buffers[] = {GL_COLOR_ATTACHMENT0,
                                      GL_COLOR_ATTACHMENT1,
                                      GL_COLOR_ATTACHMENT2};
    glDrawBuffers (3, material_draw_buffers);

    glBindBuffer (GL_ARRAY_BUFFER, ms.vb);
    glVertexAttribPointer (ms._cat0_loc, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glBindBuffer (GL_ARRAY_BUFFER, ms.nb);
    glVertexAttribPointer (ms._cat1_nor, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glBindBuffer (GL_ARRAY_BUFFER, ms.tb);
    glVertexAttribPointer (ms._cat2_tex, 3, GL_FLOAT, GL_FALSE, 0, 0);

    /* Program needs to be active to load Uniforms */
    glUseProgram (ms.mpp);

    /**
     * Texture unit 0,
     * make sure diffuse / color texture is glBindTexture'd
     * while glActiveTexture is zero.
     */
    glUniform1i (ms._tex0, 0);

    /* Also go load diffuse, specular out of the aiColor4Ds */
    glUniform4f (ms._diffuse,
                 col_diff.r, col_diff.g, col_diff.b, col_diff.a);
    glUniform4f (ms._specular,
                 col_spec.r, col_spec.g, col_spec.b, col_spec.a);
    
    glActiveTexture (GL_TEXTURE0);
    glEnable (GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, ms.ctex);

    glDrawArrays (GL_TRIANGLES, 0, me->mNumFaces * 3);

    glUseProgram (0);

    glMatrixMode (GL_PROJECTION);
    glPopMatrix ();

    glMatrixMode (GL_MODELVIEW);
    glPopMatrix ();
  }

  material_unbind (&ms);

  /**
   * I believe I don't have the right COLOR_ATTACHMENTs during material stage.
   * In any case ctex probably ends up as normals.
   * Creating a new FBO for the material stage is probably ok.
   *
   * Warning:
   * For unknown reason the model, automaticall unwrapped by Blender
   * (Select all faces -> U -> Unwrap) had its UV coordinates screwed up.
   * Re-exporting with a proper UV map somehow fixed the problem.
   *
   * Blender settings: (Texure Properties)
   * Image/Source: Single Image
   * Mapping/Coordinates: UV
   * Mapping Layer: (Empty)
   * Mapping/Projection: Flat
   */
  //debug_draw_tex_quad (ctex, 200, 0, 100, 100);
  debug_draw_tex_quad (mf._tnor, 200, 0, 100, 100);
  debug_draw_tex_quad (mf._tdiff, 200, 110, 100, 100);
  debug_draw_tex_quad (mf._tspec, 200, 220, 100, 100);

  /* 3.4 Lighting Stage */
  struct LightingFbo lf = {0};
  lf.tdep = dtex;

  lighting_create_fbo (&lf);

  struct LightingData ls = {0};
  ls.fbo = lf._fbo;
  ls.lpp = lighting_ambient_pass_program ();
  ls.dtex = dtex;
  ls.tnor = mf._tnor;
  ls.tdiff = mf._tdiff;
  ls.tspec = mf._tspec;

  lighting_bind (&ls);

  {
  }

  lighting_unbind (&ls);

  /* Restore the saved allegro settings */

  allegro_ffp_restore (RESTORE_MODE_RESTORE, RESTORE_SUB_ALLEGRO);
}
Пример #27
0
static void init_gl(ModeInfo *mi) 
{
  cube21_conf *cp = &cube21[MI_SCREEN(mi)];
#ifdef MIPMAP
  int status;
#endif
  parse_colmode();
  cp->wire = MI_IS_WIREFRAME(mi);
  cp->cmat = !cp->wire && (colmode != CUBE21_COLOR_WHITE);
  if(MI_IS_MONO(mi)) {
    tex = False;
    cp->cmat = False;
  }

# ifdef HAVE_JWZGLES /* #### glPolygonMode other than GL_FILL unimplemented */
  cp->wire = 0;
# endif

  if(cp->wire) {
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    return;
  }
  if(!tex)
    cp->color_inner[0] = cp->color_inner[1] = cp->color_inner[2] = 0.4;
  else
    cp->color_inner[0] = cp->color_inner[1] = cp->color_inner[2] = 1.0;

  glClearDepth(1.0);
  glDrawBuffer(GL_BACK);
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glShadeModel(GL_FLAT);
  glDepthFunc(GL_LESS);
  glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
  glLightfv(GL_LIGHT0, GL_POSITION, position0);
  glLightfv(GL_LIGHT1, GL_AMBIENT, ambient);
  glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse);
  glLightfv(GL_LIGHT1, GL_POSITION, position1);
  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_LIGHT0);
  glEnable(GL_LIGHT1);
  glEnable(GL_LIGHTING);
  glEnable(GL_NORMALIZE);
  glEnable(GL_COLOR_MATERIAL);
  glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material_ambient);
  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_diffuse);
  glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_specular);
  glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
  if(!tex) return;
  glEnable(GL_TEXTURE_2D);
#ifdef MIPMAP
  clear_gl_error();
  status = gluBuild2DMipmaps(GL_TEXTURE_2D, 1, TEX_WIDTH, TEX_HEIGHT,
      GL_LUMINANCE, GL_UNSIGNED_BYTE, texture);
  if (status) {
    const char *s = gluErrorString(status);
    fprintf (stderr, "%s: error mipmapping texture: %s\n", progname, (s?s:"(unknown)"));
    exit (1);
  }
  check_gl_error("mipmapping");
#else    
  glTexImage2D(GL_TEXTURE_2D, 0, 1, TEX_WIDTH, TEX_HEIGHT,
      0, GL_LUMINANCE, GL_UNSIGNED_BYTE, cp->texture);
#endif  
  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#ifdef MIPMAP
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
#else
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
#endif
}
Пример #28
0
vsSurface::vsSurface( const Settings& settings, bool depthOnly, bool multisample ):
	m_width(settings.width),
	m_height(settings.height),
	m_texture(0),
	m_textureCount(settings.buffers),
	m_depth(0),
	m_stencil(0),
	m_fbo(0),
	m_isRenderbuffer(false)
{
	CheckGLError("vsSurface");

	GLint maxSamples = 0;
	if ( multisample )
		glGetIntegerv(GL_MAX_SAMPLES, &maxSamples);

	GLenum internalFormat = GL_RGBA8;
	GLenum pixelFormat = GL_RGBA;
	GLenum type = GL_UNSIGNED_INT_8_8_8_8_REV;
	GLenum filter = settings.linear ? GL_LINEAR : GL_NEAREST;

	vsAssert( !( multisample && settings.mipMaps ), "Can't do both multisample and mipmaps!" );
	glActiveTexture(GL_TEXTURE0);

	// create FBO
	glGenFramebuffers(1, &m_fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);

	m_texture = new GLuint[m_textureCount];

	if ( depthOnly )
	{
		glDrawBuffer(GL_NONE);
		glReadBuffer(GL_NONE);
	}
	else
	{
		for ( int i = 0; i < m_textureCount; i++ )
		{
			if (multisample)
			{
				glGenRenderbuffers(1, &m_texture[i]);
				glBindRenderbuffer( GL_RENDERBUFFER, m_texture[i] );
				glRenderbufferStorageMultisample( GL_RENDERBUFFER, maxSamples, pixelFormat, m_width, m_height );
				glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+i, GL_RENDERBUFFER, m_texture[i]);
				m_isRenderbuffer = true;
			}
			else
			{
				glGenTextures(1, &m_texture[i]);
				glBindTexture(GL_TEXTURE_2D, m_texture[i]);
				m_isRenderbuffer = false;
				glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, m_width, m_height, 0, pixelFormat, type, 0);
				glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+i, GL_TEXTURE_2D, m_texture[i], 0);
				if ( settings.mipMaps )
				{
					glGenerateMipmap(GL_TEXTURE_2D);
				}
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
				glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
				glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
				glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16.0f );
				glBindTexture(GL_TEXTURE_2D, 0);
			}
		}
	}

	if (settings.depth || depthOnly)
	{
		if ( multisample )
		{
			glGenRenderbuffers(1, &m_depth);
			glBindRenderbuffer(GL_RENDERBUFFER, m_depth);
			if ( settings.stencil )
			{
				glRenderbufferStorageMultisample( GL_RENDERBUFFER, maxSamples, GL_DEPTH24_STENCIL8, m_width, m_height );
				glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_depth);
			}
			else
			{
				glRenderbufferStorageMultisample( GL_RENDERBUFFER, maxSamples, GL_DEPTH_COMPONENT24, m_width, m_height );
			}
			glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depth);
		}
		else
		{
			glGenTextures(1, &m_depth);
			glBindTexture(GL_TEXTURE_2D, m_depth);
			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			//glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
			//glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE_ARB);
			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
			//glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);

			//if ( stencil )
			//{
			//glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
			//}
			//else
			{
				glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
			}
			glBindTexture(GL_TEXTURE_2D, 0);
			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depth, 0);
		}
	}

	CheckFBO();
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	CheckGLError("vsSurface");
}
Пример #29
0
/**
 * Grab the z/stencil/back/front image from the srcWin and display it
 * (possibly converted to grayscale) in the dstWin.
 */
static void
redraw(Display *dpy, Window srcWin, Window dstWin )
{
   GLubyte *image = malloc(Width * Height * 4);

   glXMakeCurrent(dpy, srcWin, Context);
   glPixelStorei(GL_PACK_ALIGNMENT, 1);
   if (Buffer == BACK_BUFFER) {
      glReadBuffer(GL_BACK);
      glReadPixels(0, 0, Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, image);
   }
   else if (Buffer == FRONT_BUFFER) {
      glReadBuffer(GL_FRONT);
      glReadPixels(0, 0, Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, image);
   }
   else if (Buffer == Z_BUFFER) {
      GLfloat *z = malloc(Width * Height * sizeof(GLfloat));
      int i;
      glReadPixels(0, 0, Width, Height, GL_DEPTH_COMPONENT, GL_FLOAT, z);
      for (i = 0; i < Width * Height; i++) {
         image[i*4+0] =
         image[i*4+1] =
         image[i*4+2] = (GLint) (255.0 * z[i]);
         image[i*4+3] = 255;
      }
      free(z);
   }
   else if (Buffer == STENCIL_BUFFER) {
      GLubyte *sten = malloc(Width * Height * sizeof(GLubyte));
      int i, min = 100, max = -1;
      float step;
      int sz;
      glGetIntegerv(GL_STENCIL_BITS, &sz);
      glReadPixels(0, 0, Width, Height,
                   GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, sten);
      /* find min/max for converting stencil to grayscale */
      for (i = 0; i < Width * Height; i++) {
         if (sten[i] < min)
            min = sten[i];
         if (sten[i] > max)
            max = sten[i];
      }
      if (min == max)
         step = 0;
      else
         step = 255.0 / (float) (max - min);
      for (i = 0; i < Width * Height; i++) {
         image[i*4+0] =
         image[i*4+1] =
         image[i*4+2] = (GLint) ((sten[i] - min) * step);
         image[i*4+3] = 255;
      }
      free(sten);
   }

   glXMakeCurrent(dpy, dstWin, Context);
   glWindowPos2iARB(0, 0);
   glDrawBuffer(GL_FRONT);
   glDrawPixels(Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, image);
   glFlush();

   free(image);
}
Пример #30
0
/* ARGSUSED5 */  /* Only Win32 uses gameMode parameter. */
GLUTwindow *
__glutCreateWindow(GLUTwindow * parent,
  int x, int y, int width, int height, int gameMode)
{
  GLUTwindow *window;
  XSetWindowAttributes wa;
  unsigned long attribMask;
  int winnum;
  int i;
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_fbconfig)
  GLXFBConfigSGIX fbc;
#else
  void *fbc;
#endif

#if defined(__OS2PM__)
 {
    extern HAB   hab;      /* PM anchor block handle         */
    CLASSINFO classinfo;

    if(!WinQueryClassInfo(hab,"GLUT", &classinfo) )
                               __glutOpenOS2Connection(NULL);
  }
#elif defined(_WIN32)
  WNDCLASS wc;
  int style;

  if (!GetClassInfo(GetModuleHandle(NULL), "GLUT", &wc)) {
    __glutOpenWin32Connection(NULL);
  }
#else
  if (!__glutDisplay) {
    __glutOpenXConnection(NULL);
  }
#endif

#ifndef __OS2PM__
  if (__glutGameModeWindow) {
    __glutFatalError("cannot create windows in game mode.");
  }
#endif

  winnum = getUnusedWindowSlot();
  window = (GLUTwindow *) malloc(sizeof(GLUTwindow));
  if (!window) {
    __glutFatalError("out of memory.");
  }
  window->num = winnum;

#if defined(__OS2PM__)
  /* Add this new window to the window list. */
  __glutWindowList[winnum] = window;
  window->shownState = -1;
#endif

#if !defined(_WIN32)  && !defined(__OS2PM__)
  window->vis = __glutDetermineWindowVisual(&window->treatAsSingle,
    &window->visAlloced, (void**) &fbc);
  if (!window->vis) {
    __glutFatalError(
      "visual with necessary capabilities not found.");
  }
  __glutSetupColormap(window->vis, &window->colormap, &window->cmap);
#endif
  window->eventMask = StructureNotifyMask | ExposureMask;

  attribMask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
  wa.background_pixmap = None;
  wa.border_pixel = 0;
  wa.colormap = window->cmap;
  wa.event_mask = window->eventMask;
  if (parent) {
    if (parent->eventMask & GLUT_HACK_STOP_PROPAGATE_MASK)
      wa.event_mask |= GLUT_HACK_STOP_PROPAGATE_MASK;
    attribMask |= CWDontPropagate;
    wa.do_not_propagate_mask = parent->eventMask & GLUT_DONT_PROPAGATE_FILTER_MASK;
  } else {
    wa.do_not_propagate_mask = 0;
  }

  /* Stash width and height before Win32's __glutAdjustCoords
     possibly overwrites the values. */
  window->width = width;
  window->height = height;
  window->forceReshape = True;
  window->ignoreKeyRepeat = False;

#if defined(__OS2PM__)

 {  ULONG flStyle=0;
    int ii;
    ERRORID  erridErrorCode;/* last error id code */
    extern HAB   hab;      /* PM anchor block handle         */

  if (parent) {
    flStyle = WS_CLIPCHILDREN|WS_VISIBLE;
  } else {
    if (gameMode) {
      /* Game mode window should be a WS_POPUP window to
         ensure that the taskbar is hidden by it.  A standard
         WS_OVERLAPPEDWINDOW does not hide the task bar. */
      flStyle = FCF_STANDARD |  WS_MAXIMIZED;
    } else {
      /* A standard toplevel window with borders and such. */
      flStyle = FCF_STANDARD | WS_CLIPCHILDREN;
//      flStyle = WS_OVERLAPPEDWINDOW;
    }
  }
{
 HWND  hwnd;                           /* Window     */
 ULONG ListBoxId;                      /* Window id  */
                                       /* (supplied by application) */


 HWND hwndClient;        /* handle to the client                 */
 HWND hwndFrame;         /* handle to the frame                  */
 PFNWP GenericWndProc;
 FRAMECDATA  fcd;
 RECTL  rect;     /* Boundary rectangle                   */



/************************************************/
// flCreate = (FCF_STANDARD) & ~FCF_TASKLIST;
/**********************************/
  if (parent)
  {   window->frame = NULL;

 hwnd = WinCreateWindow(parent->win,  /* Parent window             */
                        "GLUTCHILD",        /* Class name                */
                        "",    /* Window text               */
                        flStyle,       /* Window style              */
                        x, y,          /* Position (x,y)            */
                        width, height,      /* Size (width,height)       */
                        parent->win,    /* Owner window              */
                        HWND_TOP,      /* Sibling window            */
                        0,             /* Window id                 */
                        NULL,          /* Control data              */
                        NULL);         /* Pres parameters           */

 erridErrorCode = WinGetLastError(hab);
    window->win = hwnd;

  window->hdc = WinOpenWindowDC(window->win);
  window->hpsBuffer = hpsCurrent;


 rect.xLeft = x;
 rect.xRight = x+width;
 rect.yBottom = y;
 rect.yTop = y + height;

/***** else parent *****************************/
  } else {
        hwnd = WinCreateStdWindow(HWND_DESKTOP,
           0,       /* WS_VISIBLE frame-window style        */
           &flStyle,        /* window style                 */
           "GLUT",          /* class name                   */
           "GLUT",/* window title                  */
            0L,                  /* default client style          */
            NULLHANDLE,          /* resource in executable file   */
            ID_WINDOW,           /* resource id                   */
            &hwndClient);        /* receives client window handle */

 erridErrorCode = WinGetLastError(hab);
       window->win = hwndClient;
       window->frame = hwnd;
  window->hdc = WinOpenWindowDC(window->win);

  window->hpsBuffer = hpsCurrent;


/* converts a client window's boundaries into  an equivalent frame rectangle */
 rect.xLeft = x;
 rect.xRight = x+width;
 rect.yBottom = y;
 rect.yTop = y + height;

 /* calculate equivalent frame boundary from boundary data */
  WinCalcFrameRect(window->frame, &rect, FALSE);
 }
/***** endof if(parent) *****************************/

  /* Must set the XHDC for fake glXChooseVisual & fake
     glXCreateContext & fake XAllocColorCells. */
  XHDC = window->hdc;
  XHWND = window->win;
  window->vis = __glutDetermineWindowVisual(&window->treatAsSingle,
    &window->visAlloced, &fbc);
    if (!window->vis)
    {   __glutFatalError(
        "pixel format with necessary capabilities not found.");
    }
    { int rc;
      rc = wglChoosePixelFormat(window->hdc, window->vis),

//     evglSetPixelFormat(2); /* int iPixelFormat 1 - doublebuffer/2 - single buffer ??*/
      wglSetPixelFormat(window->hdc,rc,window->vis);
    }
   __glutSetupColormap(window->vis, &window->colormap, &window->cmap);

  window->ctx = glXCreateContext(window->hpsBuffer, window->vis,
    None, __glutTryDirect);

  WinSetWindowPos(hwnd,
                  HWND_TOP,rect.xLeft,rect.yBottom,
                  rect.xRight-rect.xLeft, rect.yTop-rect.yBottom,
      SWP_ACTIVATE | SWP_MOVE | SWP_SIZE | SWP_SHOW|SWP_ZORDER); /* flags*/

  /* Make sure subwindows get a windowStatus callback. */
  if (parent)
       WinPostMsg(parent->win, WM_ACTIVATE, 0, 0);

  }
}

#elif defined(_WIN32)

  __glutAdjustCoords(parent ? parent->win : NULL,
    &x, &y, &width, &height);
  if (parent) {
    style = WS_CHILD;
  } else {
    if (gameMode) {
      /* Game mode window should be a WS_POPUP window to
         ensure that the taskbar is hidden by it.  A standard
         WS_OVERLAPPEDWINDOW does not hide the task bar. */
      style = WS_POPUP | WS_MAXIMIZE;
    } else {
      /* A standard toplevel window with borders and such. */
      style = WS_OVERLAPPEDWINDOW;
    }
  }
  window->win = CreateWindow("GLUT", "GLUT",
    WS_CLIPSIBLINGS | WS_CLIPCHILDREN | style,
    x, y, width, height, parent ? parent->win : __glutRoot,
    NULL, GetModuleHandle(NULL), 0);
  window->hdc = GetDC(window->win);
  /* Must set the XHDC for fake glXChooseVisual & fake
     glXCreateContext & fake XAllocColorCells. */
  XHDC = window->hdc;
  window->vis = __glutDetermineWindowVisual(&window->treatAsSingle,
    &window->visAlloced, &fbc);
  if (!window->vis) {
    __glutFatalError(
      "pixel format with necessary capabilities not found.");
  }
  if (!SetPixelFormat(window->hdc,
      ChoosePixelFormat(window->hdc, window->vis),
      window->vis)) {
    __glutFatalError("SetPixelFormat failed during window create.");
  }
  __glutSetupColormap(window->vis, &window->colormap, &window->cmap);
  /* Make sure subwindows get a windowStatus callback. */
  if (parent) {
    PostMessage(parent->win, WM_ACTIVATE, 0, 0);
  }
  window->renderDc = window->hdc;
#else
  window->win = XCreateWindow(__glutDisplay,
    parent == NULL ? __glutRoot : parent->win,
    x, y, width, height, 0,
    window->vis->depth, InputOutput, window->vis->visual,
    attribMask, &wa);
#endif
  window->renderWin = window->win;
#if defined(GLX_VERSION_1_1) && defined(GLX_SGIX_fbconfig)
  if (fbc) {
    window->ctx = __glut_glXCreateContextWithConfigSGIX(__glutDisplay, fbc,
      GLX_RGBA_TYPE_SGIX, None, __glutTryDirect);
  } else
#endif
#if defined(__OS2PM__)
//    window->ctx = glXCreateContext(window->hpsBuffer, window->vis,
//      None, __glutTryDirect);
#else
    window->ctx = glXCreateContext(__glutDisplay, window->vis,
      None, __glutTryDirect);
#endif
  if (!window->ctx) {
    __glutFatalError(
      "failed to create OpenGL rendering context.");
  }
  window->renderCtx = window->ctx;
#if !defined(_WIN32) && !defined(__OS2PM__)
  window->isDirect = glXIsDirect(__glutDisplay, window->ctx);
  if (__glutForceDirect) {
    if (!window->isDirect)
      __glutFatalError("direct rendering not possible.");
  }
#endif

  window->parent = parent;
  if (parent) {
    window->siblings = parent->children;
    parent->children = window;
  } else {
    window->siblings = NULL;
  }
  window->overlay = NULL;
  window->children = NULL;
  window->display = __glutDefaultDisplay;
  window->reshape = __glutDefaultReshape;
  window->mouse = NULL;
  window->motion = NULL;
  window->passive = NULL;
  window->entry = NULL;
  window->keyboard = NULL;
  window->keyboardUp = NULL;
  window->windowStatus = NULL;
  window->visibility = NULL;
  window->special = NULL;
  window->specialUp = NULL;
  window->buttonBox = NULL;
  window->dials = NULL;
  window->spaceMotion = NULL;
  window->spaceRotate = NULL;
  window->spaceButton = NULL;
  window->tabletMotion = NULL;
  window->tabletButton = NULL;
#ifdef _WIN32
  window->joystick = NULL;
  window->joyPollInterval = 0;
#endif

#if defined(__OS2PM__)
  window->wm_command = NULL;
#endif

  window->tabletPos[0] = -1;
  window->tabletPos[1] = -1;
#if defined(__OS2PM__)
  if(window->shownState == -1)
           window->shownState = 0;
   window->visState =  window->shownState;
#else
  window->shownState = 0;
  window->visState = -1;  /* not VisibilityUnobscured,
                             VisibilityPartiallyObscured, or
                             VisibilityFullyObscured */
#endif
  window->entryState = -1;  /* not EnterNotify or LeaveNotify */

  window->desiredConfMask = 0;
  window->buttonUses = 0;
  window->cursor = GLUT_CURSOR_INHERIT;

  /* Setup window to be mapped when glutMainLoop starts. */
  window->workMask = GLUT_MAP_WORK;
#ifdef _WIN32
  if (gameMode) {
    /* When mapping a game mode window, just show
       the window.  We have already created the game
       mode window with a maximize flag at creation
       time.  Doing a ShowWindow(window->win, SW_SHOWNORMAL)
       would be wrong for a game mode window since it
       would unmaximize the window. */
    window->desiredMapState = GameModeState;
  } else {
    window->desiredMapState = NormalState;
  }
#else
  window->desiredMapState = NormalState;
#endif
  window->prevWorkWin = __glutWindowWorkList;
  __glutWindowWorkList = window;

  /* Initially, no menus attached. */
  for (i = 0; i < GLUT_MAX_MENUS; i++) {
    window->menu[i] = 0;
  }

  /* Add this new window to the window list. */
  __glutWindowList[winnum] = window;

  /* Make the new window the current window. */
  __glutSetWindow(window);

  __glutDetermineMesaSwapHackSupport();

  if (window->treatAsSingle) {
    /* We do this because either the window really is single
       buffered (in which case this is redundant, but harmless,
       because this is the initial single-buffered context
       state); or we are treating a double buffered window as a
       single-buffered window because the system does not appear
       to export any suitable single- buffered visuals (in which
       the following are necessary). */
    glDrawBuffer(GL_FRONT);
    glReadBuffer(GL_FRONT);
  }
  return window;
}