Beispiel #1
0
bool GrGLRenderTarget::completeStencilAttachment() {
    GrGLGpu* gpu = this->getGLGpu();
    const GrGLInterface* interface = gpu->glInterface();
    GrStencilAttachment* stencil = this->renderTargetPriv().getStencilAttachment();
    if (nullptr == stencil) {
        GR_GL_CALL(interface, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                                      GR_GL_STENCIL_ATTACHMENT,
                                                      GR_GL_RENDERBUFFER, 0));
        GR_GL_CALL(interface, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                                      GR_GL_DEPTH_ATTACHMENT,
                                                      GR_GL_RENDERBUFFER, 0));
#ifdef SK_DEBUG
        if (kChromium_GrGLDriver != gpu->glContext().driver()) {
            // This check can cause problems in Chromium if the context has been asynchronously
            // abandoned (see skbug.com/5200)
            GrGLenum status;
            GR_GL_CALL_RET(interface, status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
            SkASSERT(GR_GL_FRAMEBUFFER_COMPLETE == status);
        }
#endif
        return true;
    } else {
        const GrGLStencilAttachment* glStencil = static_cast<const GrGLStencilAttachment*>(stencil);
        GrGLuint rb = glStencil->renderbufferID();

        gpu->invalidateBoundRenderTarget();
        gpu->stats()->incRenderTargetBinds();
        GR_GL_CALL(interface, BindFramebuffer(GR_GL_FRAMEBUFFER, this->renderFBOID()));
        GR_GL_CALL(interface, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                                      GR_GL_STENCIL_ATTACHMENT,
                                                      GR_GL_RENDERBUFFER, rb));
        if (glStencil->format().fPacked) {
            GR_GL_CALL(interface, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                                          GR_GL_DEPTH_ATTACHMENT,
                                                          GR_GL_RENDERBUFFER, rb));
        } else {
            GR_GL_CALL(interface, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                                          GR_GL_DEPTH_ATTACHMENT,
                                                          GR_GL_RENDERBUFFER, 0));
        }

#ifdef SK_DEBUG
        if (kChromium_GrGLDriver != gpu->glContext().driver()) {
            // This check can cause problems in Chromium if the context has been asynchronously
            // abandoned (see skbug.com/5200)
            GrGLenum status;
            GR_GL_CALL_RET(interface, status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
            SkASSERT(GR_GL_FRAMEBUFFER_COMPLETE == status);
        }
#endif
        return true;
    }
}
Beispiel #2
0
static void setup_framebuffer(const GrGLInterface* gl, int screenWidth, int screenHeight) {
    //Setup framebuffer
    GrGLuint texture;
    GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    GR_GL_CALL(gl, PixelStorei(GR_GL_PACK_ROW_LENGTH, 0));
    GR_GL_CALL(gl, GenTextures(1, &texture));
    GR_GL_CALL(gl, ActiveTexture(GR_GL_TEXTURE15));
    GR_GL_CALL(gl, BindTexture(GR_GL_TEXTURE_2D, texture));
    GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MAG_FILTER, GR_GL_NEAREST));
    GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MIN_FILTER, GR_GL_NEAREST));
    GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_WRAP_S, GR_GL_CLAMP_TO_EDGE));
    GR_GL_CALL(gl, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_WRAP_T, GR_GL_CLAMP_TO_EDGE));
    GR_GL_CALL(gl, TexImage2D(GR_GL_TEXTURE_2D,
                              0, //level
                              GR_GL_RGBA8, //internal format
                              screenWidth, // width
                              screenHeight, // height
                              0, //border
                              GR_GL_RGBA, //format
                              GR_GL_UNSIGNED_BYTE, // type
                              NULL));

    // bind framebuffer
    GrGLuint framebuffer;
    GR_GL_CALL(gl, BindTexture(GR_GL_TEXTURE_2D, 0));
    GR_GL_CALL(gl, GenFramebuffers(1, &framebuffer));
    GR_GL_CALL(gl, BindFramebuffer(GR_GL_FRAMEBUFFER, framebuffer));
    GR_GL_CALL(gl, FramebufferTexture2D(GR_GL_FRAMEBUFFER,
                                        GR_GL_COLOR_ATTACHMENT0,
                                        GR_GL_TEXTURE_2D,
                                        texture, 0));
    GR_GL_CALL(gl, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));
    GR_GL_CALL(gl, Viewport(0, 0, screenWidth, screenHeight));
}
bool
WebGLFramebuffer::HasCompletePlanes(GLbitfield mask)
{
    if (CheckFramebufferStatus() != LOCAL_GL_FRAMEBUFFER_COMPLETE)
        return false;

    MOZ_ASSERT(mContext->mBoundDrawFramebuffer == this ||
               mContext->mBoundReadFramebuffer == this);

    bool hasPlanes = true;
    if (mask & LOCAL_GL_COLOR_BUFFER_BIT)
        hasPlanes &= mColorAttachment0.IsDefined();

    if (mask & LOCAL_GL_DEPTH_BUFFER_BIT) {
        hasPlanes &= mDepthAttachment.IsDefined() ||
                     mDepthStencilAttachment.IsDefined();
    }

    if (mask & LOCAL_GL_STENCIL_BUFFER_BIT) {
        hasPlanes &= mStencilAttachment.IsDefined() ||
                     mDepthStencilAttachment.IsDefined();
    }

    return hasPlanes;
}
bool
test_fbo_attachments_layered()
{
	bool pass = true;
	GLuint fbo, texture[2];

	glGenFramebuffers(1, &fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, fbo);

	/* Attach first texture as a layered texture */
	texture[0] = create_bind_texture(GL_TEXTURE_3D);
	glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
			     texture[0], 0);

	/* Attach a single layer of the second texture.(Non layered) */
	texture[1] = create_bind_texture(GL_TEXTURE_3D);
	glFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
			       GL_TEXTURE_3D, texture[1], 0, 0);

	if(!piglit_check_gl_error(GL_NO_ERROR))
		piglit_report_result(PIGLIT_FAIL);

	pass = CheckFramebufferStatus(GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS)
		&& pass;

	glDeleteFramebuffers(1, &fbo);
	glDeleteTextures(2, texture);

	return pass;
}
bool
test_fbo_attachment_targets(GLenum texOneType, GLenum texTwoType,
				 GLenum expectedFbStatus)
{
	bool pass = true;
	GLuint fbo, texture[2];

	glGenTextures(2, texture);

	glGenFramebuffers(1, &fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, fbo);

	/* Setup texture one */
	texture[0] = create_bind_texture(texOneType);
	attach_texture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
		       texOneType, texture[0]);

	/* Setup texture two */
	texture[1] = create_bind_texture(texTwoType);
	attach_texture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
		       texTwoType, texture[1]);

	if(!piglit_check_gl_error(GL_NO_ERROR))
		piglit_report_result(PIGLIT_FAIL);

	/* Check for expected fb status */
	pass = CheckFramebufferStatus(expectedFbStatus) && pass;

	/* Clean up */
	glBindFramebuffer(GL_FRAMEBUFFER, piglit_winsys_fbo);
	glDeleteFramebuffers(1, &fbo);
	glDeleteTextures(2, texture);

	return pass;
}
Beispiel #6
0
	cFrameBuffer::cFrameBuffer(int e_iWidth,int e_iHeight,bool e_bDepthNeed,GLenum e_eImageType,GLenum e_eRGBDataType)
	{
	//Setting up a framebuffer for texturing
	//generate mipmap
	//glGenTextures(1, &img);
	//glBindTexture(GL_TEXTURE_2D, img);
	//glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,  width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
	//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_MAG_FILTER, GL_LINEAR);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	//glGenerateMipmapEXT(GL_TEXTURE_2D);

		m_bDepthNeed = e_bDepthNeed;
		m_uiWidth = e_iWidth;
		m_uiHeight = e_iHeight;
		m_eImageType = e_eImageType;
		m_eRGBDataType = e_eRGBDataType;
		//in openglES 2.0 glGenFramebuffers
		glGenFramebuffers(1, &m_uiFramebufferID); 
		{//glBindFramebuffer
			// Set up the FBO with one texture attachment 
			//in openglES 2.0 glBindFramebuffer
			glBindFramebuffer(GL_FRAMEBUFFER, m_uiFramebufferID);
			//initialize renderbuffer
			if( m_bDepthNeed )
			{
				glGenRenderbuffers(1, &this->m_uiRenderufferID);
				glBindRenderbuffer(GL_RENDERBUFFER, m_uiRenderufferID);
				glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, e_iWidth, e_iHeight);//GL_DEPTH_COMPONENT24
				//bind  render buffer with texture
				glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, 
								 GL_RENDERBUFFER, m_uiRenderufferID);
			}
			// Now setup a texture to render to
			glGenTextures(1, &m_uiTextureID);
			glBindTexture(GL_TEXTURE_2D, m_uiTextureID); 
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_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);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, e_iWidth, e_iHeight, 0,m_eImageType, m_eRGBDataType, nullptr);
			MyGlErrorTest();
			//  The following 3 lines enable mipmap filtering and generate the mipmap data so rendering works
			//	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			//	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
			//	glGenerateMipmapEXT(GL_TEXTURE_2D);
			//assign texture to framebuffer
			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
							GL_TEXTURE_2D, m_uiTextureID, 0);
		}
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		static bool	l_bCheck = false;
		if( !l_bCheck )
		{
			l_bCheck = true;
			bool	l_b = CheckFramebufferStatus();
			assert(l_b&&"display card is too old!!");
		}
	}
Beispiel #7
0
/*-------------------------------------------------------------------------

  -------------------------------------------------------------------------*/
bool FilterBox::Initialize(int w, int h)
{
  bufw = w;
  bufh = h;
  //
  // FBO
  //
  glGenFramebuffersEXT(2, fb);
  glGenTextures(2, textureID);
  glGenRenderbuffersEXT(1, &depth_rb);
  initRT(0, w, h);
  initRT(1, w, h);
  //
  // initialize depth renderbuffer
  //
  glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_rb);
  glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, w, h);
  glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, 
                                GL_RENDERBUFFER_EXT, depth_rb);
  CheckFramebufferStatus();

  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  //
  // CGFX things
  //
  cgContext = cgCreateContext();
  cgGLRegisterStates(cgContext);
  std::string resolved_path;

        cgEffect = cgCreateEffectFromFile(cgContext, "data/shaders/FilterBox.cgfx", NULL);
        if(!cgEffect)
        {
			exit(0);
            const char * pszErrors = NULL;
            fprintf(stderr, "CgFx Parse error : %s", pszErrors);
            const char *listing = cgGetLastListing(cgContext);
            bValid = false;
            return false;
        }
  cgTechnique = cgGetNamedTechnique(cgEffect, "Filter");
  cgPassFilterH = cgGetNamedPass(cgTechnique, "verticalPass");
  cgPassFilterV = cgGetNamedPass(cgTechnique, "horizontalPass");
  cgPassBlend   = cgGetNamedPass(cgTechnique, "drawFinal");
  cgBlendFactor = cgGetNamedEffectParameter(cgEffect, "blendFactor");
  cgGlowFactor  = cgGetNamedEffectParameter(cgEffect, "glowFactor");
  srcSampler    = cgGetNamedEffectParameter(cgEffect, "srcSampler");
  tempSampler   = cgGetNamedEffectParameter(cgEffect, "tempSampler");
  finalSampler  = cgGetNamedEffectParameter(cgEffect, "finalSampler");
  verticalDir   = cgGetNamedEffectParameter(cgEffect, "verticalDir");
  horizontalDir = cgGetNamedEffectParameter(cgEffect, "horizontalDir");

  cgGLSetParameter2f(verticalDir, 0,1.0f/(float)h);
  cgGLSetParameter2f(horizontalDir, 1.0f/(float)w, 0);

  bValid = true;
  return true;
}
void ObjMeshGPUDeformer_uUq_fbo::BindDynamicTextureToFBO()
{
  //printf("****Binding texture %d to fbo %d\n", dynamicTextureID, fbo);
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
  glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, 
                            GL_TEXTURE_2D, vertexDeformationTextureID, 0);
  CheckFramebufferStatus();
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
void EnvFBO::RecreateBuffers(const GLsizei width, const GLsizei height)  {
/*
    width /= 2 * 2;
    height /= 2 * 2;


*/

    LOG_I("create env fbo");

    m_size = width;

/*
	m_envMap = CubeMapTexture::Load(m_size);

	Texture::SetActiveTextureUnit(m_targetTextureUnit);
	m_envMap->Bind();
	{
	    m_envMap->SetMagMinFilters(GL_LINEAR);
	    m_envMap->SetTextureClamping();
	}
	m_envMap->Unbind();
*/

    Bind();
    {
	m_envMap = CubeMapTexture::Load(m_size);

	Texture::SetActiveTextureUnit(m_targetTextureUnit);
	m_envMap->Bind();
	{
	    m_envMap->SetTextureClamping();
	    m_envMap->GenerateMipmap();
	    m_envMap->SetMagMinFilters(GL_LINEAR);
	}
	m_envMap->Unbind();

	// next we create a depth buffer, and attach it to the FBO.

	m_depthBuffer = new RenderBuffer();
	m_depthBuffer->Bind();
	{
	    m_depthBuffer->RenderbufferStorage(GL_DEPTH_COMPONENT, m_size, m_size);

	    // attach the depth buffer to the FBO.
	    glFramebufferRenderbuffer(m_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER,m_depthBuffer->GetHandle());
	}
	m_depthBuffer->Unbind();

	CheckFramebufferStatus();

    }
    // switch to default frame buffer.
    Unbind();

}
Beispiel #10
0
void FBO::GenerateColorOnly( GLint iInternalFormat, GLint iFormat )
{
	Destroy();

	//Generate the texture
	glGenTextures(1, &m_iTexId[0]);
	glBindTexture(m_eTextureType, m_iTexId[0]);

	glTexParameteri (m_eTextureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri (m_eTextureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(m_eTextureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(m_eTextureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(m_eTextureType, GL_GENERATE_MIPMAP, GL_TRUE);

	///We need six Face for cube, or one for 2D
	if (m_eTextureType == GL_TEXTURE_CUBE_MAP)
	{
		glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X , 0, GL_RGBA8, m_iWidth, m_iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_Y , 0, GL_RGBA8, m_iWidth, m_iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_Z , 0, GL_RGBA8, m_iWidth, m_iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		glTexImage2D( GL_TEXTURE_CUBE_MAP_NEGATIVE_X , 0, GL_RGBA8, m_iWidth, m_iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		glTexImage2D( GL_TEXTURE_CUBE_MAP_NEGATIVE_Y , 0, GL_RGBA8, m_iWidth, m_iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		glTexImage2D( GL_TEXTURE_CUBE_MAP_NEGATIVE_Z , 0, GL_RGBA8, m_iWidth, m_iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
	}
	else
	{
		glTexImage2D(m_eTextureType, 0, iInternalFormat, m_iWidth, m_iHeight, 0, iFormat, GL_UNSIGNED_BYTE, 0);
	}

	glBindTexture(m_eTextureType, 0);

	//Generate renderbuffer
	glGenRenderbuffersEXT(1, &m_iRenderId);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_iRenderId);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, m_iWidth, m_iHeight);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

	//Generating ID
	glGenFramebuffersEXT(1, &m_iId);
	Activate();

	// attach a texture to FBO color attachement point
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, m_eTextureType, m_iTexId[0], 0);

	// attach a renderbuffer to depth attachment point
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_iRenderId);

	Deactivate();

	//Check FBO status
	if(!CheckFramebufferStatus())
		std::cerr<<"ERROR : FBO creation Fail "<<std::endl;

	//Color Only
	m_iType = 0;
}
Beispiel #11
0
void FBO::GenerateFinalHDRBuffer( GLint iInternalFormat0, GLint iFormat0, GLint iInternalFormat1, GLint iFormat1 )
{
	Destroy();

	//Generate the textures
	glGenTextures(1, &m_iTexId[0]);
	glBindTexture(m_eTextureType, m_iTexId[0]);

	glTexParameteri (m_eTextureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri (m_eTextureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(m_eTextureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(m_eTextureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(m_eTextureType, GL_GENERATE_MIPMAP, GL_TRUE);

	glTexImage2D(m_eTextureType, 0, iInternalFormat0, m_iWidth, m_iHeight, 0, iFormat0, GL_UNSIGNED_BYTE, 0);

	glGenTextures(1, &m_iTexId[1]);
	glBindTexture(m_eTextureType, m_iTexId[1]);

	glTexParameteri (m_eTextureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri (m_eTextureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(m_eTextureType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(m_eTextureType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(m_eTextureType, GL_GENERATE_MIPMAP, GL_TRUE);

	glTexImage2D(m_eTextureType, 0, iInternalFormat1, m_iWidth, m_iHeight, 0, iFormat1, GL_UNSIGNED_BYTE, 0);

	glBindTexture(m_eTextureType, 0);

	//Generate renderbuffer
	glGenRenderbuffersEXT(1, &m_iRenderId);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_iRenderId);
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, m_iWidth, m_iHeight);
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);

	//Generating ID
	glGenFramebuffersEXT(1, &m_iId);
	Activate();

	// attach a texture to FBO color attachement point
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, m_eTextureType, m_iTexId[0], 0);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, m_eTextureType, m_iTexId[1], 0);

	// attach a renderbuffer to depth attachment point
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_iRenderId);

	Deactivate();

	//Check FBO status
	if(!CheckFramebufferStatus())
		std::cerr<<"ERROR : FBO creation Fail "<<std::endl;

	//Color Only
	m_iType = 0;
}
	void GLWidgetSimpleShadow::makeShadowMap(GLWidget3D* glWidget3D){
	
		glDisable(GL_TEXTURE_2D);

		int origWidth=glWidget3D->width();
		int origHeigh=glWidget3D->height();
		

		// update camera fustrum (for overview)
		//updateSplitDist(glWidget3D->getCam()->f, 1.0f, FAR_DIST);//FAR_DIST/6 to display
		
		// generate shadow map using drawScene(1)
		glBindFramebuffer(GL_FRAMEBUFFER,FBO);
		glViewport(0,0,shadowWidth,shadowHeight);
		//glEnable(GL_CULL_FACE);
		//glCullFace(GL_FRONT);
		//glPolygonOffset( 1.0f, 4096.0f);
		glPolygonOffset( 1.1f, 4096.0f);
		glEnable(GL_POLYGON_OFFSET_FILL);
		// draw all faces since our terrain is not closed.
		//glDisable(GL_CULL_FACE);
		for(int i=0; i<cur_num_splits; i++){//cur_num_splits
			//clientMain->mGLWidget_3D->myCam->updateFrustumPoints(clientMain->mGLWidget_3D->myCam->f[i], clientMain->mGLWidget_3D->myCam->cam_pos, clientMain->mGLWidget_3D->myCam->cam_view);

			updateShadowMatrix(glWidget3D);
		
			glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowMap[i], 0);
			//glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMap[i], 0);
			glDrawBuffer(GL_NONE); // No color buffer is drawn to.
			CheckFramebufferStatus();
			glClear(GL_DEPTH_BUFFER_BIT);
			float light_mvpMatrixArray[16];
			for(int j=0;j<16;j++){
				light_mvpMatrixArray[j]=light_mvpMatrix.data()[j];
			}
			glUniformMatrix4fv(light_mvpMatrixLoc,1,GL_FALSE,light_mvpMatrixArray);
			//RENDER
			glWidget3D->drawScene(1);//1 light mode1
			
			// save camera for later
			shad_cpm[i]=light_mvpMatrix;
		}

		glBindFramebuffer(GL_FRAMEBUFFER,0);
		// revert to normal back face culling as used for rendering
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);
		glDisable(GL_POLYGON_OFFSET_FILL);
		glViewport(0,0,origWidth,origHeigh);

	}//
Beispiel #13
0
void intiFB(int w, int h)
{
	////////framebuffer init
	if(glIsTexture(tex))
	{
		glDeleteRenderbuffers(1, &depth_rb);
		glDeleteTextures(1,&tex);
		glDeleteFramebuffers(1, &fb);
	}

	glEnable(GL_DEPTH_TEST);
	glClearColor(0.0, 0.0, 0.0, 1.0);

	glGenFramebuffers(1, &fb);
	glGenTextures(1, &tex);
	glGenRenderbuffers(1, &depth_rb);

	glBindFramebuffer(GL_FRAMEBUFFER, fb);    

	// init texture
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texWidth, texHeight, 0, 
		GL_RGBA, GL_FLOAT, NULL);
	GET_GLERROR(NULL);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(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);

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 
		GL_TEXTURE_2D, tex, 0);

	GET_GLERROR(0);

	// initialize depth renderbuffer
	glBindRenderbufferEXT(GL_RENDERBUFFER, depth_rb);
	glRenderbufferStorageEXT(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, texWidth, texHeight);
	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, 
		GL_RENDERBUFFER, depth_rb);

	glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex, 0);

	GET_GLERROR(0);

	CheckFramebufferStatus();

	glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
}
Beispiel #14
0
void FilterBox::initRT(int n, int w, int h)
{
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb[n]);
  //
  // init texture
  //
  glBindTexture(GL_TEXTURE_2D, textureID[n]);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_FLOAT, NULL);
  //
  // SEEMS VERY IMPORTANT for the FBO to be valid. ARGL.
  //
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameterf(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);
  glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, textureID[n], 0);
  CheckFramebufferStatus();
}
Beispiel #15
0
/*
** Making the FBO surface ready to render
*/
AESDK_OpenGL_Err AESDK_OpenGL_MakeReadyToRender(AESDK_OpenGL_EffectCommonData& inData)
{
	AESDK_OpenGL_Err result = AESDK_OpenGL_OK;
	try
	{	
		// Bind the frame-buffer object and attach to it a render-buffer object set up as a depth-buffer.
		glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, inData.mFrameBufferSu);
			
		// Set the render target - primary surface
		glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
		
		if( CheckFramebufferStatus() != string("OK"))
			GL_CHECK(AESDK_OpenGL_Res_Load_Err);
	
	}
	catch(AESDK_OpenGL_Err& err)
	{
		result = err;
	}
	return result;
}
Beispiel #16
0
void FBO::Generate( GLint iInternalFormat, GLint iFormat )
{
	// create a texture object for the depthmap
	glGenTextures(1, &m_iTexDepthId);
	glBindTexture(m_eTextureType, m_iTexDepthId);
	glTexParameterf(m_eTextureType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameterf(m_eTextureType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameterf(m_eTextureType, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameterf(m_eTextureType, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri(m_eTextureType, GL_GENERATE_MIPMAP, GL_TRUE);
	glTexImage2D(m_eTextureType, 0, GL_DEPTH_COMPONENT24, m_iWidth, m_iHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
	glBindTexture(m_eTextureType, 0);

	// create a texture object
	glGenTextures(1, &m_iTexId[0]);
	glBindTexture(m_eTextureType, m_iTexId[0]);
	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);

	glTexImage2D(m_eTextureType, 0, iInternalFormat, m_iWidth, m_iHeight, 0, iFormat, GL_UNSIGNED_BYTE, 0);
	glBindTexture(m_eTextureType, 0);

	glGenFramebuffersEXT(1, &m_iId);
	Activate();

	// attach a texture to FBO color attachement point
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, m_eTextureType, m_iTexDepthId, 0);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, m_eTextureType, m_iTexId[0], 0);

	Deactivate();
	//Check FBO status
	if(!CheckFramebufferStatus())
		std::cerr<<"ERROR : FBO creation Fail "<<std::endl;

	//Color + Depth
	m_iType = 2;
}
Beispiel #17
0
void FBO::GenerateDepthOnly()
{
	Destroy();

	glGenTextures(1, &m_iTexDepthId);
	glBindTexture(m_eTextureType, m_iTexDepthId);

	//we create a special texture for depth
	glTexImage2D(m_eTextureType, 0, GL_DEPTH_COMPONENT, m_iWidth, m_iHeight, 0,GL_DEPTH_COMPONENT, GL_FLOAT, 0);
	glTexParameteri (m_eTextureType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri (m_eTextureType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	//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_DEPTH_TEXTURE_MODE, GL_INTENSITY);
	glTexParameteri(m_eTextureType, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(m_eTextureType, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glBindTexture(m_eTextureType, 0);

	//Generating ID
	glGenFramebuffersEXT(1, &m_iId);
	Activate();

	//We attach the texture to the depth attachment point
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,GL_DEPTH_ATTACHMENT_EXT,m_eTextureType, m_iTexDepthId, 0);

	//In order to avoid Color in the depth buffer
	glDrawBuffer(GL_NONE);
	glReadBuffer(GL_NONE);

	Deactivate();

	//Check FBO status
	if(!CheckFramebufferStatus())
		std::cerr<<"ERROR : FBO creation Fail "<<std::endl;

	//Depth Only
	m_iType = 1;
}
Beispiel #18
0
GLboolean CreateFB( GLuint shadow_sz, GLuint *FBO, GLuint *FBOdepth )
{
	if( *FBO )
		glDeleteFramebuffersEXT( 1, FBO  );
	if( *FBOdepth )
		glDeleteTextures( 1, FBOdepth );

	glGenFramebuffersEXT( 1, FBO  );
	glGenTextures( 1, FBOdepth );

	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, *FBO );

	//Initialize depth texture
	glBindTexture( GL_TEXTURE_2D, *FBOdepth );
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE_ARB );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL );
	glTexImage2D (GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadow_sz, shadow_sz, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
	glFramebufferTexture2DEXT (GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, *FBOdepth, 0);

        //No color buffer to draw to or read from
	glDrawBuffer(GL_FALSE);
	glReadBuffer(GL_FALSE);

	//Check if everything is as it should
	if (!CheckFramebufferStatus())
		return GL_FALSE;

	// Re-enable rendering to the window
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

	return GL_TRUE;
}
Beispiel #19
0
int FrameBufferObject::CreateImageObject(unsigned int width, unsigned int height, int depthbuffer_enabled, int stencilbuffer_enabled)
{
	//Create the Image object
	ImageObject new_object;
  EH_DECLARE;

	new_object.width		= width;
	new_object.height		= height;
	new_object.texture_type	= NULL;
	new_object.texture_id	= NULL;
	new_object.depth_id		= NULL;
	new_object.stencil_id	= NULL;

	EH_Log("CreateImageObject %d %d\n", width, height);

	//First determine if the requested dimensions are power of two
	if (ispoweroftwo(width) && ispoweroftwo(height))
	{
		new_object.texture_type = GL_TEXTURE_2D;	//Power of two enum
		EH_Log("Using GL_TEXTURE_2D");
	}
	else
	{
		new_object.texture_type = 0x84F5;			//Non power of two enum
	}


	//Create texture 
	glGenTextures(1, &new_object.texture_id);
    glBindTexture(new_object.texture_type, new_object.texture_id);
    glTexImage2D(new_object.texture_type, 0, GL_RGBA, new_object.width, new_object.height, 0, GL_RGBA, GL_FLOAT, NULL);
	//GLenum filterMode = (new_object.texture_type == 0x84F5) ? GL_NEAREST : GL_LINEAR;
	//GLenum filterMode = GL_NEAREST;
	GLfloat filterMode = GL_LINEAR;
    glTexParameterf(new_object.texture_type, GL_TEXTURE_MIN_FILTER, filterMode);
    glTexParameterf(new_object.texture_type, GL_TEXTURE_MAG_FILTER, filterMode);
    glTexParameterf(new_object.texture_type, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);//GL_CLAMP
    glTexParameterf(new_object.texture_type, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);//GL_CLAMP
#ifdef OM_MULTISAMPLE
	if (1) {
		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, framebuffer_id);
		glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, 2, GL_RGBA8, 
			new_object.width, new_object.height);
		CheckFramebufferStatus();
	}
#endif
	//Create the depth RenderBuffer if requested
	if (depthbuffer_enabled != 0)
	{
		glGenRenderbuffersEXT(1, &new_object.depth_id);
		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, new_object.depth_id);
		
		
#ifdef OM_MULTISAMPLE
		if (1) {
			//samples=2, format=GL_DEPTH_COMPONENT24, width=256, height=256
			glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, 2, GL_DEPTH_COMPONENT16, 
				new_object.width, new_object.height);
			CheckFramebufferStatus();
		} else
#endif
			glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, new_object.width, new_object.height);


		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer_id);
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, 
			GL_RENDERBUFFER_EXT, new_object.depth_id);
		//CheckFramebufferStatus();

	}
	//Create the stencil RenderBuffer if requested
	if (stencilbuffer_enabled != 0)
	{
		glGenRenderbuffersEXT(1, &new_object.stencil_id);
		glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, new_object.stencil_id);
		glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX,  new_object.width, new_object.height);
	}

	//Push this new image object onto the list
	image_objects.push_back(new_object);

	

	//Return the 'index' for the id of this texture
	return (int)image_objects.size() - 1;
}
Beispiel #20
0
real DrawVoronoi(real* xx)
{
	int i,j;

	real fEnergy = 1e20;

	GLfloat *buffer_screen = new GLfloat[screenwidth*screenheight*4];

	//////////////////////////////////////////////
	// First pass - Render the initial sites    //
	//////////////////////////////////////////////
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FB_objects);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[0], 
		GL_TEXTURE_RECTANGLE_NV, Processed_Texture[0], 0);
	CheckFramebufferStatus();

	glClearColor(-1, -1, -1, -1);
	glClear(GL_COLOR_BUFFER_BIT);

	glDrawBuffer(fbo_attachments[0]);

	cgGLEnableProfile(VertexProfile);
	cgGLEnableProfile(FragmentProfile);

	cgGLBindProgram(VP_DrawSites);
	cgGLBindProgram(FP_DrawSites);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(1, screenwidth+1, 1, screenheight+1);
	glViewport(1, 1, screenwidth, screenheight);

	DrawSites(xx, NULL);

	// glReadBuffer(fbo_attachments[0]);
	// imdebugPixelsf(0, 0, screenwidth+2, screenheight+2, GL_RGBA);

	Current_Buffer = 1;

	/////////////////////////////////////
	// Second pass - Flood the sites   //
	/////////////////////////////////////
	cgGLBindProgram(VP_Flood);
	cgGLBindProgram(FP_Flood);

	if (VP_Flood_Size != NULL)
		cgSetParameter2f(VP_Flood_Size, screenwidth, screenheight);

	bool ExitLoop = false;
	bool SecondExit;
	int steplength;;
	SecondExit = (additional_passes==0);
	bool PassesBeforeJFA;
	PassesBeforeJFA = (additional_passes_before>0);
	if (PassesBeforeJFA)
		steplength = pow(2.0, (additional_passes_before-1));
	else
		steplength = (screenwidth>screenheight ? screenwidth : screenheight)/2;

	while (!ExitLoop)
	{
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[Current_Buffer], 
			GL_TEXTURE_RECTANGLE_NV, Processed_Texture[Current_Buffer], 0);
		CheckFramebufferStatus();
		glDrawBuffer(fbo_attachments[Current_Buffer]);

		glClearColor(-1, -1, -1, -1);
		glClear(GL_COLOR_BUFFER_BIT);

		//Bind & enable shadow map texture
		glActiveTextureARB(GL_TEXTURE0_ARB);
		glBindTexture(GL_TEXTURE_RECTANGLE_NV, Processed_Texture[1-Current_Buffer]);
		if (VP_Flood_Steplength != NULL)
			cgSetParameter1d(VP_Flood_Steplength, steplength);

		glBegin(GL_QUADS);
			glVertex2f(1.0, 1.0);
			glVertex2f(1.0, float(screenheight+1));
			glVertex2f(float(screenwidth+1), float(screenheight+1));
			glVertex2f(float(screenwidth+1), 1.0);
		glEnd();
		glReadBuffer(fbo_attachments[Current_Buffer]);
		// imdebugPixelsf(0, 0, screenwidth+2, screenheight+2, GL_RGBA);

		if (steplength==1 && PassesBeforeJFA)
		{
			steplength = (screenwidth>screenheight ? screenwidth : screenheight)/2;
			PassesBeforeJFA = false;
		}
		else if (steplength>1)
			steplength /= 2;
		else if (SecondExit)
			ExitLoop = true;
		else
		{
			steplength = pow(2.0, (additional_passes-1));
			SecondExit = true;
		}
		Current_Buffer = 1-Current_Buffer;
	}
	glReadPixels(1,1,screenwidth,screenheight,GL_RGBA,GL_FLOAT,buffer_screen);

	///////////////////////////////
	// Test pass, Compute energy //
	///////////////////////////////
	int Current_Energy_Buffer = 0;
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[0], 
		GL_TEXTURE_RECTANGLE_NV, Energy_Texture[Current_Energy_Buffer], 0);
	CheckFramebufferStatus();
	glDrawBuffer(fbo_attachments[0]);

	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT);

	cgGLBindProgram(VP_ComputeEnergyCentroid);
	cgGLBindProgram(FP_ComputeEnergyCentroid);

	if (FP_ComputeEnergyCentroid_Size != NULL)
		cgSetParameter2f(FP_ComputeEnergyCentroid_Size, screenwidth, screenheight);

	glActiveTextureARB(GL_TEXTURE0_ARB);
	glBindTexture(GL_TEXTURE_RECTANGLE_ARB, Processed_Texture[1-Current_Buffer]);

	glBegin(GL_QUADS);
	glVertex2f(1.0, 1.0);
	glVertex2f(float(screenwidth+1), 1.0);
	glVertex2f(float(screenwidth+1), float(screenheight+1));
	glVertex2f(1.0, float(screenheight+1));
	glEnd();

	// glReadBuffer(fbo_attachments[0]);
	// imdebugPixelsf(0, 0, screenwidth+2, screenheight+2, GL_RGBA);

	Current_Energy_Buffer = 1-Current_Energy_Buffer;

	//////////////////////
	// perform reduction
	//////////////////////
	cgGLBindProgram(VP_Deduction);
	cgGLBindProgram(FP_Deduction);

	bool ExitEnergyLoop = false;
	int quad_size = int((screenwidth>screenheight?screenwidth:screenheight)/2.0+0.5);
	while (!ExitEnergyLoop)
	{
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[0], 
			GL_TEXTURE_RECTANGLE_NV, Energy_Texture[Current_Energy_Buffer], 0);
		CheckFramebufferStatus();
		glDrawBuffer(fbo_attachments[0]);

		glClearColor(0, 0, 0, 0);
		glClear(GL_COLOR_BUFFER_BIT);

		//Bind & enable shadow map texture
		glActiveTextureARB(GL_TEXTURE0_ARB);
		glBindTexture(GL_TEXTURE_RECTANGLE_ARB, Energy_Texture[1-Current_Energy_Buffer]);

		glBegin(GL_QUADS);
		glVertex2f(1.0, 1.0);
		glVertex2f(float(quad_size+1), 1.0);
		glVertex2f(float(quad_size+1), float(quad_size+1));
		glVertex2f(1.0, float(quad_size+1));
		glEnd();

		// glReadBuffer(fbo_attachments[0]);
		// imdebugPixelsf(0, 0, screenwidth+2, screenheight+2, GL_RGBA);

		if (quad_size>1)
		{
			int temp = quad_size/2;
			quad_size = temp*2==quad_size ? temp : temp+1;
		}
		else
			ExitEnergyLoop = true;
		Current_Energy_Buffer = 1-Current_Energy_Buffer;
	}
	float total_sum[4];
	// glReadBuffer(fbo_attachments[0]);
	// imdebugPixelsf(0, 0, screenwidth+2, screenheight+2, GL_RGBA);
	glReadPixels(1, 1, 1, 1, GL_RGBA, GL_FLOAT, &total_sum);
	printf("Energy: %f\n", total_sum[0]);
	fEnergy = total_sum[0];

	//////////////////////////////////////////
	// Third pass - Scatter points to sites //
	//////////////////////////////////////////
	cgGLBindProgram(VP_ScatterCentroid);
	cgGLBindProgram(FP_ScatterCentroid);

	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[0], 
		GL_TEXTURE_RECTANGLE_NV, Site_Texture, 0);
	CheckFramebufferStatus();
	glDrawBuffer(buffers[0]);

	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT);

	if (VP_ScatterCentroid_Size != NULL)
		cgSetParameter2f(VP_ScatterCentroid_Size, screenwidth, screenheight);

	//Bind & enable shadow map texture
	glActiveTextureARB(GL_TEXTURE0_ARB);
	glBindTexture(GL_TEXTURE_RECTANGLE_NV, Processed_Texture[1-Current_Buffer]);

	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
	glBegin(GL_POINTS);
	for (i=0; i<screenwidth; i++)
		for (j=0; j<screenheight; j++)
			glVertex2f(i+1.5, j+1.5);
	glEnd();
	glDisable(GL_BLEND);

	Current_Buffer = 1-Current_Buffer;

	///////////////////////////////////////
	// Fourth pass - Test stop condition //
	///////////////////////////////////////
	cgGLBindProgram(VP_DrawSitesOQ);
	cgGLBindProgram(FP_DrawSitesOQ);

	glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[2], GL_RENDERBUFFER_EXT, RB_object);
	CheckFramebufferStatus();
	glDrawBuffer(fbo_attachments[2]);

	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT);

	if (VP_DrawSitesOQ_Size != NULL)
		cgSetParameter2f(VP_DrawSitesOQ_Size, screenwidth, screenheight);

	//Bind & enable shadow map texture
	glActiveTextureARB(GL_TEXTURE0_ARB);
	glBindTexture(GL_TEXTURE_RECTANGLE_NV, Site_Texture);
	glActiveTextureARB(GL_TEXTURE1_ARB);
	glBindTexture(GL_TEXTURE_RECTANGLE_NV, Processed_Texture[Current_Buffer]);

	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
	glDepthMask(GL_FALSE);
	glBeginQueryARB(GL_SAMPLES_PASSED_ARB, occlusion_query);
	glBegin(GL_POINTS);
	for (i=0; i<point_num; i++)
	{
		float xx, yy;
		xx = i%screenwidth+1.5;
		yy = i/screenheight+1.5;
		glTexCoord1f(i);
		glVertex2f(xx, yy);
	}
	glEnd();
	glEndQueryARB(GL_SAMPLES_PASSED_ARB);
	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
	glDepthMask(GL_TRUE);

	// glReadBuffer(fbo_attachments[2]);
	// imdebugPixelsf(0, 0, screenwidth+2, screenheight+2, GL_RGBA);

	do{
		glGetQueryObjectivARB(occlusion_query, GL_QUERY_RESULT_AVAILABLE_ARB, &oq_available);
	}while(oq_available);
	glGetQueryObjectuivARB(occlusion_query, GL_QUERY_RESULT_ARB, &sampleCount);
	printf("sample count: %d\n", sampleCount);

	cgGLDisableProfile(VertexProfile);
	cgGLDisableProfile(FragmentProfile);

	////////////////////
	// compute measures
	////////////////////
	bool *bOnBoundary = new bool[point_num];
	bool *bIsHexagon = new bool[point_num];
	int *nNeighbors = new int[point_num*7];
	real *dDiameter = new real[point_num];
	real *dNeighborDist = new real[point_num];

	float site_pos[2], x, y, dist, neighbor_pos[2];
	int id, drow, dcol, nrow, ncol, neighbor_id, k;
	real dMaxDiameter, chi_id, chi;
	int nHex, nVC;

	for (id=0; id<point_num; id++)
	{
		bOnBoundary[id] = false;
		bIsHexagon[id] = true;
		nNeighbors[id*7] = 0;
		for (k=1; k<7; k++)
			nNeighbors[id*7+k] = -1;
		dDiameter[id] = -1;
		dNeighborDist[id] = 2*(screenwidth+screenheight);
	}
	dMaxDiameter = -1;
	chi = -1;
	nHex = nVC = 0;

	for (i=0; i<screenheight; i++)
	{
		for (j=0; j<screenwidth; j++)
		{
			site_pos[0] = buffer_screen[i*screenwidth*4+j*4];
			site_pos[1] = buffer_screen[i*screenwidth*4+j*4+1];
			id = int(buffer_screen[i*screenwidth*4+j*4+2]);
			x = j+1.5;
			y = i+1.5;
			site_pos[0] = (site_pos[0]-1)/screenwidth*2-1;
			site_pos[1] = (site_pos[1]-1)/screenheight*2-1;
			x = (x-1)/screenwidth*2-1;
			y = (y-1)/screenheight*2-1;
			dist = (x-site_pos[0])*(x-site_pos[0])+(y-site_pos[1])*(y-site_pos[1]);
			dist = sqrt(dist);
			dDiameter[id] = dDiameter[id]<dist ? dist : dDiameter[id];

			// traverse 9 neighbors
			for (drow=-1; drow<=1; drow++)
			{
				for (dcol=-1; dcol<=1; dcol++)
				{
					if (drow==0 && dcol==0)
						continue;
					nrow = i+drow;
					ncol = j+dcol;

					if (nrow<0 || nrow>=screenheight || ncol<0 || ncol>=screenwidth)
					{
						bOnBoundary[id] = true;
						continue;
					}

					neighbor_pos[0] = buffer_screen[nrow*screenwidth*4+ncol*4];
					neighbor_pos[1] = buffer_screen[nrow*screenwidth*4+ncol*4+1];
					neighbor_id = int(buffer_screen[nrow*screenwidth*4+ncol*4+2]);
					neighbor_pos[0] = (neighbor_pos[0]-1)/screenwidth*2-1;
					neighbor_pos[1] = (neighbor_pos[1]-1)/screenheight*2-1;
					if (neighbor_id==id)
						continue;

					dist = (neighbor_pos[0]-site_pos[0])*(neighbor_pos[0]-site_pos[0])
						   +(neighbor_pos[1]-site_pos[1])*(neighbor_pos[1]-site_pos[1]);
					dist = sqrt(dist);
					dNeighborDist[id] = dNeighborDist[id]>dist ? dist : dNeighborDist[id];

					for (k=1; k<7; k++)
					{
						if (nNeighbors[id*7+k]<0)
						{
							nNeighbors[id*7+k] = neighbor_id;
							nNeighbors[id*7]++;
							break;
						}
						else if (nNeighbors[id*7+k]==neighbor_id)
							break;
					}
					if (k==7)
						bIsHexagon[id] = false;
				}
			}
		}
	}
	for (id=0; id<point_num; id++)
	{
		if (nNeighbors[id*7]!=6)
			bIsHexagon[id] = false;
	}
	for (id=0; id<point_num; id++)
	{
		dMaxDiameter = dMaxDiameter<dDiameter[id] ? dDiameter[id] : dMaxDiameter;
		chi_id = 2*dDiameter[id]/dNeighborDist[id];
		chi = chi<chi_id ? chi_id : chi;
		if (!bOnBoundary[id])
		{
			nVC++;
		}
		if (bIsHexagon[id])
		{
			nHex++;
		}
	}

	printf("\n==== measures ====\n");
	printf("Number of VC in the middle: %d\n", nVC);
	printf("Number of hexagons: %d\n", nHex);
	printf("h: %f\n", dMaxDiameter);
	printf("chi: %f\n", chi);
	printf("==== measures ====\n\n");

	////////////////////
	// Fill Octagon & another
	////////////////////
	GLubyte *ColorTexImage = new GLubyte[screenwidth*screenheight*4];
	for (i=0; i<screenheight; i++)
	{
		for (j=0; j<screenwidth; j++)
		{
			int id = i*screenwidth+j;
			if (id<point_num)
			{
				if (bIsHexagon[id])
				{
					ColorTexImage[id*4] = 255;
					ColorTexImage[id*4+1] = 255; 
					ColorTexImage[id*4+2] = 255;
					ColorTexImage[id*4+3] = 255;
				}
				else
				{
					ColorTexImage[id*4] = 192;
					ColorTexImage[id*4+1] = 192; 
					ColorTexImage[id*4+2] = 192;
					ColorTexImage[id*4+3] = 255;
				}
			}
			else
			{
					ColorTexImage[id*4] = 
					ColorTexImage[id*4+1] = 
					ColorTexImage[id*4+2] = 
					ColorTexImage[id*4+3] = 0.0;
			}
		}
	}
	glActiveTextureARB(GL_TEXTURE2_ARB);
	glGenTextures(1, &Color_Texture);
	glBindTexture(GL_TEXTURE_RECTANGLE_NV, Color_Texture);
	glTexParameteri(GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexImage2D(GL_TEXTURE_RECTANGLE_NV, 0, GL_RGBA, screenwidth,
		screenheight, 0, GL_RGBA, GL_UNSIGNED_BYTE, ColorTexImage);

	delete ColorTexImage;

	delete [] buffer_screen;
	delete [] bOnBoundary;
	delete [] bIsHexagon;
	delete [] nNeighbors;
	delete [] dDiameter;
	delete [] dNeighborDist;

	///////////////////////////////////
	// Last pass, Display the result //
	///////////////////////////////////
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);    

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0, screenwidth-1, 0, screenheight-1);
	glViewport(0, 0, screenwidth, screenheight);

	glActiveTextureARB(GL_TEXTURE0_ARB);
	glBindTexture(GL_TEXTURE_RECTANGLE_NV, Processed_Texture[Current_Buffer]);
	glActiveTextureARB(GL_TEXTURE1_ARB);
	glBindTexture(GL_TEXTURE_RECTANGLE_NV, Site_Texture);

	cgGLEnableProfile(VertexProfile);
	cgGLEnableProfile(FragmentProfile);

	cgGLBindProgram(VP_FinalRender);
	cgGLBindProgram(FP_FinalRender);

	if (FP_FinalRender_Size != NULL)
		cgSetParameter2f(FP_FinalRender_Size, screenwidth, screenheight);

	// Set parameters of fragment program

	glBegin(GL_QUADS);
		glVertex2f(0.0, 0.0);
		glVertex2f(0.0, float(screenheight));
		glVertex2f(float(screenwidth), float(screenheight));
		glVertex2f(float(screenwidth), 0.0);
	glEnd();

	cgGLDisableProfile(VertexProfile);
	cgGLDisableProfile(FragmentProfile);

	DrawSites(xx, NULL);

	return fEnergy;
}
bool
WebGLFramebuffer::CheckAndInitializeAttachments()
{
    MOZ_ASSERT(mContext->mBoundDrawFramebuffer == this ||
               mContext->mBoundReadFramebuffer == this);

    if (CheckFramebufferStatus() != LOCAL_GL_FRAMEBUFFER_COMPLETE)
        return false;

    // Cool! We've checked out ok. Just need to initialize.
    const size_t moreColorAttachmentCount = mMoreColorAttachments.Length();

    // Check if we need to initialize anything
    {
        bool hasUninitializedAttachments = false;

        if (mColorAttachment0.HasImage())
            hasUninitializedAttachments |= mColorAttachment0.HasUninitializedImageData();
        if (mDepthAttachment.HasImage())
            hasUninitializedAttachments |= mDepthAttachment.HasUninitializedImageData();
        if (mStencilAttachment.HasImage())
            hasUninitializedAttachments |= mStencilAttachment.HasUninitializedImageData();
        if (mDepthStencilAttachment.HasImage())
            hasUninitializedAttachments |= mDepthStencilAttachment.HasUninitializedImageData();

        for (size_t i = 0; i < moreColorAttachmentCount; i++) {
            if (mMoreColorAttachments[i].HasImage())
                hasUninitializedAttachments |= mMoreColorAttachments[i].HasUninitializedImageData();
        }

        if (!hasUninitializedAttachments)
            return true;
    }

    // Get buffer-bit-mask and color-attachment-mask-list
    uint32_t mask = 0;
    bool colorAttachmentsMask[WebGLContext::kMaxColorAttachments] = { false };
    MOZ_ASSERT(1 + moreColorAttachmentCount <= WebGLContext::kMaxColorAttachments);

    if (mColorAttachment0.HasUninitializedImageData()) {
        colorAttachmentsMask[0] = true;
        mask |= LOCAL_GL_COLOR_BUFFER_BIT;
    }

    if (mDepthAttachment.HasUninitializedImageData() ||
        mDepthStencilAttachment.HasUninitializedImageData())
    {
        mask |= LOCAL_GL_DEPTH_BUFFER_BIT;
    }

    if (mStencilAttachment.HasUninitializedImageData() ||
        mDepthStencilAttachment.HasUninitializedImageData())
    {
        mask |= LOCAL_GL_STENCIL_BUFFER_BIT;
    }

    for (size_t i = 0; i < moreColorAttachmentCount; i++) {
        if (mMoreColorAttachments[i].HasUninitializedImageData()) {
          colorAttachmentsMask[1 + i] = true;
          mask |= LOCAL_GL_COLOR_BUFFER_BIT;
        }
    }

    // Clear!
    mContext->ForceClearFramebufferWithDefaultValues(false, mask, colorAttachmentsMask);

    // Mark all the uninitialized images as initialized.
    if (mColorAttachment0.HasUninitializedImageData())
        mColorAttachment0.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);
    if (mDepthAttachment.HasUninitializedImageData())
        mDepthAttachment.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);
    if (mStencilAttachment.HasUninitializedImageData())
        mStencilAttachment.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);
    if (mDepthStencilAttachment.HasUninitializedImageData())
        mDepthStencilAttachment.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);

    for (size_t i = 0; i < moreColorAttachmentCount; i++) {
        if (mMoreColorAttachments[i].HasUninitializedImageData())
            mMoreColorAttachments[i].SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);
    }

    return true;
}
Beispiel #22
0
bool SkGLContext::init(int width, int height) {
    if (fGL) {
        fGL->unref();
        this->destroyGLContext();
    }

    fGL = this->createGLContext();
    if (fGL) {
        // clear any existing GL erorrs
        GrGLenum error;
        do {
            error = SK_GL(*this, GetError());
        } while (GR_GL_NO_ERROR != error);
        GrGLuint cbID;
        GrGLuint dsID;
        SK_GL(*this, GenFramebuffers(1, &fFBO));
        SK_GL(*this, BindFramebuffer(GR_GL_FRAMEBUFFER, fFBO));
        SK_GL(*this, GenRenderbuffers(1, &cbID));
        SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, cbID));
        if (fGL->supportsES2()) {
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             GR_GL_RGBA8,
                                             width, height));
        } else {
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             GR_GL_RGBA,
                                             width, height));
        }
        SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                             GR_GL_COLOR_ATTACHMENT0,
                                             GR_GL_RENDERBUFFER, 
                                             cbID));
        SK_GL(*this, GenRenderbuffers(1, &dsID));
        SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, dsID));
        if (fGL->supportsES2()) {
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             GR_GL_STENCIL_INDEX8,
                                             width, height));
        } else {
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             GR_GL_DEPTH_STENCIL,
                                             width, height));
            SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                                 GR_GL_DEPTH_ATTACHMENT,
                                                 GR_GL_RENDERBUFFER,
                                                 dsID));
        }
        SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                             GR_GL_STENCIL_ATTACHMENT,
                                             GR_GL_RENDERBUFFER,
                                             dsID));
        SK_GL(*this, Viewport(0, 0, width, height));
        SK_GL(*this, ClearStencil(0));
        SK_GL(*this, Clear(GR_GL_STENCIL_BUFFER_BIT));
        
        error = SK_GL(*this, GetError());
        GrGLenum status =
            SK_GL(*this, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));

        if (GR_GL_FRAMEBUFFER_COMPLETE != status ||
            GR_GL_NO_ERROR != error) {
            fFBO = 0;
            fGL->unref();
            fGL = NULL;
            this->destroyGLContext();
            return false;
        } else {
            return true;
        }
    }
    return false;
}
bool SkGLContextHelper::init(int width, int height) {
    if (fGL) {
        fGL->unref();
        this->destroyGLContext();
    }

    fGL = this->createGLContext();
    if (fGL) {
        const GrGLubyte* temp;

        GrGLBinding bindingInUse = GrGLGetBindingInUse(this->gl());

        if (!fGL->validate(bindingInUse) || !fExtensions.init(bindingInUse, fGL)) {
            fGL = NULL;
            this->destroyGLContext();
            return false;
        }

        SK_GL_RET(*this, temp, GetString(GR_GL_VERSION));
        const char* versionStr = reinterpret_cast<const char*>(temp);
        GrGLVersion version = GrGLGetVersionFromString(versionStr);

        // clear any existing GL erorrs
        GrGLenum error;
        do {
            SK_GL_RET(*this, error, GetError());
        } while (GR_GL_NO_ERROR != error);

        SK_GL(*this, GenFramebuffers(1, &fFBO));
        SK_GL(*this, BindFramebuffer(GR_GL_FRAMEBUFFER, fFBO));
        SK_GL(*this, GenRenderbuffers(1, &fColorBufferID));
        SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, fColorBufferID));
        if (kES_GrGLBinding == bindingInUse) {
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             GR_GL_RGBA8,
                                             width, height));
        } else {
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             GR_GL_RGBA,
                                             width, height));
        }
        SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                             GR_GL_COLOR_ATTACHMENT0,
                                             GR_GL_RENDERBUFFER,
                                             fColorBufferID));
        SK_GL(*this, GenRenderbuffers(1, &fDepthStencilBufferID));
        SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, fDepthStencilBufferID));

        // Some drivers that support packed depth stencil will only succeed
        // in binding a packed format an FBO. However, we can't rely on packed
        // depth stencil being available.
        bool supportsPackedDepthStencil;
        if (kES_GrGLBinding == bindingInUse) {
            supportsPackedDepthStencil = version >= GR_GL_VER(3,0) ||
                                         this->hasExtension("GL_OES_packed_depth_stencil");
        } else {
            supportsPackedDepthStencil = version >= GR_GL_VER(3,0) ||
                                         this->hasExtension("GL_EXT_packed_depth_stencil") ||
                                         this->hasExtension("GL_ARB_framebuffer_object");
        }

        if (supportsPackedDepthStencil) {
            // ES2 requires sized internal formats for RenderbufferStorage
            // On Desktop we let the driver decide.
            GrGLenum format = kES_GrGLBinding == bindingInUse ?
                                    GR_GL_DEPTH24_STENCIL8 :
                                    GR_GL_DEPTH_STENCIL;
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             format,
                                             width, height));
            SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                                 GR_GL_DEPTH_ATTACHMENT,
                                                 GR_GL_RENDERBUFFER,
                                                 fDepthStencilBufferID));
        } else {
            GrGLenum format = kES_GrGLBinding == bindingInUse ?
                                    GR_GL_STENCIL_INDEX8 :
                                    GR_GL_STENCIL_INDEX;
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             format,
                                             width, height));
        }
        SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                             GR_GL_STENCIL_ATTACHMENT,
                                             GR_GL_RENDERBUFFER,
                                             fDepthStencilBufferID));
        SK_GL(*this, Viewport(0, 0, width, height));
        SK_GL(*this, ClearStencil(0));
        SK_GL(*this, Clear(GR_GL_STENCIL_BUFFER_BIT));

        SK_GL_RET(*this, error, GetError());
        GrGLenum status;
        SK_GL_RET(*this, status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));

        if (GR_GL_FRAMEBUFFER_COMPLETE != status ||
            GR_GL_NO_ERROR != error) {
            fFBO = 0;
            fColorBufferID = 0;
            fDepthStencilBufferID = 0;
            fGL->unref();
            fGL = NULL;
            this->destroyGLContext();
            return false;
        } else {
            return true;
        }
    }
    return false;
}
Beispiel #24
0
	void VrmlGame::Draw3D( const GLWindow2 &glWindow, Map &map, SE3<> se3CfromW, GLuint fboId, GLenum *buffers, ATANCamera &mCamera, int statusFlag)
	{
		if(!mbInitialised) {
			Init();
		}
		GetMatrixMP(map);
		GLfloat temp_trans[] = {mP(0,0), mP(0,1), mP(0,2), mP(0,3), mP(1,0), mP(1,1), mP(1,2), mP(1,3), mP(2,0), mP(2,1), mP(2,2), mP(2,3), mP(3,0), mP(3,1), mP(3,2), mP(3,3)};
		
		//add at 2.23
		//读取阴影明暗变量
		std::string filename = "variable.txt";
		std::ifstream variableFile;
		float shadowvariable;
		int light_count;
		variableFile.open(filename.c_str());
		if (!variableFile)
		{
			cout << "can't open the variable file" <<endl;
		}
		variableFile>>shadowvariable;
		variableFile>>light_count;

		if (statusFlag != 2 )
		{
			//shadow
			glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboShadowId);
			CheckFramebufferStatus();
			glUseProgramObjectARB(0);
			glViewport(0,0,RENDER_WIDTH*SHADOW_WAP_RATIO,RENDER_HEIGHT*SHADOW_WAP_RATIO);
			glClear(GL_DEPTH_BUFFER_BIT);
			glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
			//setup matrices
			glEnable(GL_DEPTH_TEST);
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
			gluPerspective(45,RENDER_WIDTH/RENDER_HEIGHT,3,40000);

			glDisable(GL_BLEND);
			glEnable(GL_DEPTH_TEST);
			glDepthFunc(GL_LEQUAL);
			glEnable(GL_NORMALIZE);
			glEnable(GL_COLOR_MATERIAL);
			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();
			gluLookAt(0.0, 10.0, 0.0, -10.0, -100.0, 0.0, 0.0, 1.0, 0.0);
			//消除自我阴影
			glEnable(GL_CULL_FACE);  //之前没有加这句话,所以Front没有被剔除
			glCullFace(GL_FRONT);
			DrawMediatorAndObject(statusFlag);  //需要设置texture7
			SetTextureMatrix();  //设置texture7
		}
 		
		

		//add 12.8  draw virtual object
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,fboId);
		//ATTACHMENT0---TEX_BUFF1
		CheckFramebufferStatus();
		glViewport(0,0,RENDER_WIDTH,RENDER_HEIGHT);
		glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);  //
		glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		//glDisable(GL_CULL_FACE);
		//glCullFace(GL_BACK);
		glEnable(GL_DEPTH_TEST);
		// Set up 3D projection
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glMultMatrix(mCamera.MakeUFBLinearFrustumMatrix(0.005, 100));
		glMultMatrix(se3CfromW);
		
	    //opengl staff
		glDisable(GL_BLEND);
		glEnable(GL_DEPTH_TEST);
		glDepthFunc(GL_LEQUAL);
 		glEnable(GL_NORMALIZE);
 		glEnable(GL_COLOR_MATERIAL);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
 		glMultMatrix(SE3<>());
 		glMultMatrixf(temp_trans);


		
		phongShadow.UseShader(true);
		glEnable(GL_TEXTURE_2D);
		//if (statusFlag != 2 )
		//{
			//phongShadow.SetUniVar("xPixelOffset", 1.0f/ (640.0f* 2));
			//phongShadow.SetUniVar("yPixelOffset", 1.0f/ (480.0f* 2));
			phongShadow.SetSampler("ShadowMap",7);
			glActiveTexture(GL_TEXTURE7);
			glBindTexture(GL_TEXTURE_2D, depthTextureId);
		//}
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);
		DrawMediatorAndObject(statusFlag);
		//if (statusFlag != 2 )
		//{
			glActiveTexture(GL_TEXTURE7);
			glBindTexture(GL_TEXTURE_2D, 0);
		//}
		glDisable(GL_TEXTURE_2D);
		glDisable(GL_CULL_FACE);
		phongShadow.UseShader(false);

		////test shadow mapping
		//貌似这段程序没法画出深度图,不过印象中之前可以的啊  ---2.23
		/*glUseProgramObjectARB(0);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(-RENDER_WIDTH/2,RENDER_WIDTH/2,-RENDER_HEIGHT/2,RENDER_HEIGHT/2,1,20);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glColor4f(1,1,1,1);
		glActiveTextureARB(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D,depthTextureId);
		glEnable(GL_TEXTURE_2D);
		glTranslated(0,0,-1);
		glBegin(GL_QUADS);
		glTexCoord2d(0,0);glVertex3f(0,0,0);
		glTexCoord2d(1,0);glVertex3f(RENDER_WIDTH/2,0,0);
		glTexCoord2d(1,1);glVertex3f(RENDER_WIDTH/2,RENDER_HEIGHT/2,0);
		glTexCoord2d(0,1);glVertex3f(0,RENDER_HEIGHT/2,0);
		glEnd();
		glDisable(GL_TEXTURE_2D);*/

		glDisable(GL_LIGHTING);
		glDisable(GL_DEPTH_TEST);
	}
void FrameBufferObject::init(unsigned int width, unsigned int height,
		const unsigned int* colorBufferInternalFormat, 
		const unsigned int* colorBufferSWRAP,
		const unsigned int* colorBufferTWRAP,
		const unsigned int* colorBufferMinFiltering,
		const unsigned int* colorBufferMagFiltering,
		FBO_DepthBufferType depthBufferType,
		const unsigned int depthBufferMinFiltering,
		const unsigned int depthBufferMagFiltering,
		const unsigned int depthBufferSWRAP,
		const unsigned int depthBufferTWRAP,
		bool depthTextureCompareToR) {
	
	/////////////////INITIALIZATION/////////////////
    this->width = width;
    this->height = height;

	//color render buffer
	if(this->nbColorAttachement>0)
	{
		colorTextures = new GLuint[nbColorAttachement];
		colorMinificationFiltering = new GLuint[nbColorAttachement];
		for(int i=0; i<this->nbColorAttachement; i++)
		{
			glGenTextures(1, &colorTextures[i]);
			glBindTexture(GL_TEXTURE_2D, colorTextures[i]);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, colorBufferMinFiltering[i]);
			this->colorMinificationFiltering[i] = colorBufferMinFiltering[i];
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, colorBufferMagFiltering[i]);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, colorBufferSWRAP[i]);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, colorBufferTWRAP[i]);
			glTexImage2D(GL_TEXTURE_2D, 0, colorBufferInternalFormat[i], width, height, 0, GL_RGBA, GL_FLOAT, NULL);

			if(this->colorMinificationFiltering[i]==GL_NEAREST_MIPMAP_NEAREST
			|| this->colorMinificationFiltering[i]==GL_LINEAR_MIPMAP_NEAREST
			||this->colorMinificationFiltering[i]==GL_NEAREST_MIPMAP_LINEAR
			|| this->colorMinificationFiltering[i]==GL_LINEAR_MIPMAP_LINEAR)
			{
				glGenerateMipmapEXT(GL_TEXTURE_2D);
			}
		}
	}

	//depth render buffer
	this->depthType = depthBufferType;
	if(this->depthType!=FBO_DepthBufferType_NONE)
	{
		switch(this->depthType)
		{
		case FBO_DepthBufferType_TEXTURE:
			glGenTextures(1, &this->depthID);
			glBindTexture(GL_TEXTURE_2D, this->depthID);
			this->depthMinificationFiltering = depthBufferMinFiltering;
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, depthBufferMinFiltering);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, depthBufferMagFiltering);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, depthBufferSWRAP);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, depthBufferTWRAP);
			if(depthTextureCompareToR)
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE_ARB);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24_ARB, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);

			if(this->depthMinificationFiltering==GL_NEAREST_MIPMAP_NEAREST
			|| this->depthMinificationFiltering==GL_LINEAR_MIPMAP_NEAREST
			||this->depthMinificationFiltering==GL_NEAREST_MIPMAP_LINEAR
			|| this->depthMinificationFiltering==GL_LINEAR_MIPMAP_LINEAR)
			{
				glGenerateMipmapEXT(GL_TEXTURE_2D);
			}
			break;

		case FBO_DepthBufferType_RENDERTARGET:
		default:
			glGenRenderbuffersEXT(1, &this->depthID);
			glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, this->depthID);
			glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24_ARB, width, height);
			break;
		}
	}

	/////////////////ATTACHEMENT/////////////////
    glGenFramebuffersEXT(1, &fbo);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);

	//color render buffer attachement
	if(nbColorAttachement>0)
	{
		for(int i=0; i<this->nbColorAttachement; i++)
		{
			glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+i, GL_TEXTURE_2D, this->colorTextures[i], 0 );
		}
		glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
		glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
	}
	else
	{
		glReadBuffer(GL_NONE);
		glDrawBuffer(GL_NONE);
	}
	
	//depth render buffer attachement
	if(this->depthType!=FBO_DepthBufferType_NONE)
	{
		switch(this->depthType)
		{
		case FBO_DepthBufferType_TEXTURE:
			glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, this->depthID, 0);
			break;

		case FBO_DepthBufferType_RENDERTARGET:
		default:
			glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, this->depthID);
			break;
		}
	}

    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

	CheckFramebufferStatus(this->fbo);
}
void InitOpenGL()
{
	glewInit();

	//////////////////////////////////////////////////////
	//initialize and load shader
	GLuint new_shader = InitShader(vertex_shader.c_str(), fragment_shader.c_str());
	if (new_shader == -1)
	{
		glClearColor(1.0f, 0.0f, 1.0f, 0.0f);
	}
	else
	{
		glClearColor(0.35f, 0.35f, 0.35f, 0.0f);
		if (shader_program != -1)
		{
			glDeleteProgram(shader_program);
		}
		shader_program = new_shader;
	}

	//////////////////////////////////////////////////////
	//build reflected and reflect objects
	//load objects - cow, fish, sphere
	cow_mesh_data = LoadMesh(cow_mesh_name);
	fish_mesh_data = LoadMesh(fish_mesh_name);
	sphere_mesh_data = LoadMesh(sphere_mesh_name);

	//////////////////////////////////////////////////////
	//create a cubemap texture object and set empty texture images
	glGenTextures(1, &CubemapID);
	glBindTexture(GL_TEXTURE_CUBE_MAP, CubemapID);
	for (int i = 0; i < 6; i++)
	{
		glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, cubemapsize, cubemapsize, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
	}

	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

	//////////////////////////////////////////////////////
	//create the depth buffer for the framebuffer object
	glGenRenderbuffers(1, &RBOID);
	glBindRenderbuffer(GL_RENDERBUFFER, RBOID);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, cubemapsize, cubemapsize);

	//////////////////////////////////////////////////////
	//create the framebuffer object and attach the cubemap faces and the depth buffer
	glGenFramebuffers(1, &FBOID);
	glBindFramebuffer(GL_FRAMEBUFFER, FBOID);
	for (int i = 0; i < 6; i++)
	{
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, CubemapID, 0);
	}
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, RBOID);

	if (!CheckFramebufferStatus())
	{
		ExitGlut();
	}
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glEnable(GL_DEPTH_TEST);
}
Beispiel #27
0
// Function of L-BFGS-B
void funcgrad(real* x, real& f, real* g, const cudaStream_t& stream)
{
	int i,j;
	get_timestamp(start_time_func);

	//////////////////////////////////////////////
	// First pass - Render the initial sites    //
	//////////////////////////////////////////////

	// FB_objects에 Processed_Texture[0]을 반영
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FB_objects);
	// 결과가 Processed_Texture[0]에 반영되도록 설정
	// fbo_attachments는 ColorAttachemnt 번호
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[0],
		GL_TEXTURE_RECTANGLE_NV, Processed_Texture[0], 0);
	CheckFramebufferStatus();

	// 출력할 버퍼를 선정
	glDrawBuffer(fbo_attachments[0]);
	glClearColor(-1, -1, -1, -1);
	glClear(GL_COLOR_BUFFER_BIT);

	cgGLEnableProfile(VertexProfile);
	cgGLEnableProfile(FragmentProfile);

	cgGLBindProgram(VP_DrawSites);
	cgGLBindProgram(FP_DrawSites);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(1, screenwidth+1, 1, screenheight+1);
	glViewport(1, 1, screenwidth, screenheight);

	DrawSites(x, stream);

	// glReadBuffer(fbo_attachments[0]);
	// imdebugPixelsf(0, 0, screenwidth+2, screenheight+2, GL_RGBA, "funcgrad - First Pass");

	Current_Buffer = 1; // 다음에 사용할 Texture를 선정

	/////////////////////////////////////
	// Second pass - Flood the sites   //
	/////////////////////////////////////
	cgGLBindProgram(VP_Flood);
	cgGLBindProgram(FP_Flood);

	if (VP_Flood_Size != NULL)
		cgSetParameter2f(VP_Flood_Size, screenwidth, screenheight);

	bool ExitLoop = false;
	bool SecondExit;
	int steplength;;
	SecondExit = (additional_passes==0);
	bool PassesBeforeJFA;
	PassesBeforeJFA = (additional_passes_before>0);
	if (PassesBeforeJFA)
		steplength = pow(2.0, (additional_passes_before-1));
	else
		steplength = (screenwidth>screenheight ? screenwidth : screenheight)/2;

	while (!ExitLoop)
	{
		// Pixel 단위로 값을 저장하고 있는 Processed_Texture를 VertextBuffer로 사용???
		glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[Current_Buffer], 
			GL_TEXTURE_RECTANGLE_NV, Processed_Texture[Current_Buffer], 0);
		CheckFramebufferStatus();
		glDrawBuffer(fbo_attachments[Current_Buffer]);

		glClearColor(-1, -1, -1, -1);
		glClear(GL_COLOR_BUFFER_BIT);

		//Bind & enable shadow map texture
		glActiveTextureARB(GL_TEXTURE0_ARB);
		glBindTexture(GL_TEXTURE_RECTANGLE_NV, Processed_Texture[1-Current_Buffer]);
		if (VP_Flood_Steplength != NULL)
			cgSetParameter1d(VP_Flood_Steplength, steplength);

		glBegin(GL_QUADS);
			glVertex2f(1.0, 1.0);
			glVertex2f(1.0, float(screenheight+1));
			glVertex2f(float(screenwidth+1), float(screenheight+1));
			glVertex2f(float(screenwidth+1), 1.0);
		glEnd();
		// glReadBuffer(fbo_attachments[Current_Buffer]);
		// imdebugPixelsf(0, 0, screenwidth+2, screenheight+2, GL_RGBA);

		// funcgrad가 2번 이상 호출하는 경우를 위한 초기화 코드
		if (steplength==1 && PassesBeforeJFA)
		{
			steplength = (screenwidth>screenheight ? screenwidth : screenheight)/2;
			PassesBeforeJFA = false;
		}
		else if (steplength>1)
			steplength /= 2;
		else if (SecondExit)
			ExitLoop = true;
		else
		{
			steplength = pow(2.0, (additional_passes-1));
			SecondExit = true;
		}
		
		// Loop를 돌 때마다 다른 버퍼를 사용하도록 처리
		Current_Buffer = 1-Current_Buffer;
	}

	////////////////////////////////
	// Third pass, Compute energy //
	////////////////////////////////
	cgGLBindProgram(VP_Scatter);
	cgGLBindProgram(FP_Scatter);

	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, fbo_attachments[0], 
		GL_TEXTURE_RECTANGLE_NV, Site_Texture, 0);
	CheckFramebufferStatus();
	glDrawBuffer(fbo_attachments[0]);

	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT);

	if (VP_Scatter_Size != NULL)
		cgSetParameter2f(VP_Scatter_Size, screenwidth, screenheight);

	//Bind & enable shadow map texture
	glActiveTextureARB(GL_TEXTURE0_ARB);
	// Loop 종료시 CurrentBuffer를 변경하기 때문에
	// 완료된 버퍼를 사용하기 위해 1-Current_Buffer를 선택
	glBindTexture(GL_TEXTURE_RECTANGLE_NV, Processed_Texture[1-Current_Buffer]);

	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
	glCallList(ScreenPointsList);
	glDisable(GL_BLEND);

	Energyf(grSite, g, f_tb_dev, screenwidth, iSiteTextureHeight, point_num, stream);

	lbfgsbcuda::CheckBuffer(g, point_num * 2, point_num * 2);

	glFinish();
	get_timestamp(end_time_func);
	elapsed_time_func = (end_time_func-start_time_func);
	total_time_func += elapsed_time_func;

	// energyf()의 결과를 반환
	f = *f_tb_host;
}
Beispiel #28
0
bool
WebGLFramebuffer::ValidateAndInitAttachments(const char* funcName)
{
    MOZ_ASSERT(mContext->mBoundDrawFramebuffer == this ||
               mContext->mBoundReadFramebuffer == this);

    nsCString fbStatusInfo;
    const auto fbStatus = CheckFramebufferStatus(&fbStatusInfo);
    if (fbStatus != LOCAL_GL_FRAMEBUFFER_COMPLETE) {
        nsCString errorText = nsPrintfCString("Incomplete framebuffer: Status 0x%04x",
                                              fbStatus.get());
        if (fbStatusInfo.Length()) {
            errorText += ": ";
            errorText += fbStatusInfo;
        }

        mContext->ErrorInvalidFramebufferOperation("%s: %s.", funcName,
                                                   errorText.BeginReading());
        return false;
    }

    // Cool! We've checked out ok. Just need to initialize.

    // Check if we need to initialize anything
    {
        bool hasUninitializedAttachments = false;

        if (mColorAttachment0.HasImage() && IsDrawBuffer(0))
            hasUninitializedAttachments |= mColorAttachment0.HasUninitializedImageData();

        size_t i = 1;
        for (const auto& cur : mMoreColorAttachments) {
            if (cur.HasImage() && IsDrawBuffer(i))
                hasUninitializedAttachments |= cur.HasUninitializedImageData();

            ++i;
        }

        if (mDepthAttachment.HasImage())
            hasUninitializedAttachments |= mDepthAttachment.HasUninitializedImageData();
        if (mStencilAttachment.HasImage())
            hasUninitializedAttachments |= mStencilAttachment.HasUninitializedImageData();
        if (mDepthStencilAttachment.HasImage())
            hasUninitializedAttachments |= mDepthStencilAttachment.HasUninitializedImageData();

        if (!hasUninitializedAttachments)
            return true;
    }

    // Get buffer-bit-mask and color-attachment-mask-list
    uint32_t clearBits = 0;
    std::vector<GLenum> tempDrawBuffers(1 + mMoreColorAttachments.Size(), LOCAL_GL_NONE);

    if (mColorAttachment0.HasUninitializedImageData() && IsDrawBuffer(0)) {
        clearBits |= LOCAL_GL_COLOR_BUFFER_BIT;
        tempDrawBuffers[0] = LOCAL_GL_COLOR_ATTACHMENT0;
    }

    size_t i = 1;
    for (const auto& cur : mMoreColorAttachments) {
        if (cur.HasUninitializedImageData() && IsDrawBuffer(i)) {
            clearBits |= LOCAL_GL_COLOR_BUFFER_BIT;
            tempDrawBuffers[i] = LOCAL_GL_COLOR_ATTACHMENT0 + i;
        }

        ++i;
    }

    if (mDepthAttachment.HasUninitializedImageData() ||
        mDepthStencilAttachment.HasUninitializedImageData())
    {
        clearBits |= LOCAL_GL_DEPTH_BUFFER_BIT;
    }

    if (mStencilAttachment.HasUninitializedImageData() ||
        mDepthStencilAttachment.HasUninitializedImageData())
    {
        clearBits |= LOCAL_GL_STENCIL_BUFFER_BIT;
    }

    mContext->MakeContextCurrent();

    const auto fnDrawBuffers = [this](const std::vector<GLenum>& list) {
        const GLenum* ptr = nullptr;
        if (list.size()) {
            ptr = &(list[0]);
        }
        this->mContext->gl->fDrawBuffers(list.size(), ptr);
    };

    const auto drawBufferExt = WebGLExtensionID::WEBGL_draw_buffers;
    const bool hasDrawBuffers = (mContext->IsWebGL2() ||
                                 mContext->IsExtensionEnabled(drawBufferExt));

    if (hasDrawBuffers) {
        fnDrawBuffers(tempDrawBuffers);
    }

    // Clear!
    mContext->ForceClearFramebufferWithDefaultValues(clearBits, false);

    if (hasDrawBuffers) {
        fnDrawBuffers(mDrawBuffers);
    }

    // Mark all the uninitialized images as initialized.
    if (mDepthAttachment.HasUninitializedImageData())
        mDepthAttachment.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);
    if (mStencilAttachment.HasUninitializedImageData())
        mStencilAttachment.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);
    if (mDepthStencilAttachment.HasUninitializedImageData())
        mDepthStencilAttachment.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);

    if (mColorAttachment0.HasUninitializedImageData() && IsDrawBuffer(0)) {
        mColorAttachment0.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);
    }

    i = 1;
    for (auto& cur : mMoreColorAttachments) {
        if (cur.HasUninitializedImageData() && IsDrawBuffer(i))
            cur.SetImageDataStatus(WebGLImageDataStatus::InitializedImageData);

        ++i;
    }

    return true;
}
Beispiel #29
0
void nuiGLPainter::SetSurface(nuiSurface* pSurface)
{
  if (mpSurface == pSurface)
    return;
  
  if (pSurface)
    pSurface->Acquire();
  if (mpSurface)
    mpSurface->Release();
  mpSurface = pSurface;
  
  if (pSurface)
  {
    std::map<nuiSurface*, FramebufferInfo>::const_iterator it = mFramebuffers.find(pSurface);
    bool create = (it == mFramebuffers.end()) ? true : false;  
    
    GLuint width = (GLuint)pSurface->GetWidth();
    GLuint height = (GLuint)pSurface->GetHeight();
    
    nuiTexture* pTexture = pSurface->GetTexture();
    if (pTexture && !pTexture->IsPowerOfTwo())
    {
      switch (GetRectangleTextureSupport())
      {
        case 0:
          width = (GLuint)pTexture->GetWidthPOT();
          height= (GLuint)pTexture->GetHeightPOT();
          break;
        case 1:
        case 2:
          break;
      }
    }
    
    
    FramebufferInfo info;
    
    if (create)
    {      
      glGenFramebuffersNUI(1, &info.mFramebuffer);
      //printf("glGenFramebuffersNUI -> %d\n", info.mFramebuffer);
      
      nuiCheckForGLErrors();
      glBindFramebufferNUI(GL_FRAMEBUFFER_NUI, info.mFramebuffer);
      nuiCheckForGLErrors();
      glBindRenderbufferNUI(GL_RENDERBUFFER_NUI, 0);
      nuiCheckForGLErrors();
      
      ///< Do we need a depth buffer
      if (pSurface->GetDepth())
      {
        glGenRenderbuffersNUI(1, &info.mDepthbuffer);
        nuiCheckForGLErrors();
        glBindRenderbufferNUI(GL_RENDERBUFFER_NUI, info.mDepthbuffer);
        nuiCheckForGLErrors();
        
        glRenderbufferStorageNUI(GL_RENDERBUFFER_NUI,
                                 GL_DEPTH_COMPONENT16,
                                 width, height);
        nuiCheckForGLErrors();
        
        glBindRenderbufferNUI(GL_RENDERBUFFER_NUI, 0);
        nuiCheckForGLErrors();
        
        glFramebufferRenderbufferNUI(GL_FRAMEBUFFER_NUI,
                                     GL_DEPTH_ATTACHMENT_NUI,
                                     GL_RENDERBUFFER_NUI,
                                     info.mDepthbuffer);
        nuiCheckForGLErrors();
      }
      
      ///< Do we need a stencil buffer
      if (pSurface->GetStencil())
      {
        NGL_ASSERT(!"Stencil attachement not supported");
#ifndef _OPENGL_ES_
        glGenRenderbuffersNUI(1, &info.mStencilbuffer);
        nuiCheckForGLErrors();
        
        glBindRenderbufferNUI(GL_RENDERBUFFER_NUI, info.mStencilbuffer);
        nuiCheckForGLErrors();
        
        glRenderbufferStorageNUI(GL_RENDERBUFFER_NUI,
                                 GL_STENCIL_INDEX,
                                 width, height);
        nuiCheckForGLErrors();
        
        glBindRenderbufferNUI(GL_RENDERBUFFER_NUI, 0);
        nuiCheckForGLErrors();
        
        glFramebufferRenderbufferNUI(GL_FRAMEBUFFER_NUI,
                                     GL_STENCIL_ATTACHMENT_NUI,
                                     GL_RENDERBUFFER_NUI,
                                     info.mStencilbuffer);
        nuiCheckForGLErrors();
#endif
      }
      
      ///< We definetly need a color attachement, either a texture, or a renderbuffer
      if (pTexture && pSurface->GetRenderToTexture())
      {
        GLint oldTexture;
        glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint *) &oldTexture);
        
        UploadTexture(pTexture);
        
        std::map<nuiTexture*, TextureInfo>::iterator tex_it = mTextures.find(pTexture);
        NGL_ASSERT(tex_it != mTextures.end());
        TextureInfo& tex_info(tex_it->second);
        
        //        glBindTexture(GL_TEXTURE_2D, oldTexture);
        glBindTexture(GL_TEXTURE_2D, 0);
        
        nuiCheckForGLErrors();
        
        glFramebufferTexture2DNUI(GL_FRAMEBUFFER_NUI,
                                  GL_COLOR_ATTACHMENT0_NUI,
                                  GetTextureTarget(pTexture->IsPowerOfTwo()),
                                  tex_info.mTexture,
                                  0);
        //printf("surface texture -> %d\n", tex_info.mTexture);
        nuiCheckForGLErrors();
      }
      else
      {
        glGenRenderbuffersNUI(1, &info.mRenderbuffer);
        nuiCheckForGLErrors();
        
        glBindRenderbufferNUI(GL_RENDERBUFFER_NUI, info.mRenderbuffer);
        nuiCheckForGLErrors();
        
        GLint pixelformat = pSurface->GetPixelFormat();
        GLint internalPixelformat = pSurface->GetPixelFormat();
        internalPixelformat = GL_RGBA;
#if !defined(_OPENGL_ES_) && defined(_MACOSX_)
        if (internalPixelformat == GL_RGBA)
        {
          pixelformat = GL_BGRA;
        }
        else if (internalPixelformat == GL_RGB)
        {
          pixelformat = GL_BGR;
        }
#endif
        
        glRenderbufferStorageNUI(GL_RENDERBUFFER_NUI, pixelformat, width, height);
        nuiCheckForGLErrors();
        
        glFramebufferRenderbufferNUI(GL_FRAMEBUFFER_NUI,
                                     GL_COLOR_ATTACHMENT0_NUI,
                                     GL_RENDERBUFFER_NUI,
                                     info.mRenderbuffer);
        //printf("surface render buffer -> %d\n", info.mRenderbuffer);
        nuiCheckForGLErrors();
      }
      CheckFramebufferStatus();
      nuiCheckForGLErrors();
      mFramebuffers[pSurface] = info;
    }
    else
    {
      /// !create
      info = it->second;
      glBindFramebufferNUI(GL_FRAMEBUFFER_NUI, info.mFramebuffer);
      glBindRenderbufferNUI(GL_RENDERBUFFER_NUI, info.mRenderbuffer);
      //printf("glBindFramebufferNUI -> %d\n", info.mFramebuffer);
      //printf("glBindRenderbufferNUI -> %d\n", info.mRenderbuffer);
      
      nuiCheckForGLErrors();
      CheckFramebufferStatus();
    }
  }
  else
  {
    /// !pSurface
    glBindFramebufferNUI(GL_FRAMEBUFFER_NUI, mDefaultFramebuffer);
    //printf("UNBIND glBindFramebufferNUI -> %d\n", mDefaultFramebuffer);
    glBindRenderbufferNUI(GL_RENDERBUFFER_NUI, mDefaultRenderbuffer);
    //printf("UNBIND glBindRenderbufferNUI -> %d\n", mDefaultRenderbuffer);
    
    nuiCheckForGLErrors();
    CheckFramebufferStatus();
  }
}