void
vtkTexturedPointsPainter::Texturer::StartFancyPoints()
{
#ifdef HAVE_LIBGLEW
    if(!GLEW_ARB_point_sprite)
    {
        // Point sprites are not supported
        return; 
    }
#endif

    // Create the textures
    if(!this->SphereTexturesDataCreated)
    {
        this->MakeTextures();
        this->SphereTexturesDataCreated = true;
    }

    // Push color and texture attributes so we can restore them later.
    glPushAttrib(GL_COLOR_BUFFER_BIT | GL_TEXTURE_BIT);

    // Create and bind the textures if we have not done that yet.
    if(!this->SphereTexturesLoaded)
    {
        glGenTextures(1, (GLuint*)&this->TextureName);

        // Set up the first texture
        glBindTexture(GL_TEXTURE_2D, this->TextureName);
        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);
        glTexImage2D(GL_TEXTURE_2D, 0, 2, SPHERE_TEX_W, SPHERE_TEX_H,
                     0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, this->SphereTexture);

        this->SphereTexturesLoaded = true;
    }

    //
    // Turn on alpha blending.
    //
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    //
    // Turn on alpha testing.
    //
    int dt = 0;
    glGetIntegerv(GL_DEPTH_TEST, (GLint*)&dt);
    if(dt == 1)
    {
        // Set the alpha testing mode and function.
        glEnable(GL_ALPHA_TEST);
        glAlphaFunc(GL_GREATER, 0.7);
    }

    //
    // Turn on the point sprite extension
    //
#define MY_POINT_SPRITE_ARB  0x8861
#define MY_COORD_REPLACE_ARB 0x8862
    glEnable(MY_POINT_SPRITE_ARB);

    //
    // Turn on the texture
    //
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, this->TextureName);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
    glTexEnvi(MY_POINT_SPRITE_ARB,
              MY_COORD_REPLACE_ARB,
              GL_TRUE);
}
Ejemplo n.º 2
0
	// useless stuff ?
	void	x3ds_instance::update_material()
	{
		GLint aux_buffers;
		glGetIntegerv(GL_AUX_BUFFERS, &aux_buffers);
		if (aux_buffers < 2)
		{
			static int n = 0;
			if (n < 1)
			{
				n++;
				log_error("Your video card does not have AUX buffers, can't snapshot movieclips\n");
			}
			return;
		}

		glPushAttrib(GL_ALL_ATTRIB_BITS);

		// update textures
		for (stringi_hash<gc_ptr <bitmap_info> >::iterator it = 
			m_material.begin(); it != m_material.end(); ++it)
		{
			as_value target = m_map[it->first];
			character* ch = find_target(target);
			if (ch)
			{
				if (ch->get_parent() == NULL)
				{
					log_error("Can't snapshot _root movieclip, material '%s'\n", it->first.c_str());
					continue;
				}

				GLint draw_buffer;
				glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);

				glDrawBuffer(GL_AUX1);
				glReadBuffer(GL_AUX1);

				// save "ch" matrix
				matrix ch_matrix = ch->get_matrix();

				float ch_width = TWIPS_TO_PIXELS(ch->get_width());
				float ch_height = TWIPS_TO_PIXELS(ch->get_height());

				// get viewport size
        GLint vp[4]; 
        glGetIntegerv(GL_VIEWPORT, vp); 
				int vp_width = vp[2];
				int vp_height = vp[3];

				// get texture size
				int	tw = 1; while (tw < ch_width) { tw <<= 1; }
				int	th = 1; while (th < ch_height) { th <<= 1; }

				// texture size must be <= viewport size
				if (tw > vp_width)
				{
					tw = vp_width;
				}
				if (th > vp_height)
				{
					th = vp_height;
				}

				ch->set_member("_width", tw);
				ch->set_member("_height", th);

				rect bound;
				ch->get_bound(&bound);

				// parent world matrix moves point(0,0) to "pzero"
				matrix mparent = ch->get_parent()->get_world_matrix();
				point pzero;
				mparent.transform_by_inverse(&pzero, point(0, 0));

				// after transformation of "ch" matrix left-top corner is in point(bound.m_x_min, bound.m_y_min),
				// therefore we need to move point(bound.m_x_min, bound.m_y_min) to point(pzero.m_x, pzero.m_y)
				// that "ch" movieclip's left-top corner will be in point(0,0) of screen
				matrix m = ch->get_matrix();
				float xt = (pzero.m_x - bound.m_x_min) / m.get_x_scale();
				float yt = (pzero.m_y - bound.m_y_min) / m.get_y_scale();

				// move "ch" to left-bottom corner (as point of origin of OpenGL is in left-bottom)
				// later glCopyTexImage2D will copy snapshot of "ch" into texture
				yt += PIXELS_TO_TWIPS(vp_height - th) / m.get_y_scale();
				m.concatenate_translation(xt, yt);

				ch->set_matrix(m);

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

				ch->display();

				// restore "ch" matrix
				ch->set_matrix(ch_matrix);

				gc_ptr<bitmap_info> bi = it->second;
				if (bi->m_texture_id == 0)
				{
					glGenTextures(1, (GLuint*) &bi->m_texture_id);
					bi->m_original_height = (int) ch_height;
					bi->m_original_width = (int) ch_width;
				}
				glBindTexture(GL_TEXTURE_2D, bi->m_texture_id);
				glEnable(GL_TEXTURE_2D);
				glDisable(GL_TEXTURE_GEN_S);
				glDisable(GL_TEXTURE_GEN_T);				

				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_MAG_FILTER, GL_LINEAR);	// GL_NEAREST ?
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

				glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0,0, tw, th, 0);

				glDisable(GL_TEXTURE_2D);

				glDrawBuffer(draw_buffer);
				glReadBuffer(draw_buffer);
			}
		}
		glPopAttrib();
	}
Ejemplo n.º 3
0
/**
 * @brief Really create the far texture for the given model.
 */
void CFarTextureHandler::CreateFarTexture(const CSolidObject* obj)
{
	const S3DModel* model = obj->model;

	//! make space in the std::vectors
	while (cache.size() <= obj->team) {
		cache.push_back(std::vector<int>());
	}
	while (cache[obj->team].size() <= model->id) {
		cache[obj->team].push_back(0);
	}
	cache[obj->team][model->id] = -1;

	//! check if there is enough free space in the atlas, if not try to resize it
	const int maxSprites = (texSizeX / iconSizeX)*(texSizeY / iconSizeY) / numOrientations - 1;
	if (usedFarTextures >= maxSprites) {
		const int oldTexSizeY = texSizeY;

		if (globalRendering->supportNPOTs) {
			texSizeY += std::max(iconSizeY,  4 * numOrientations * iconSizeX * iconSizeY / texSizeX); //! minimum additional space for 4 icons
		} else {
			texSizeY <<= 1;
		}

		if (texSizeY > globalRendering->maxTextureSize) {
			//logOutput.Print("Out of farTextures"); 
			texSizeY = oldTexSizeY;
			return;
		}

		unsigned char* oldPixels = new unsigned char[texSizeX*texSizeY*4];
		glBindTexture(GL_TEXTURE_2D, farTexture);
		glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, oldPixels);
		memset(oldPixels + texSizeX*oldTexSizeY*4, 0, texSizeX*(texSizeY - oldTexSizeY)*4);

		GLuint newFarTexture;
		glGenTextures(1,&newFarTexture);
		glBindTexture(GL_TEXTURE_2D, newFarTexture);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, texSizeX, texSizeY, 0, GL_RGBA, GL_UNSIGNED_BYTE, oldPixels);
		delete[] oldPixels;

		fbo.Bind();
		fbo.UnattachAll();

		glDeleteTextures(1,&farTexture);
		farTexture = newFarTexture;

		fbo.AttachTexture(farTexture);
		fbo.CheckStatus("FARTEXTURE");
		fbo.Unbind();
	}

	if (!fbo.IsValid()) {
		//logOutput.Print("framebuffer not valid!");
		return;
	}

	fbo.Bind();
	fbo.CreateRenderBuffer(GL_DEPTH_ATTACHMENT_EXT, GL_DEPTH_COMPONENT16, texSizeX, texSizeY); //! delete it after finished rendering to the texture
	fbo.CheckStatus("FARTEXTURE");

	glPushAttrib(GL_ALL_ATTRIB_BITS);
	glDisable(GL_BLEND);

	unitDrawer->SetupForUnitDrawing();
	unitDrawer->GetOpaqueModelRenderer(model->type)->PushRenderState();

	if (model->type == MODELTYPE_S3O || model->type == MODELTYPE_OBJ || model->type == MODELTYPE_ASS) {
		// FIXME for some strange reason we need to invert the culling, why?
		if (model->type == MODELTYPE_S3O) {
			glCullFace(GL_FRONT);
		}
		texturehandlerS3O->SetS3oTexture(model->textureType);
	}

	unitDrawer->SetTeamColour(obj->team);
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

	glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(-model->radius, model->radius, -model->radius, model->radius, -model->radius*1.5f, model->radius*1.5f);
	glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glScalef(-1.0f, 1.0f, 1.0f);

	glRotatef(45.0f, 1.0f, 0.0f, 0.0f);

	// light the far-textures from straight above, we do
	// not care much about the actual sun direction here
	static const float4 sunDir = UpVector;

	glLightfv(GL_LIGHT1, GL_POSITION, &sunDir.x);

	//! draw the model in 8 different orientations
	for (size_t orient = 0; orient < numOrientations; ++orient) {
		//! setup viewport
		int2 pos = GetTextureCoordsInt(usedFarTextures, orient);
		glViewport(pos.x * iconSizeX, pos.y * iconSizeY, iconSizeX, iconSizeY);

		glClear(GL_DEPTH_BUFFER_BIT);

		glPushMatrix();
		glTranslatef(0, -model->height * 0.5f, 0);

		//! draw the model to a temporary buffer
		model->DrawStatic();

		glPopMatrix();

		//! rotate by 45 degrees for the next orientation
		glRotatef(-360.0f / numOrientations, 0, 1, 0);
	}

	unitDrawer->GetOpaqueModelRenderer(model->type)->PopRenderState();
	unitDrawer->CleanUpUnitDrawing();

	//glViewport(globalRendering->viewPosX, 0, globalRendering->viewSizeX, globalRendering->viewSizeY);
	glPopAttrib();

	fbo.Unattach(GL_DEPTH_ATTACHMENT_EXT);
	fbo.Unbind();

	usedFarTextures++;
	cache[obj->team][model->id] = usedFarTextures;
}
Ejemplo n.º 4
0
// inhered interfaces
void 
CTfWin::_DisplayFunc()
{
	assert(iNrOfEntries);
	glClear(GL_COLOR_BUFFER_BIT);

	pcTransFunc->_ExportColorMap(&pfColorMap[0], iNrOfEntries);
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
		glLoadIdentity();

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

	if( cHistogram.pfBins.BIsAllocated() )
	{
		// normalize the coordinate
		glTranslatef(-1.0f, -1.0f, -1.0f);
		glScalef(2.0f, 2.0f, 2.0f);

		float fDomainMin  = pcTransFunc->cDomainMin.FGetValue();
		float fDomainMax  = pcTransFunc->cDomainMax.FGetValue();
		float fHistogramMin = cHistogram.cMin.FGetValue();
		float fHistogramMax = cHistogram.cMax.FGetValue();

		glPushMatrix();
		glScalef(1.0f / (float)(fHistogramMax - fHistogramMin), 1.0f, 1.0f);
		glTranslatef(-fHistogramMin, 0.0f, 0.0f);
		
		glTranslatef(fDomainMin, 0.0f, 0.0f);
		glScalef((fDomainMax - fDomainMin)/(float)iNrOfEntries, 1.0f, 1.0f);

		glBegin(GL_QUADS);
		for(int i = 0; i < iNrOfEntries; i++)
		{
			float l, r, b, t;
			l = (float)i;
			r = (float)i + 1;
			b = 0.0f;
			t = pfColorMap[i*4 + 3];	// use the alpha channel as the height
			glColor3fv(&pfColorMap[i*4]);	// setup the color

			glVertex2f(l, b);
			glVertex2f(r, b);
			glVertex2f(r, t);
			glVertex2f(l, t);
		}
		glEnd();

		glColor4f(1.0, 1.0, 1.0, 1.0);
		_DrawString3D(SZSprintf("%.2e", fDomainMin), 0.0f, 0.5f, 0.0f);
		_DrawString3D(SZSprintf("%.2e", fDomainMax), (float)iNrOfEntries, 0.5f, 0.0f);

		glPopMatrix();

		/////////////////////////////////////////////////////
		glPushMatrix();
		glScalef(1.0f / (float)(float)cHistogram.pfBins.USize(), 1.0f, 1.0f);

		glPushAttrib(GL_LINE_BIT);
		glLineWidth(4.0);

		glBegin(GL_LINE_STRIP);
		glColor4f(1.0, 1.0, 1.0, 1.0);
		for(int i = 0; i < (int)cHistogram.pfBins.USize(); i++)
		{
			glVertex2f((float)i, cHistogram.pfBins[i]);
			glVertex2f((float)i + 1.0f, cHistogram.pfBins[i]);
		}
		glEnd();
		glPopAttrib();	// glPushAttrib(GL_LINE_BIT);
		glPopMatrix();

		_DrawString(SZSprintf("%.2e", fHistogramMin), 0, 2, false);
		_DrawString(SZSprintf("%.2e", fHistogramMax), -1, 2, true);
		_DrawString(SZSprintf("%.2e", cHistogram.fMaxCount), 0, -16, false);
	}
	else
	{

		// normalize the coordinate
		glTranslatef(-1.0f, -1.0f, -1.0f);
		glScalef(2.0f, 2.0f, 2.0f);
		glScalef(1.0f/(float)iNrOfEntries, 1.0f, 1.0f);

		// plot the transfer func. as bar chart
		// each entry in the TR is a bar
		// the height of each bar represents the corresponding alpha
		// the color  of each bar represents the corresponding color
		glBegin(GL_QUADS);
		for(int i = 0; i < iNrOfEntries; i++)
		{
			float l, r, b, t;
			l = (float)i;
			r = (float)i + 1;
			b = 0.0f;
			t = pfColorMap[i*4 + 3];	// use the alpha channel as the height
			glColor3fv(&pfColorMap[i*4]);	// setup the color

			glVertex2f(l, b);
			glVertex2f(r, b);
			glVertex2f(r, t);
			glVertex2f(l, t);
		}
		glEnd();

		// plot the transfer func. as lines
		for(int c = 0; c < 3; c++)	// only plot the RGB channels
		{
			switch(c)
			{
			case 0:	glColor4f(1.0, 0.0f, 0.0f, 1.0f);	break;
			case 1:	glColor4f(0.0, 1.0f, 0.0f, 1.0f);	break;
			case 2:	glColor4f(0.0, 0.0f, 1.0f, 1.0f);	break;
			}

			glBegin(GL_LINE_STRIP);
				for(int i = 0; i < iNrOfEntries; i++)
					glVertex2f((float)i, pfColorMap[i*4 + c]);
			glEnd();
		}

		glColor4f(0.0f, 1.0f, 1.0f, 1.0f);
		_DrawString(SZSprintf("%.2e", pcTransFunc->cDomainMin.FGetValue()), 0, 0, false);
		_DrawString(SZSprintf("%.2e", pcTransFunc->cDomainMax.FGetValue()), -1, 0, true);

	}

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
}
Ejemplo n.º 5
0
/*===========================================================================*/
void VideoRenderer::exec( kvs::ObjectBase* object, kvs::Camera* camera, kvs::Light* light )
{
    kvs::IgnoreUnusedVariable( light );

    kvs::opencv::VideoObject* video = reinterpret_cast<kvs::opencv::VideoObject*>( object );

    BaseClass::startTimer();

    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT );

    if ( !glIsTexture( m_texture.id() ) ) this->create_texture( video );

    glDisable( GL_DEPTH_TEST );
    glEnable( GL_TEXTURE_2D );

    switch( m_type )
    {
    case VideoRenderer::Centering:
        this->centering( camera->windowWidth(), camera->windowHeight() );
        break;
    default: break;
    }

    const IplImage* frame = video->device().queryFrame();
    const int width = frame->width;
    const int height = frame->height;
    const char* data = frame->imageData; // BGRBGRBGR...
    m_texture.bind();
    m_texture.download( width, height, data );

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

        glMatrixMode( GL_PROJECTION );
        glPushMatrix();
        {
            glLoadIdentity();
            glOrtho( m_left, m_right, m_bottom, m_top, -1, 1 );

            glBegin( GL_QUADS );
/* mirror */
            glTexCoord2f( 0.0, 0.0 ); glVertex2f( 1.0, 1.0 );
            glTexCoord2f( 0.0, 1.0 ); glVertex2f( 1.0, 0.0 );
            glTexCoord2f( 1.0, 1.0 ); glVertex2f( 0.0, 0.0 );
            glTexCoord2f( 1.0, 0.0 ); glVertex2f( 0.0, 1.0 );
/* normal */
/*
            glTexCoord2f( 0.0, 0.0 ); glVertex2f( 0.0, 1.0 );
            glTexCoord2f( 0.0, 1.0 ); glVertex2f( 0.0, 0.0 );
            glTexCoord2f( 1.0, 1.0 ); glVertex2f( 1.0, 0.0 );
            glTexCoord2f( 1.0, 0.0 ); glVertex2f( 1.0, 1.0 );
*/
            glEnd();
        }
        glPopMatrix();
        glMatrixMode( GL_MODELVIEW );
    }
    glPopMatrix();

    m_texture.unbind();

    glClearDepth( 1000 );
    glEnable( GL_DEPTH_TEST );
    glDisable( GL_TEXTURE_2D );

    glPopAttrib();

    BaseClass::stopTimer();
}
Ejemplo n.º 6
0
	// Much Like NeHe's glPrint Function, But Modified To Work
	// With FreeType Fonts.
	void print(const font_data &ft_font, float x, float y, const char *fmt, ...)  {

		// We Want A Coordinate System Where Distance Is Measured In Window Pixels.
//		pushScreenCoordinateMatrix();                                  

		GLuint font=ft_font.list_base;
		// We Make The Height A Little Bigger.  There Will Be Some Space Between Lines.
		float h=ft_font.h/*/.63f*/;                                                
		char    text[256];                                  // Holds Our String
		va_list ap;                                     // Pointer To List Of Arguments

		if (fmt == NULL)                                    // If There's No Text
			*text=0;                                    // Do Nothing
		else {
			va_start(ap, fmt);                              // Parses The String For Variables
			vsprintf_s(text, fmt, ap);                            // And Converts Symbols To Actual Numbers
			va_end(ap);                                 // Results Are Stored In Text
		}

		// Here Is Some Code To Split The Text That We Have Been
		// Given Into A Set Of Lines. 
		// This Could Be Made Much Neater By Using
		// A Regular Expression Library Such As The One Available From
		// boost.org (I've Only Done It Out By Hand To Avoid Complicating
		// This Tutorial With Unnecessary Library Dependencies).
		const char *start_line=text;
		vector<string> lines;
		const char *c=text;
		for(;*c;c++) {
			if(*c=='\n') {
				string line;
				for(const char *n=start_line;n<c;n++) line.append(1,*n);
				lines.push_back(line);
				start_line=c+1;
			}
		}
		if(start_line) {
			string line;
			for(const char *n=start_line;n<c;n++) line.append(1,*n);
			lines.push_back(line);
		}

		glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT  | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
		glMatrixMode(GL_MODELVIEW);
//		glDisable(GL_LIGHTING);
		glEnable(GL_TEXTURE_2D);
		glDisable(GL_DEPTH_TEST);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);     

		glListBase(font);
		float modelview_matrix[16];    
//		glGetFloatv(GL_MODELVIEW_MATRIX, modelview_matrix);
		// This Is Where The Text Display Actually Happens.
		// For Each Line Of Text We Reset The Modelview Matrix
		// So That The Line's Text Will Start In The Correct Position.
		// Notice That We Need To Reset The Matrix, Rather Than Just Translating
		// Down By h. This Is Because When Each Character Is
		// Drawn It Modifies The Current Matrix So That The Next Character
		// Will Be Drawn Immediately After It. 
		for(int i=0;i<lines.size();i++) {
			glPushMatrix();
//			glLoadIdentity();
			glTranslatef(x-h/4,y-h*i-h/4,0);
//			glMultMatrixf(modelview_matrix);

			// The Commented Out Raster Position Stuff Can Be Useful If You Need To
			// Know The Length Of The Text That You Are Creating.
			// If You Decide To Use It Make Sure To Also Uncomment The glBitmap Command
			// In make_dlist().
			// glRasterPos2f(0,0);
			glCallLists(lines[i].length(), GL_UNSIGNED_BYTE, lines[i].c_str());
			// float rpos[4];
			// glGetFloatv(GL_CURRENT_RASTER_POSITION ,rpos);
			// float len=x-rpos[0]; (Assuming No Rotations Have Happend)

			glPopMatrix();
		}

		glPopAttrib();         

//		pop_projection_matrix();
	}
Ejemplo n.º 7
0
void LifeWidget::paintGL()
{
	float caseXmin, caseYmin, caseXmax, caseYmax;
	
	if ((mouseX <= 1.0) && (mouseX >= 0.0) && (mouseY <= 1.0) && (mouseY >= 0.0))
		setCursor(NULL);
	else
		setCursor(Qt::ArrowCursor);
	
	glPushAttrib(GL_ALL_ATTRIB_BITS);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
	
	glShadeModel(GL_SMOOTH);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
	
	resizeGL(width(), height());
	
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
	
	glColor3f(0.0, 0.2, 0.8);
	glBegin(GL_QUADS);
		for (int i = 0; i < nbCases; i++)
			for (int j = 0; j < nbCases; j++)
				if (lifeGame->isAlive(i, j))
				{
					caseXmin =(float)i / (float)nbCases;
					caseXmax =(float)(i + 1) / (float)nbCases;
					caseYmin =(float)j / (float)nbCases;
					caseYmax =(float)(j + 1) / (float)nbCases;
				
					glVertex3f(caseXmin, caseYmin, -0.1);
					glVertex3f(caseXmin, caseYmax, -0.1);
					glVertex3f(caseXmax, caseYmax, -0.1);
					glVertex3f(caseXmax, caseYmin, -0.1);
				}
	glEnd();
	
	if (showGrid)
	{
		glColor3f(0.5, 0.5, 0.5);
		glBegin(GL_LINES);
			for (int i = 0; i <= nbCases; i++)
			{
			float j = (float)i / (float)nbCases;
				
				glVertex3f(0.0, j, -0.05);
				glVertex3f(1.0, j, -0.05);
			
				glVertex3f(j, 0.0, -0.05);
				glVertex3f(j, 1.0, -0.05);
			}
		glEnd();
	}
		
	glColor3f(1.0, 0.0, 0.0);
	glBegin(GL_LINE_LOOP);
		caseXmin =(float)posX / (float)nbCases;
		caseXmax =(float)(posX + 1) / (float)nbCases;
		caseYmin =(float)posY / (float)nbCases;
		caseYmax =(float)(posY + 1) / (float)nbCases;
		
		glVertex3f(caseXmin, caseYmin, -0.02);
		glVertex3f(caseXmin, caseYmax, -0.02);
		glVertex3f(caseXmax, caseYmax, -0.02);
		glVertex3f(caseXmax, caseYmin, -0.02);
	glEnd();
	
	glColor3f(0.0, 1.0, 1.0);
	glBegin(GL_LINES);
		glVertex3f(mouseX - 0.01, mouseY, -0.01);
		glVertex3f(mouseX - 0.0025, mouseY, -0.01);
		glVertex3f(mouseX + 0.01, mouseY, -0.01);
		glVertex3f(mouseX + 0.0025, mouseY, -0.01);
		glVertex3f(mouseX, mouseY - 0.01, -0.01);
		glVertex3f(mouseX, mouseY - 0.0025, -0.01);
		glVertex3f(mouseX, mouseY + 0.01, -0.01);
		glVertex3f(mouseX, mouseY + 0.0025, -0.01);
	glEnd();
	
	glFlush();
	
	glPopAttrib();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
}
Ejemplo n.º 8
0
void  drawOBJMesh(struct OBJ_Model * obj)
{
        glPushAttrib(GL_ALL_ATTRIB_BITS); //We dont want the attributes we use here to poison the rest of the drawing
        if (obj == 0 ) { fprintf(stderr,"drawOBJMesh called with unloaded object \n"); return; }
        long unsigned int i,j;

        glDisable(GL_CULL_FACE);

        if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Initial Error while @ drawOBJMesh\n"); }
		//for every group
		for(i=0; i<obj->numGroups; i++)
		{

		if (obj->matList!=0)
		 { //We might not have a material with our object!
			//if there is a bmp file to load the texture from, in the mtl file
			if( obj->matList[obj->groups[i].material].hasTex )
            {
				if( obj->matList[obj->groups[i].material].ldText>0)
				{
			 	  glEnable(GL_TEXTURE_2D);
				  glBindTexture(GL_TEXTURE_2D, obj->matList[ obj->groups[i].material].ldText);
				}
			}
			else
			 {	/*glDisable(GL_TEXTURE_2D);*/ }


            if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error before setting up material @ drawOBJMesh\n"); }


            GLenum faces=GL_FRONT;//GL_FRONT_AND_BACK;
			glMaterialfv(faces, GL_AMBIENT,  obj->matList[ obj->groups[i].material].ambient);
			glMaterialfv(faces, GL_DIFFUSE,  obj->matList[ obj->groups[i].material].diffuse);
			glMaterialfv(faces, GL_SPECULAR, obj->matList[ obj->groups[i].material].specular);
            if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error after setting up material for specularity @ drawOBJMesh\n"); }

            #if DISABLE_SHININESS
			 glMaterialf(faces, GL_SHININESS, 0.0 );
			#else
			 glMaterialfv(faces, GL_SHININESS, obj->matList[ obj->groups[i].material].shine);
            #endif
            if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error after setting up material for shininess @ drawOBJMesh\n"); }



			//if the group has texture coordinates
			if(  ( obj->groups[i].hasTex) ==0 ) { InitAutoTex(); } else
			                               {
			                                 glDisable(GL_TEXTURE_GEN_S);
                                             glDisable(GL_TEXTURE_GEN_T);
			                               }

            if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error after setting up material @ drawOBJMesh\n"); }

		}   else
        {
              //No Matterials , No Textures
			   glDisable(GL_TEXTURE_GEN_S);
               glDisable(GL_TEXTURE_GEN_T);
               glDisable(GL_TEXTURE_2D);
        }

        if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error before starting drawing triangles @ drawOBJMesh\n"); }

           doOBJDrawCallsForGroup(obj,i);

        if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Initial Error after drawing triangles @ drawOBJMesh\n"); }
    }//FOR I
glPopAttrib();

}
Ejemplo n.º 9
0
int compileOBJList(struct OBJ_Model * obj)
{

	/*
	create	or replace a display list with :
	void glNewList( GLuint list, GLenum mode )
	void glEndList( void )
	where:
	list	Specifies the display-list name.

	mode	Specifies the compilation mode,	which can be
		GL_COMPILE or GL_COMPILE_AND_EXECUTE.

	  Display lists	are groups of GL commands that have been
	  stored for subsequent	execution.  Display lists are created
	  with glNewList.  All subsequent commands are placed in the
	  display list,	in the order issued, until glEndList is
	  called.

	  glNewList has	two arguments.	The first argument, list, is a
	  positive integer that	becomes	the unique name	for the
	  display list.	 Names can be created and reserved with
	  glGenLists
	*/

    glPushAttrib(GL_ALL_ATTRIB_BITS);
	long unsigned int i,j;

	//generate an empty display list, and save its id in dispList
	obj->dispList=glGenLists(1);

	glNewList(obj->dispList,GL_COMPILE);

	for(i=0; i<obj->numGroups; i++)
		{

		if (obj->matList!=0)
		 { //We might not have a material with our object!
			if( obj->matList[ obj->groups[i].material].hasTex)
			{
				if( obj->matList[ obj->groups[i].material].ldText>0)
				{
				  glEnable(GL_TEXTURE_2D);
				  glBindTexture(GL_TEXTURE_2D,  obj->matList[ obj->groups[i].material].ldText);
				}
			}
			else
			{
			  //glDisable(GL_TEXTURE_2D);
			}

            glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,  obj->matList[ obj->groups[i].material].ambient);
			glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,  obj->matList[ obj->groups[i].material].diffuse);
			glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, obj->matList[ obj->groups[i].material].specular);

            #if DISABLE_SHININESS
			 glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0 );
			#else
			 glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, obj->matList[ obj->groups[i].material].shine);
            #endif

			if(  ( obj->groups[i].hasTex) ==0 )
			{
				InitAutoTex();
			}
			else
			{
				glDisable(GL_TEXTURE_GEN_S);
                glDisable(GL_TEXTURE_GEN_T);
			}
          } else
          {
              //No Matterials , No Textures
			   glDisable(GL_TEXTURE_GEN_S);
               glDisable(GL_TEXTURE_GEN_T);
               glDisable(GL_TEXTURE_2D);
          }

           doOBJDrawCallsForGroup(obj,i);


		}//FOR I
	glEndList();
glPopAttrib();
return 1;
}
Ejemplo n.º 10
0
main(int argc, char *argv[])
{
    int texcomps;
    static GLfloat splane[4] = {1.f/200.f, 0.f, 0.f, .5f};
    static GLfloat rplane[4] = {0, 1.f/200.f, 0, .5f};
    static GLfloat tplane[4] = {0, 0, 1.f/200.f, .5f};
    static GLfloat lightpos[4] = {150., 150., 150., 1.f};


    glutInit(&argc, argv);
    glutInitWindowSize(winWidth, winHeight);
    if(argc > 1)
    {
	char *args = argv[1];
	GLboolean done = GL_FALSE;
	while(!done)
	{
	    switch(*args)
	    {
	    case 's': /* single buffer */
		printf("Single Buffered\n");
		dblbuf = GL_FALSE;
		break;
	    case '-': /* do nothing */
		break;
	    case 0:
		done = GL_TRUE;
		break;
	    }
	    args++;
	}
    }
    if(dblbuf)
	glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
    else
	glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH);

    (void)glutCreateWindow("volume rendering demo");
    glutDisplayFunc(redraw);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(key);

    /* Initialize OpenGL State */

    /* draw a perspective scene */
#if 0
    glMatrixMode(GL_PROJECTION);
    /* cube, 300 on a side */
    glFrustum(-150., 150., -150., 150., 300., 600.);
    glMatrixMode(GL_MODELVIEW);
    /* look at scene from (0, 0, 450) */
    gluLookAt(0., 0., 450., 0., 0., 0., 0., 1., 0.);
#else
    glMatrixMode(GL_PROJECTION);
    /* cube, 300 on a side */
    glOrtho(-150., 150., -150., 150., -150., 150.);
    glMatrixMode(GL_MODELVIEW);
#endif

    glEnable(GL_DEPTH_TEST);
#ifdef GL_EXT_texture3D
    glEnable(GL_TEXTURE_3D_EXT);
#endif

    glEnable(GL_TEXTURE_GEN_S);
    glEnable(GL_TEXTURE_GEN_T);
    glEnable(GL_TEXTURE_GEN_R);

    glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
    glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
    glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);

    glTexGenfv(GL_S, GL_OBJECT_PLANE, splane);
    glTexGenfv(GL_T, GL_OBJECT_PLANE, tplane);
    glTexGenfv(GL_R, GL_OBJECT_PLANE, rplane);

#ifdef GL_EXT_texture3D
    /* to avoid boundary problems */
    glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_R_EXT, GL_CLAMP);
#endif

    glEnable(GL_CLIP_PLANE0);
    glEnable(GL_CLIP_PLANE1);
    glEnable(GL_CLIP_PLANE2);
    glEnable(GL_CLIP_PLANE3);
    glEnable(GL_CLIP_PLANE4);
    glEnable(GL_CLIP_PLANE5);

    glDisable(GL_LIGHT0);
    glLightfv(GL_LIGHT0, GL_POSITION, lightpos);



    tex3ddata = loadtex3d(&texwid, &texht, &texdepth, &texcomps);

    slices = texht;

#ifdef GL_EXT_texture3D
    glTexParameteri(GL_TEXTURE_3D_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage3DEXT(GL_TEXTURE_3D_EXT, 0, GL_LUMINANCE_ALPHA,
		    texwid, texht, texdepth,
		    0,
		    GL_RGBA, GL_UNSIGNED_BYTE, tex3ddata);
#endif

    /* make a display list containing a sphere */
    glNewList(SPHERE, GL_COMPILE);
    {
	static GLfloat lightpos[] = {150.f, 150.f, 150.f, 1.f};
	static GLfloat material[] = {1.f, .5f, 1.f, 1.f};
	GLUquadricObj *qobj = gluNewQuadric();
	glPushAttrib(GL_LIGHTING_BIT);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
	glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, material);
	gluSphere(qobj, 20.f, 20, 20);
	gluDeleteQuadric(qobj);
	glPopAttrib();
    }
    glEndList();

    key('?', 0, 0); /* print usage message */

    CHECK_ERROR("end of main");

    if(!glutExtensionSupported("GL_EXT_texture3d")) {
      fprintf(stderr,
        "volume: requires OpenGL texture 3D extension to operate correctly.\n");
    }
    hasBlendColor = glutExtensionSupported("GL_EXT_blend_color");
    if(!hasBlendColor) {
      fprintf(stderr,
        "volume: needs OpenGL blend color extension to attenuate.\n");
    }

    glutMainLoop();
    return 0;             /* ANSI C requires main to return int. */
}
Ejemplo n.º 11
0
void SkyBox::draw() {
    glPushMatrix();
    // Enable/Disable features
    glPushAttrib(GL_ENABLE_BIT);
    glEnable(GL_TEXTURE_2D);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_LIGHTING);
    glDisable(GL_BLEND);


    // Just in case we set all vertices to white.
    //glColor4f(1,1,1,1);
    glBindTexture(GL_TEXTURE_2D, t_xneg);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex3f(  width, -border, -border );
    glTexCoord2f(1, 0);
    glVertex3f( width, -border, width  );
    glTexCoord2f(1, 1);
    glVertex3f( width,  width, width );
    glTexCoord2f(0, 1);
    glVertex3f(  width,  width, -border );
    glEnd();

    glBindTexture(GL_TEXTURE_2D, t_xpos);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex3f(  -border, -border, width );
    glTexCoord2f(1, 0);
    glVertex3f( -border, -border, -border  );
    glTexCoord2f(1, 1);
    glVertex3f( -border,  width, -border );
    glTexCoord2f(0, 1);
    glVertex3f(  -border,  width, width );
    glEnd();

    glBindTexture(GL_TEXTURE_2D, t_zneg);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex3f(  -border, -border, -border );
    glTexCoord2f(1, 0);
    glVertex3f( width, -border, -border  );
    glTexCoord2f(1, 1);
    glVertex3f( width,  width, -border );
    glTexCoord2f(0, 1);
    glVertex3f(  -border,  width, -border );
    glEnd();

    glBindTexture(GL_TEXTURE_2D, t_zpos);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex3f(  width, -border, width );
    glTexCoord2f(1, 0);
    glVertex3f( -border, -border, width );
    glTexCoord2f(1, 1);
    glVertex3f( -border,  width, width );
    glTexCoord2f(0, 1);
    glVertex3f(  width,  width, width );
    glEnd();

    glBindTexture(GL_TEXTURE_2D, t_yneg);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex3f(  width, -border, -border );
    glTexCoord2f(1, 0);
    glVertex3f( width, -border, width );
    glTexCoord2f(1, 1);
    glVertex3f( -border,  -border, width );
    glTexCoord2f(0, 1);
    glVertex3f(  -border,  -border, -border );
    glEnd();

    glBindTexture(GL_TEXTURE_2D, t_ypos);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex3f(  width,  width, -border );
    glTexCoord2f(1, 0);
    glVertex3f(  -border, width, -border );
    glTexCoord2f(1, 1);
    glVertex3f( -border, width, width );
    glTexCoord2f(0, 1);
    glVertex3f( width,  width, width );
    glEnd();

    glEnable(GL_LIGHTING);

    glPopAttrib();
    glPopMatrix();
}
Ejemplo n.º 12
0
DWORD	ofFFGLPlugin::ProcessOpenGL(ProcessOpenGLStruct* pGL)
{
	_ofWin->update();
	
	setupInputTextures(pGL);
	
	
//	GLint vp[4];
//	glGetIntegerv(GL_VIEWPORT,vp);
	
	GLint mmode;
	glGetIntegerv(GL_MATRIX_MODE,&mmode);
	
	//push all matrices
	glMatrixMode(GL_TEXTURE);
	glPushMatrix();
	glLoadIdentity();
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	// set up coordinate system based on our proxy window.
	glOrtho(0.0, _ofWin->windowSize.x, _ofWin->windowSize.y, 0.0, -1.0, 1.0);

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

	// this could be optimized...alot
	glPushAttrib(GL_ALL_ATTRIB_BITS);
	
	// draw
	_ofWin->draw();
	
	
	glPopAttrib();
	
	//reset all matrices
	glMatrixMode(GL_TEXTURE);
	glPopMatrix();
	
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
	
	glMatrixMode(mmode);
	
	// we reset the host fbo id here
	// in case we have been rendering offscreen in the plugin.
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,pGL->HostFBO);
	
	// TODO it may be necessary to even do this:
	// but it's a bit of a hack....
	
	/*if( pGL->HostFBO )
	{
		glDrawBuffer(GL_BACK);
		glReadBuffer(GL_BACK);
	}
	else 
	{
		glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
		glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
	}
	*/
	
	// ... and it would be better if host handles these things 
		


	return FF_SUCCESS;
}
Ejemplo n.º 13
0
void DrawText::Display(const char * pText)
{
    if (!mGlyph || mTextureName == 0)
        return;

    // Push OpenGL attributes.
    glPushAttrib(GL_ENABLE_BIT);
    glPushAttrib(GL_COLOR_BUFFER_BIT);
    glPushAttrib(GL_TEXTURE_BIT);

    glBindTexture(GL_TEXTURE_2D, mTextureName);
    glEnable(GL_TEXTURE_2D);

    // Blend with background color
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Visible for double side
    glDisable(GL_CULL_FACE);

    // Blend with foreground color
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    glPushMatrix();
    const char * pCharacter = pText;
    while (*pCharacter != '\0')
    {
        if (*pCharacter == '\n')
        {
            glPopMatrix();
            // Move to the next line, left align
            glTranslatef(0, -mPointSize, 0);
            glPushMatrix();
        }
        else
        {
            Glyph * lGlyph = mGlyph + (*pCharacter - TEXTURE_MIN_GLYPH);
            if (lGlyph)
            {
                // Draw a rectangle with texture, alpha on.
                glBegin(GL_POLYGON);
                glTexCoord2f(lGlyph->texture_left, lGlyph->texture_bottom);
                glVertex2f(lGlyph->vertex_left * mPointSize, lGlyph->vertex_bottom * mPointSize);
                glTexCoord2f(lGlyph->texture_right, lGlyph->texture_bottom);
                glVertex2f(lGlyph->vertex_right * mPointSize, lGlyph->vertex_bottom * mPointSize);
                glTexCoord2f(lGlyph->texture_right, lGlyph->texture_top);
                glVertex2f(lGlyph->vertex_right * mPointSize, lGlyph->vertex_top * mPointSize);
                glTexCoord2f(lGlyph->texture_left, lGlyph->texture_top);
                glVertex2f(lGlyph->vertex_left * mPointSize, lGlyph->vertex_top * mPointSize);
                glEnd();

                const float advance = lGlyph->advance * mPointSize + mGap;
                glTranslatef(advance, 0, 0);
            }
            else
            {
                FBXSDK_printf("Invalid character: %c.\n", *pCharacter);
            }
            
        }
        ++pCharacter;
    }
    glPopMatrix();

    // Pop OpenGL attributes.
    glPopAttrib();
    glPopAttrib();
    glPopAttrib();
}
Ejemplo n.º 14
0
/* BrowserItem::draw
 * Draws the item in a [size]x[size] box, keeping the correct aspect
 * ratio of it's image
 *******************************************************************/
void BrowserItem::draw(int size, int x, int y, int font, int nametype, int viewtype, rgba_t colour, bool text_shadow)
{
	// Determine item name string (for normal viewtype)
	string draw_name = "";
	if (nametype == 0)
		draw_name = name;
	else if (nametype == 1)
		draw_name = S_FMT("%d", index);

	// Item name
	if (viewtype == 0)
	{
		if (text_shadow) Drawing::drawText(draw_name, x+(size*0.5+1), y+size+5, COL_BLACK, font, Drawing::ALIGN_CENTER);
		Drawing::drawText(draw_name, x+(size*0.5), y+size+4, colour, font, Drawing::ALIGN_CENTER);
	}
	else if (viewtype == 1)
	{
		if (text_shadow) Drawing::drawText(name, x+size+9, y+(size*0.5)+1, COL_BLACK, font);
		Drawing::drawText(name, x+size+8, y+(size*0.5), colour, font);
		if (text_shadow) Drawing::drawText(S_FMT("%d", index), x+size+9, y+(size*0.5)-15, COL_BLACK, font);
		Drawing::drawText(S_FMT("%d", index), x+size+8, y+(size*0.5)-16, colour, font);
	}

	// If the item is blank don't bother with the image
	if (blank)
		return;

	// Try to load image if it isn't already
	if (!image || (image && !image->isLoaded()))
		loadImage();

	// If it still isn't just draw a red box with an X
	if (!image || (image && !image->isLoaded()))
	{
		glPushAttrib(GL_ENABLE_BIT|GL_CURRENT_BIT);

		glColor3f(1, 0, 0);
		glDisable(GL_TEXTURE_2D);

		// Outline
		glBegin(GL_LINE_LOOP);
		glVertex2i(x, y);
		glVertex2i(x, y+size);
		glVertex2i(x+size, y+size);
		glVertex2i(x+size, y);
		glEnd();

		// X
		glBegin(GL_LINES);
		glVertex2i(x, y);
		glVertex2i(x+size, y+size);
		glVertex2i(x, y+size);
		glVertex2i(x+size, y);
		glEnd();

		glPopAttrib();

		return;
	}

	// Determine texture dimensions
	double width = image->getWidth();
	double height = image->getHeight();

	// Scale up if size > 128
	if (size > 128)
	{
		double scale = (double)size / 128.0;
		width *= scale;
		height *= scale;
	}

	if (width > height)
	{
		// Scale down by width
		if (width > size)
		{
			double scale = (double)size / width;
			width *= scale;
			height *= scale;
		}
	}
	else
	{
		// Scale down by height
		if (height > size)
		{
			double scale = (double)size / height;
			width *= scale;
			height *= scale;
		}
	}

	// Determine draw coords
	double top = y + ((double)size * 0.5) - (height * 0.5);
	double left = x + ((double)size * 0.5) - (width * 0.5);

	// Draw
	image->bind();
	OpenGL::setColour(COL_WHITE, false);

	glBegin(GL_QUADS);
	glTexCoord2f(0.0f, 0.0f);	glVertex2d(left, top);
	glTexCoord2f(0.0f, 1.0f);	glVertex2d(left, top + height);
	glTexCoord2f(1.0f, 1.0f);	glVertex2d(left + width, top + height);
	glTexCoord2f(1.0f, 0.0f);	glVertex2d(left + width, top);
	glEnd();
}
Ejemplo n.º 15
0
void DSSkybox::load(GLuint index) {

    // 原来可能已经存在天空盒,需要清空
    del();

    GLuint texture_height, texture_width;

    // 先载入纹理,将纹理编号存入 texture[]
    tinyxml2::XMLDocument doc;
    doc.LoadFile("skyboxes.xml");
    auto root = doc.FirstChildElement();
    auto item = root->FirstChildElement("skybox");
    for (; item != nullptr; item = item->NextSiblingElement()) {

        // 找到了该序号的天空盒信息
        if (item->UnsignedAttribute("id") == index) {

            texture[0] = dsLoadTextureBMP2D(
                             item->FirstChildElement("t0")->GetText(),
                             &texture_height,
                             &texture_width
                         );
            texture[1] = dsLoadTextureBMP2D(
                             item->FirstChildElement("t1")->GetText()
                         );
            texture[2] = dsLoadTextureBMP2D(
                             item->FirstChildElement("t2")->GetText()
                         );
            texture[3] = dsLoadTextureBMP2D(
                             item->FirstChildElement("t3")->GetText()
                         );
            texture[4] = dsLoadTextureBMP2D(
                             item->FirstChildElement("t4")->GetText()
                         );
            texture[5] = dsLoadTextureBMP2D(
                             item->FirstChildElement("t5")->GetText()
                         );
            item->FirstChildElement("depth")->QueryDoubleText(&depth);

            break;
        }
    }

    // 再创建显示列表
    width = 2000;
    height = width / (GLdouble)texture_width * (GLdouble)texture_height;

    GLdouble x = width / 2;

    display_list = glGenLists(1);

    glNewList(display_list, GL_COMPILE); // GL_COMPILE_AND_EXECUTE
    {
        glPushAttrib(GL_ENABLE_BIT);
        glDisable(GL_LIGHTING);

        // 地面
        glBindTexture(GL_TEXTURE_2D, texture[5]);
        glBegin(GL_QUADS);
        {
            glTexCoord2d(1, 0);
            glVertex3d(- x, - x, - depth);
            glTexCoord2d(1, 1);
            glVertex3d(x, - x, - depth);
            glTexCoord2d(0, 1);
            glVertex3d(x, x, - depth);
            glTexCoord2d(0, 0);
            glVertex3d(- x, x, - depth);
        }
        glEnd();

        // 东面
        glBindTexture(GL_TEXTURE_2D, texture[0]);
        glBegin(GL_QUADS);
        {
            glTexCoord2d(0, 0);
            glVertex3d(x, x + 1, - depth);
            glTexCoord2d(0, 1);
            glVertex3d(x, x + 1, height - depth);
            glTexCoord2d(1, 1);
            glVertex3d(x, - x - 1, height - depth);
            glTexCoord2d(1, 0);
            glVertex3d(x, - x - 1, - depth);
        }
        glEnd();

        // 西面
        glBindTexture(GL_TEXTURE_2D, texture[1]);
        glBegin(GL_QUADS);
        {
            glTexCoord2d(0, 0);
            glVertex3d(- x, - x - 1, - depth);
            glTexCoord2d(0, 1);
            glVertex3d(- x, - x - 1, height - depth);
            glTexCoord2d(1, 1);
            glVertex3d(- x, x + 1, height - depth);
            glTexCoord2d(1, 0);
            glVertex3d(- x, x + 1, - depth);
        }
        glEnd();

        // 南面
        glBindTexture(GL_TEXTURE_2D, texture[2]);
        glBegin(GL_QUADS);
        {
            glTexCoord2d(0, 0);
            glVertex3d(x + 1, - x, - depth);
            glTexCoord2d(0, 1);
            glVertex3d(x + 1, - x, height - depth);
            glTexCoord2d(1, 1);
            glVertex3d(- x - 1, - x, height - depth);
            glTexCoord2d(1, 0);
            glVertex3d(- x - 1, - x, - depth);
        }
        glEnd();

        // 北面
        glBindTexture(GL_TEXTURE_2D, texture[3]);
        glBegin(GL_QUADS);
        {
            glTexCoord2d(0, 0);
            glVertex3d(- x - 1, x, - depth);
            glTexCoord2d(0, 1);
            glVertex3d(- x - 1, x, height - depth);
            glTexCoord2d(1, 1);
            glVertex3d(x + 1, x, height - depth);
            glTexCoord2d(1, 0);
            glVertex3d(x + 1, x, - depth);
        }
        glEnd();

        // 顶面
        glBindTexture(GL_TEXTURE_2D, texture[4]);
        glBegin(GL_QUADS);
        {
            glTexCoord2d(1, 1);
            glVertex3d(- x, -x, height - depth);
            glTexCoord2d(1, 0);
            glVertex3d(x, -x, height - depth);
            glTexCoord2d(0, 0);
            glVertex3d(x, x, height - depth);
            glTexCoord2d(0, 1);
            glVertex3d(- x, x, height - depth);
        }
        glEnd();

        //glEnable(GL_LIGHTING);
        glPopAttrib();
    }
    glEndList();
}
Ejemplo n.º 16
0
void ScreenCalibrator::display(GLContextData& contextData) const
	{
	/* Set up OpenGL state: */
	glPushAttrib(GL_ENABLE_BIT|GL_LINE_BIT|GL_POINT_BIT);
	glDisable(GL_LIGHTING);
	glPointSize(3.0f);
	
	/* Get the tracking point mover's transformation: */
	Vrui::NavTrackerState scaledDeviceT=Vrui::getInverseNavigationTransformation();
	scaledDeviceT*=trackingPointsMover->getTransformation();
	
	/* Calculate the point transformation: */
	Vrui::TrackerState pmt=Vrui::TrackerState(scaledDeviceT.getTranslation(),scaledDeviceT.getRotation());
	pmt*=trackingPointsTransform;
	pmt=Vrui::TrackerState::identity;
	
	/* Draw all tracking and survey points: */
	glBegin(GL_POINTS);
	glColor3f(1.0f,1.0f,0.0f);
	for(PointList::const_iterator tpIt=trackingPoints.begin();tpIt!=trackingPoints.end();++tpIt)
		glVertex(pmt.transform(*tpIt));
	glColor3f(0.0f,1.0f,0.0f);
	for(PointList::const_iterator spIt=screenPoints.begin();spIt!=screenPoints.end();++spIt)
		glVertex(*spIt);
	glColor3f(1.0f,0.0f,0.0f);
	for(PointList::const_iterator fpIt=floorPoints.begin();fpIt!=floorPoints.end();++fpIt)
		glVertex(*fpIt);
	glColor3f(1.0f,0.0f,1.0f);
	for(PointList::const_iterator bpIt=ballPoints.begin();bpIt!=ballPoints.end();++bpIt)
		glVertex(*bpIt);
	glEnd();
	
	/* Draw all tracker calibration pairs: */
	size_t numPoints=trackingPoints.size();
	if(numPoints>ballPoints.size())
		numPoints=ballPoints.size();
	glBegin(GL_LINES);
	for(size_t i=0;i<numPoints;++i)
		{
		glColor3f(1.0f,1.0f,0.0f);
		glVertex(pmt.transform(trackingPoints[i]));
		glColor3f(1.0f,0.0f,1.0f);
		glVertex(ballPoints[i]);
		}
	glEnd();
	
	/* Draw the screen rectangle: */
	glBegin(GL_LINE_LOOP);
	glColor3f(0.0f,1.0f,0.0f);
	glVertex(screenTransform.transform(Point(0,0,0)));
	glVertex(screenTransform.transform(Point(screenSize[0],0,0)));
	glVertex(screenTransform.transform(Point(screenSize[0],screenSize[1],0)));
	glVertex(screenTransform.transform(Point(0,screenSize[1],0)));
	glEnd();
	
	/* Draw the projected screen quadrangle: */
	glBegin(GL_LINE_LOOP);
	glColor3f(0.0f,0.0f,1.0f);
	glVertex(pScreenTransform.transform(Point(0,0,0)));
	glVertex(pScreenTransform.transform(Point(1,0,0)));
	glVertex(pScreenTransform.transform(Point(1,1,0)));
	glVertex(pScreenTransform.transform(Point(0,1,0)));
	glEnd();
	
	/* Reset OpenGL state: */
	glPopAttrib();
	}
Ejemplo n.º 17
0
	// Pops The Projection Matrix Without Changing The Current
	// MatrixMode.
	inline void pop_projection_matrix() {
		glPushAttrib(GL_TRANSFORM_BIT);
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glPopAttrib();
	}
Ejemplo n.º 18
0
void GLWidget::paintGL()
{
    glPopMatrix(); // pop the matrix pushed in the pbuffer list

    // push the projection matrix and the entire GL state before
    // doing any rendering into our framebuffer object
    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();

    glViewport(0, 0, fbo->size().width(), fbo->size().height());
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1, 1, -1, 1, -99, 99);
    glTranslatef(-0.5f, -0.5f, 0.0f);
    glMatrixMode(GL_MODELVIEW);

    // render to the framebuffer object
    fbo->bind();
    glBindTexture(GL_TEXTURE_2D, cubeTexture);
    glCallList(pbufferList);
    fbo->release();

    // pop the projection matrix and GL state back for rendering
    // to the actual widget
    glPopAttrib();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    glBindTexture(GL_TEXTURE_2D, fbo->texture());
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // draw the background
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();

    glVertexPointer(2, GL_INT, 0, faceArray);
    glTranslatef(-1.2f, -0.8f, 0.0f);
    glScalef(0.2f, 0.2f, 0.2f);
    for (int y = 0; y < 5; ++y) {
	for (int x = 0; x < 5; ++x) {
	    glTranslatef(2.0f, 0, 0);
	    glColor4f(0.8f, 0.8f, 0.8f, 1.0f);
	    glDrawArrays(GL_QUADS, 0, 4);
	}
 	glTranslatef(-10.0f, 2.0f, 0);
    }
    glVertexPointer(3, GL_INT, 0, cubeArray);

    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);

    // draw the bouncing cubes
    drawCube(0, 0.0f, 1.5f, 2.5f, 1.5f);
    drawCube(1, 1.0f, 2.0f, 2.5f, 2.0f);
    drawCube(2, 2.0f, 3.5f, 2.5f, 2.5f);
    glPopMatrix();
}
Ejemplo n.º 19
0
void
USDVMP::draw(FnKat::ViewerModifierInput& input) 
{
    TF_DEBUG(KATANA_DEBUG_VMP_USD).Msg("%s @ %p : %s\n",
            TF_FUNC_NAME().c_str(), this, _prim.GetPath().GetString().c_str());

    // Render
    if (_stage) {
        // Get draw options needed for styling.
        bool isSelected = input.getDrawOption("selected");
        bool drawPoints = input.getDrawOption("fillPoints");
        bool drawWireframe = input.getDrawOption("fillWireframe");
        bool drawSmooth = input.getDrawOption("shadingSmooth");
        bool isPicking = input.getDrawOption("isPicking");

        // Clear out override color
        _params.overrideColor[3] = 0.0f;

        // Determine the approrpiate draw mode based on the styling options.
        if ( drawSmooth ) {
            if (_GetProxyOverlayMode() == _tokens->wireframe) {
                _params.drawMode = UsdImagingGL::DRAW_WIREFRAME_ON_SURFACE;
            } else {
                _params.drawMode = UsdImagingGL::DRAW_SHADED_SMOOTH;
            }
        }
        if ( drawWireframe ) {
            _params.drawMode = UsdImagingGL::DRAW_WIREFRAME;
        }
        if ( drawPoints ) { 
            // TODO: support draw points
            _params.drawMode = UsdImagingGL::DRAW_POINTS;
        }

        // If this gprim is selected setup drawmode and selection color.
        if ( isSelected ) {
            _params.drawMode = UsdImagingGL::DRAW_GEOM_SMOOTH;
            _params.overrideColor = GfVec4f(0.0f, 1.0f, 1.0f, 1.0f);
            glColor4fv(_params.overrideColor.GetArray());
        }
        if (isPicking) {
            if(input.getDrawOption("hasPickColor") == 1) {
                GfVec4f pickColor(0, 0, 0, 1);
                pickColor[0] = input.getDrawOptionFloat("pickColorR");
                pickColor[1] = input.getDrawOptionFloat("pickColorG");
                pickColor[2] = input.getDrawOptionFloat("pickColorB");
                _params.overrideColor = pickColor;
            }
            else {
                // Most horrible hack in the world :(
                // Katana does it's picking by setting a shader
                // that takes a pick id and renders geometry with
                // the color representation of that id.
                // Unfortunately if we are using Hydra, we need to
                // use our own shaders. To get around this, we are
                // using specific knowledge of the katana pick shader
                // to extract the pick id and set our own override color
                // based on this id. This is basically emulating what the
                // katana shader is doing.
                GLint program = -1;
                glGetIntegerv(GL_CURRENT_PROGRAM, &program);
                TF_VERIFY(program != -1);
                GLint kat_PickIdLoc = glGetUniformLocation(program, "kat_PickId");
                if (TF_VERIFY(kat_PickIdLoc != -1)) {
                    GLint kat_PickId;
                    glGetUniformiv(program, kat_PickIdLoc, &kat_PickId);
                    // Simulate pick id with color
                    _params.overrideColor = GfVec4f(
                        ((float)((kat_PickId >> 0  ) & 0xff)) / 255.0f,
                        ((float)((kat_PickId >> 8  ) & 0xff)) / 255.0f,
                        ((float)((kat_PickId >> 16 ) & 0xff)) / 255.0f,
                        1.0f);
                }
            }
            // Using DRAW_GEOM_ONLY will disable lighting and make
            // sure we are rendering a solid color
            _params.drawMode = UsdImagingGL::DRAW_GEOM_ONLY;
        }

        // Save and restore shader settings around render call
        // because hydra does not restore shader state.
        GLint oldProgram = -1;
        glGetIntegerv(GL_CURRENT_PROGRAM, &oldProgram);

        if (TF_VERIFY(_renderer)) {
            _renderer->SetCameraStateFromOpenGL();

            glPushAttrib(GL_LIGHTING_BIT | GL_ENABLE_BIT);

            if (_GetProxyOverlayMode() == _tokens->ghosted) {
                glEnable(GL_LIGHT0);
                float f = 0.1;
                float params[4] = { f, 0.0, f, 1.0 };
                glLightfv(GL_LIGHT0, GL_AMBIENT, params);
            }

            _renderer->SetLightingStateFromOpenGL();

            glPopAttrib();

            // The multi-threaded Usd Op may be loading or unloading models on
            // the stage we need, so we grab the global lock in reader mode
            // before rendering.
            boost::shared_lock<boost::upgrade_mutex> 
                                            readerLock(UsdKatanaGetStageLock());
            
            _renderer->Render(_prim, _params);
        }

        // Restore old shader
        glUseProgram(oldProgram);
    }
Ejemplo n.º 20
0
void 
GltSkySphere::draw() const
{
	if (!visible())
		return;
		
	GLERROR

	GltViewport viewport(true);

	//
	// Setup perspective camera mode,
	// orthogonal doesn't really work...
	//

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	gluPerspective(_fov,double(viewport.width())/double(viewport.height()), 0.1, 200.0);

	//
	// Twiddle the current modelview matrix
	// to cancel out translation and scale.
	//

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();

	Matrix      matrix(GL_MODELVIEW_MATRIX);

	// No translation

	matrix[12] = 0.0;
	matrix[13] = 0.0;
	matrix[14] = 0.0;

	// No scale

	const real sf = sqrt( SQ(matrix[0]) + SQ(matrix[1]) + SQ(matrix[2]) ); 
	matrix *= matrixScale(1.0/sf);

	//

	matrix.glLoadMatrix();
	transformation().glMultMatrix();
	
	//
	//
	//

		GLERROR

		glPushAttrib(GL_ENABLE_BIT|GL_POLYGON_BIT|GL_LIGHTING_BIT);

			glDisable(GL_DEPTH_TEST);
			glDisable(GL_LIGHTING);
			glDisable(GL_TEXTURE_2D);
			glEnable(GL_CULL_FACE);

			if (solid())
			{
				glEnable(GL_BLEND);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
				glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
				glShadeModel(GL_SMOOTH);
			}
			else
			{
				glDisable(GL_BLEND);
				glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
				glShadeModel(GL_FLAT);
			}
			
			//

			drawSphere(_map,_slices);

			//

		glPopAttrib();

		GLERROR

	glPopMatrix();
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);

	GLERROR
}
Ejemplo n.º 21
0
int APIENTRY WinMain(HINSTANCE hCurrentInst, HINSTANCE hPreviousInst,LPSTR lpszCmdLine, int nCmdShow) // int main(int argc, char *argv[])
{
	std::cout << "Test Physics\n";

	std::vector<RigidBody*> rigidbodies;
	rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(1)) }, { 1.5f, 0.0f, 1.5f }));
	rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(1)) }, { -1.5f, 0.0f, 1.5f }));
	rigidbodies.back()->orientation = normalize(float4(0.1f, 0.01f, 0.3f, 1.0f));
	auto seesaw = new RigidBody({ AsShape(WingMeshBox( { 3, 0.5f, 0.1f })) }, { 0, -2.5, 0.25f });
	rigidbodies.push_back(seesaw);
	rigidbodies.push_back( new RigidBody({ AsShape(WingMeshCube(0.25f)) }, seesaw->position_start + float3( 2.5f, 0, 0.4f)));
	rigidbodies.push_back( new RigidBody({ AsShape(WingMeshCube(0.50f)) }, seesaw->position_start + float3(-2.5f, 0, 5.0f)));
	rbscalemass(rigidbodies.back(), 4.0f);
	rigidbodies.push_back(new RigidBody({ AsShape(WingMeshBox({1,0.2f,0.2f})),AsShape(WingMeshBox({0.2f,1,0.2f})),AsShape(WingMeshBox({0.2f,0.2f,1})) }, { -1.5f, 0.5f, 7.5f }));
	for (float z = 5.5f; z < 14.0f; z += 3.0f)
		rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(0.5f)) }, { 0.0f, 0.0f, z }));
	for (float z = 15.0f; z < 20.0f; z += 3.0f)
		rigidbodies.push_back(new RigidBody({ AsShape(WingMeshDual(WingMeshCube(0.5f), 0.65f)) }, { 2.0f, -1.0f, z }));

	WingMesh world_slab = WingMeshBox({ -10, -10, -5 }, { 10, 10, -2 }); // world_geometry



	GLWin glwin("TestPhys sample");
	glwin.ViewAngle = 60.0f;

	glwin.keyboardfunc = [&](unsigned char key, int x, int y)->void 
	{
			switch (std::tolower(key))
			{
			case ' ':
				g_simulate = !g_simulate;
				break;
			case 'q': case 27:   // ESC
				exit(0); break;  
			case 'r':
				for (auto &rb : rigidbodies)
				{
					rb->position = rb->position_start;
					//rb->orientation = rb->orientation_start;  // when commented out this provides some variation
					rb->linear_momentum  = float3(0, 0, 0);
					rb->angular_momentum = float3(0, 0, 0);
				}
				seesaw->orientation = { 0, 0, 0, 1 };
				break;
			default:
				std::cout << "unassigned key (" << (int)key << "): '" << key << "'\n";
				break;
			}
	};

	InitTex();
	int2 mouseprev;
	while (glwin.WindowUp())
	{
		if (glwin.MouseState)  // on mouse drag 
		{
			g_yaw   += (glwin.MouseX - mouseprev.x) * 0.3f;  // poor man's trackball
			g_pitch += (glwin.MouseY - mouseprev.y) * 0.3f;
		}
		mouseprev = { glwin.MouseX, glwin.MouseY };

		if (g_simulate)
		{
			std::vector<LimitAngular> angulars;
			std::vector<LimitLinear>  linears;
			Append(linears , ConstrainPositionNailed(NULL, seesaw->position_start, seesaw, { 0, 0, 0 }));
			Append(angulars, ConstrainAngularRange(NULL, seesaw, { 0, 0, 0, 1 }, { 0, -20, 0 }, { 0, 20, 0 }));
			PhysicsUpdate(rigidbodies, linears, angulars, { &world_slab.verts });
		}


		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glViewport(0, 0, glwin.Width,glwin.Height);  // Set up the viewport
		glClearColor(0.1f, 0.1f, 0.15f, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glEnable(GL_DEPTH_TEST);

		// Set up matrices
		glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity();
		gluPerspective(glwin.ViewAngle, (double)glwin.Width/ glwin.Height, 0.01, 50);

		glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity();
		gluLookAt(0, -8, 5, 0, 0, 0, 0, 0, 1);
		glRotatef(g_pitch, 1, 0, 0);
		glRotatef(g_yaw, 0, 0, 1);

		wmdraw(world_slab);  // world_geometry

		glEnable(GL_POLYGON_OFFSET_FILL);
		glPolygonOffset(1., 1. / (float)0x10000);
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		glEnable(GL_TEXTURE_2D);
		glColor3f(0.5f, 0.5f, 0.5f);
		for (auto &rb : rigidbodies)
			rbdraw(rb);

		
		glPopAttrib();   // Restore state
		glMatrixMode(GL_PROJECTION); glPopMatrix();
		glMatrixMode(GL_MODELVIEW);  glPopMatrix();  

		glwin.PrintString({ 5, 0 },"ESC/q quits. SPACE to simulate. r to restart");
		glwin.PrintString({ 5, 1 }, "simulation %s", (g_simulate) ? "ON" : "OFF");
		glwin.SwapBuffers();
	}

	std::cout << "\n";
	return 0;
}
Ejemplo n.º 22
0
Archivo: Game.cpp Proyecto: m1h4/Xetrix
void Ship::DrawShip(void)
{
	glPushMatrix();
	glTranslatef(m_position.x,m_position.y,0.0f);
	glRotatef(m_orientation / (float)M_PI * 180.0f,0.0f,0.0f,1.0f);

	glPushAttrib(GL_CURRENT_BIT);

	glBegin(GL_LINE_LOOP);
		glVertex2f(-0.25f,0.25f);
		glVertex2f(0.75f,-0.02f);
		glVertex2f(0.75f,-0.2f);
		glVertex2f(-0.25f,-0.2f);
		glVertex2f(-0.75f,0.05f);
		glVertex2f(-1.5f,0.15f);
		glVertex2f(-1.5f,0.25f);
	glEnd();

	glBegin(GL_LINES);
		glVertex2f(-0.25f,0.25f);
		glVertex2f(0.0f,0.0f);

		glVertex2f(0.0f,0.0f);
		glVertex2f(0.75f,-0.05f);

		glVertex2f(-1.45f,0.25f);
		glVertex2f(-1.65f,0.4f);

		glVertex2f(-1.65f,0.4f);
		glVertex2f(-1.4f,0.4f);
		
		glVertex2f(-1.4f,0.4f);
		glVertex2f(-1.1f,0.25f);
	glEnd();

	if(debugDraw)
	{
		Vector2 point[] = {Vector2(0.75f,-0.2f),Vector2(-1.5f,0.15f)};
		Matrix2 orientation(m_orientation);
		Matrix2 orientationInverse(-m_orientation);

		glBegin(GL_LINES);
			glColor3f(1.0f,0.0f,0.0f);
			glVertex2fv(point[0]);
			glVertex2fv(point[0] - GetBodyVelocity(m_position + point[0] * orientation) * orientationInverse * 10.0f);
			glVertex2fv(point[1]);
			glVertex2fv(point[1] - GetBodyVelocity(m_position + point[1] * orientation) * orientationInverse * 10.0f);
		glEnd();
	}

	glPushMatrix();
	glTranslatef(m_rearEnginePosition.x,m_rearEnginePosition.y,0.0f);
	glRotatef(m_rearEngineOrientation / (float)M_PI * 180.0f + 90.0f,0.0f,0.0f,1.0f);

	glColor3f(0.0f,1.0f,1.0f);

	// Rear engine
	glBegin(GL_LINE_LOOP);
		glVertex2f(-0.08f,0.0f);
		glVertex2f(-0.1f,0.05f);
		glVertex2f(0.08f,0.05f);
		glVertex2f(0.1f,0.0f);
		glVertex2f(0.08f,-0.05f);
		glVertex2f(-0.1f,-0.05f);
	glEnd();

	glPopMatrix();
	glPushMatrix();
	glTranslatef(m_mainEnginePosition.x,m_mainEnginePosition.y,0.0f);
	glScalef(2.0f,2.0f,1.0f);
	glRotatef(m_mainEngineOrientation / (float)M_PI * 180.0f + 90.0f,0.0f,0.0f,1.0f);

	// Main engine
	glBegin(GL_LINE_LOOP);
		glVertex2f(-0.08f,0.0f);
		glVertex2f(-0.1f,0.05f);
		glVertex2f(0.08f,0.05f);
		glVertex2f(0.1f,0.0f);
		glVertex2f(0.08f,-0.05f);
		glVertex2f(-0.1f,-0.05f);
	glEnd();

	glPopMatrix();
	glPushMatrix();
	glTranslatef(m_frontEnginePosition.x,m_frontEnginePosition.y,0.0f);
	glRotatef(m_frontEngineOrientation / (float)M_PI * 180.0f + 90.0f,0.0f,0.0f,1.0f);

	// Front engine
	glBegin(GL_LINE_LOOP);
		glVertex2f(-0.08f,0.0f);
		glVertex2f(-0.1f,0.05f);
		glVertex2f(0.08f,0.05f);
		glVertex2f(0.1f,0.0f);
		glVertex2f(0.08f,-0.05f);
		glVertex2f(-0.1f,-0.05f);
	glEnd();

	glPopMatrix();

	glPopAttrib();

	glPopMatrix();
}
Ejemplo n.º 23
0
void djvOpenGlImage::draw(
    const djvPixelData &          data,
    const djvOpenGlImageOptions & options,
    djvOpenGlImageState *         state) throw (djvError)
{
    //DJV_DEBUG("djvOpenGlImage::draw");
    //DJV_DEBUG_PRINT("data = " << data);
    //DJV_DEBUG_PRINT("color profile = " << options.colorProfile);
    
    RestoreState restoreState;

    djvOpenGlImageState defaultState;

    if (! state)
    {
        state = &defaultState;
    }

    const djvPixelDataInfo & info = data.info();

    const int proxyScale =
        options.proxyScale ?
        djvPixelDataUtil::proxyScale(info.proxy) :
        1;

    const djvVector2i scale = djvVectorUtil::ceil<double, int>(
        options.xform.scale * djvVector2f(info.size * proxyScale));

    const djvVector2i scaleTmp(scale.x, data.h());

    //DJV_DEBUG_PRINT("scale = " << scale);
    //DJV_DEBUG_PRINT("scale tmp = " << scaleTmp);

    // Initialize.

    const djvOpenGlImageFilter::FILTER filter =
        info.size == scale ? djvOpenGlImageFilter::NEAREST :
        (djvVectorUtil::area(scale) < djvVectorUtil::area(info.size) ?
         options.filter.min : options.filter.mag);

    //DJV_DEBUG_PRINT("filter min = " << options.filter.min);
    //DJV_DEBUG_PRINT("filter mag = " << options.filter.mag);
    //DJV_DEBUG_PRINT("filter = " << filter);

    if (! state->_init || state->_info != info || state->_options != options)
    {
        switch (filter)
        {
            case djvOpenGlImageFilter::NEAREST:
            case djvOpenGlImageFilter::LINEAR:
            {
                //DJV_DEBUG_PRINT("init single pass");

                state->_texture->init(
                    data.info(),
                    djvOpenGlImageFilter::toGl(filter),
                    djvOpenGlImageFilter::toGl(filter));

                state->_shader->init(
                    sourceVertex,
                    sourceFragment(
                        options.colorProfile.type,
                        options.displayProfile,
                        options.channel,
                        false,
                        0,
                        false));
            }
            break;

            case djvOpenGlImageFilter::BOX:
            case djvOpenGlImageFilter::TRIANGLE:
            case djvOpenGlImageFilter::BELL:
            case djvOpenGlImageFilter::BSPLINE:
            case djvOpenGlImageFilter::LANCZOS3:
            case djvOpenGlImageFilter::CUBIC:
            case djvOpenGlImageFilter::MITCHELL:
            {
                //DJV_DEBUG_PRINT("init two pass");

                state->_texture->init(
                    data.info(),
                    GL_NEAREST,
                    GL_NEAREST);

                // Initialize horizontal pass.

                djvPixelData contrib;

                scaleContrib(
                    data.w(),
                    scale.x,
                    filter,
                    contrib);

                state->_scaleXContrib->init(
                    contrib,
                    GL_NEAREST,
                    GL_NEAREST);

                state->_scaleXShader->init(
                    sourceVertex,
                    sourceFragment(
                        options.colorProfile.type,
                        djvOpenGlImageDisplayProfile(),
                        static_cast<djvOpenGlImageOptions::CHANNEL>(0),
                        true,
                        contrib.h(),
                        true));

                // Initialize vertical pass.

                scaleContrib(
                    data.h(),
                    scale.y,
                    filter,
                    contrib);

                state->_scaleYContrib->init(
                    contrib,
                    GL_NEAREST,
                    GL_NEAREST);

                state->_scaleYShader->init(
                    sourceVertex,
                    sourceFragment(
                        static_cast<djvColorProfile::PROFILE>(0),
                        options.displayProfile,
                        options.channel,
                        true,
                        contrib.h(),
                        false));
            }
            break;

            default: break;
        }

        state->_init    = true;
        state->_info    = info;
        state->_options = options;
    }

    // Render.

    const djvPixelDataInfo::Mirror mirror(
        info.mirror.x ? (! options.xform.mirror.x) : options.xform.mirror.x,
        info.mirror.y ? (! options.xform.mirror.y) : options.xform.mirror.y);

    //DJV_DEBUG_PRINT("mirror = " << mirror.x << " " << mirror.y);

    switch (filter)
    {
        case djvOpenGlImageFilter::NEAREST:
        case djvOpenGlImageFilter::LINEAR:
        {
            //DJV_DEBUG_PRINT("draw single pass");

            state->_shader->bind();

            // Initialize color and display profiles.

            colorProfileInit(
                options,
                state->_shader->program(),
                *state->_lutColorProfile);

            displayProfileInit(
                options,
                state->_shader->program(),
                *state->_lutDisplayProfile);

            // Draw.

            activeTexture(GL_TEXTURE0);

            uniform1i(state->_shader->program(), "inTexture", 0);

            state->_texture->copy(data);
            state->_texture->bind();

            DJV_DEBUG_OPEN_GL(glPushMatrix());
            const djvMatrix3f m = djvOpenGlImageXform::xformMatrix(options.xform);
            //DJV_DEBUG_PRINT("m = " << m);
            DJV_DEBUG_OPEN_GL(glLoadMatrixd(djvMatrixUtil::matrix4(m).e));

            quad(info.size, mirror, proxyScale);

            DJV_DEBUG_OPEN_GL(glPopMatrix());
        }
        break;

        case djvOpenGlImageFilter::BOX:
        case djvOpenGlImageFilter::TRIANGLE:
        case djvOpenGlImageFilter::BELL:
        case djvOpenGlImageFilter::BSPLINE:
        case djvOpenGlImageFilter::LANCZOS3:
        case djvOpenGlImageFilter::CUBIC:
        case djvOpenGlImageFilter::MITCHELL:
        {
            //DJV_DEBUG_PRINT("draw two pass");

            // Horizontal pass.

            djvOpenGlOffscreenBuffer buffer(
                djvPixelDataInfo(scaleTmp, data.pixel()));

            {
                djvOpenGlOffscreenBufferScope bufferScope(&buffer);

                state->_scaleXShader->bind();

                colorProfileInit(
                    options,
                    state->_scaleXShader->program(),
                    *state->_lutColorProfile);

                activeTexture(GL_TEXTURE0);

                uniform1i(state->_scaleXShader->program(), "inTexture", 0);

                state->_texture->copy(data);
                state->_texture->bind();

                activeTexture(GL_TEXTURE1);

                uniform1i(
                    state->_scaleXShader->program(), "inScaleContrib", 1);

                state->_scaleXContrib->bind();

                glPushAttrib(GL_TRANSFORM_BIT | GL_VIEWPORT_BIT);
                glMatrixMode(GL_PROJECTION);
                glPushMatrix();
                glMatrixMode(GL_MODELVIEW);
                glPushMatrix();

                djvOpenGlUtil::ortho(scaleTmp);
                glViewport(0, 0, scaleTmp.x, scaleTmp.y);
                quad(scaleTmp, mirror);

                glMatrixMode(GL_PROJECTION);
                glPopMatrix();
                glMatrixMode(GL_MODELVIEW);
                glPopMatrix();
                glPopAttrib();
            }

            // Vertical pass.

            state->_scaleYShader->bind();

            displayProfileInit(
                options,
                state->_scaleYShader->program(),
                *state->_lutDisplayProfile);

            activeTexture(GL_TEXTURE0);

            uniform1i(state->_scaleYShader->program(), "inTexture", 0);

            DJV_DEBUG_OPEN_GL(glBindTexture(GL_TEXTURE_2D, buffer.texture()));

            activeTexture(GL_TEXTURE1);

            uniform1i(state->_scaleYShader->program(), "inScaleContrib", 1);

            state->_scaleYContrib->bind();

            djvOpenGlImageXform xform = options.xform;
            xform.scale = djvVector2f(1.0);
            const djvMatrix3f m = djvOpenGlImageXform::xformMatrix(xform);

            DJV_DEBUG_OPEN_GL(glPushMatrix());
            DJV_DEBUG_OPEN_GL(glLoadMatrixd(djvMatrixUtil::matrix4(m).e));

            quad(scale);

            DJV_DEBUG_OPEN_GL(glPopMatrix());
        }
        break;

        default: break;
    }
}
Ejemplo n.º 24
0
Archivo: Game.cpp Proyecto: m1h4/Xetrix
bool DrawGame(void)
{
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	//glTranslatef(0.0f,0.0f,-8.0f);
	gluLookAt(0.0f,0.0f,18.0,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f);

	glPushAttrib(GL_CURRENT_BIT);

	glBegin(GL_LINES);
		Matrix2 orientation(gameShip.m_orientation);

#ifdef _DEBUG
		if(debugDraw)
		{
			glColor3f(1.0f,0.0f,0.0f);

			glVertex2f(0.0f,0.0f);
			glVertex2f(1.0f,0.0f);

			glColor3f(0.0f,1.0f,0.0f);

			glVertex2f(0.0f,0.0f);
			glVertex2f(0.0f,1.0f);
		}
#endif

		glColor3f(0.0f,0.0f,1.0f);

		if(debugSpring1)
		{
			glVertex2fv(gameSpring1);
			glVertex2fv(gameShip.m_position + orientation * gameAnchor1);
		}

		if(debugSpring2)
		{
			glVertex2fv(gameSpring2);
			glVertex2fv(gameShip.m_position + orientation * gameAnchor2);
		}

		for(unsigned long i = 0; i < gameMissles.GetSize(); ++i)
		{
			if(gameMissles[i]->m_spring)
			{
				glVertex2fv(*gameMissles[i]->m_spring);
				glVertex2fv(gameMissles[i]->m_position);
			}
		}
	glEnd();

	glPopAttrib();

	gameShip.DrawShip();
	gameEmitter.DrawParticles();

	for(unsigned long i = 0; i < gameMissles.GetSize(); ++i)
		gameMissles[i]->DrawMissle();

	return true;
}
Ejemplo n.º 25
0
	void	x3ds_instance::display()
	{
		assert(m_def != NULL);

		if (m_def->m_file == NULL)
		{
			return;
		}

		//update_material();

		// save GL state
		glPushAttrib (GL_ALL_ATTRIB_BITS);	
		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();

		// apply gameSWF matrix

		rect bound;
		m_def->get_bound(&bound);

		matrix m = get_parent()->get_world_matrix();
		m.transform(&bound);

		// get viewport size
		GLint vp[4]; 
		glGetIntegerv(GL_VIEWPORT, vp); 
//		int vp_width = vp[2];
		int vp_height = vp[3];

		bound.twips_to_pixels();
		int w = (int) (bound.m_x_max - bound.m_x_min);
		int h = (int) (bound.m_y_max - bound.m_y_min);
		int x = (int) bound.m_x_min;
		int y = (int) bound.m_y_min;
		glViewport(x, vp_height - y - h, w, h);

		// set 3D params

		glClear(GL_DEPTH_BUFFER_BIT);
		glDepthFunc(GL_LEQUAL);
		glEnable(GL_DEPTH_TEST);
		glCullFace(GL_BACK);

		glEnable(GL_POLYGON_SMOOTH);
//		glEnable(GL_BLEND);
//		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glDisable(GL_BLEND);

		// set GL matrix to identity
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();

		assert(m_camera);

		Lib3dsNode* cnode = lib3ds_file_node_by_name(m_def->m_file, m_camera->name, LIB3DS_CAMERA_NODE);
		Lib3dsNode* tnode = lib3ds_file_node_by_name(m_def->m_file, m_camera->name, LIB3DS_TARGET_NODE);

		float* target = tnode ? tnode->data.target.pos : m_camera->target;

		float	view_angle;
		float roll;
		float* camera_pos;
		if (cnode)
		{
			view_angle = cnode->data.camera.fov;
			roll = cnode->data.camera.roll;
			camera_pos = cnode->data.camera.pos;
		}
		else
		{
			view_angle = m_camera->fov;
			roll = m_camera->roll;
			camera_pos = m_camera->position;
		}

		float ffar = m_camera->far_range;
		float nnear = m_camera->near_range <= 0 ? ffar * .001f : m_camera->near_range;

		float top = tan(view_angle * 0.5f) * nnear;
		float bottom = -top;
		float aspect = 1.3333f;	// 4/3 == width /height
		float left = aspect* bottom;
		float right = aspect * top;

		//	gluPerspective(fov, aspect, nnear, ffar) ==> glFrustum(left, right, bottom, top, nnear, ffar);
		//	fov * 0.5 = arctan ((top-bottom)*0.5 / near)
		//	Since bottom == -top for the symmetrical projection that gluPerspective() produces, then:
		//	top = tan(fov * 0.5) * near
		//	bottom = -top
		//	Note: fov must be in radians for the above formulae to work with the C math library. 
		//	If you have comnputer your fov in degrees (as in the call to gluPerspective()), 
		//	then calculate top as follows:
		//	top = tan(fov*3.14159/360.0) * near
		//	The left and right parameters are simply functions of the top, bottom, and aspect:
		//	left = aspect * bottom
		//	right = aspect * top
		glFrustum(left, right, bottom, top, nnear, ffar);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glRotatef(-90., 1.0, 0., 0.);

		// apply camera matrix
		Lib3dsMatrix cmatrix;
		lib3ds_matrix_camera(cmatrix, camera_pos, target, roll);
		glMultMatrixf(&cmatrix[0][0]);

		// apply light
		set_light();

		// draw 3D model

		for (Lib3dsNode* p = m_def->m_file->nodes; p != 0; p = p->next)
		{
			render_node(p);
		}

		// restore openGL state
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
		glPopAttrib();
	}
Ejemplo n.º 26
0
void GlslApplication::render_scene() const
{
    // backup state so it doesn't mess up students stuff
    glPushAttrib( GL_ALL_ATTRIB_BITS );
    glPushClientAttrib( GL_CLIENT_ALL_ATTRIB_BITS );
    // we set most gl state each time since it all gets popped each frame

    glClearColor(
        scene.background_color.r,
        scene.background_color.g,
        scene.background_color.b,
        1.0f );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glEnable( GL_NORMALIZE );
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_LIGHTING );
    glEnable( GL_TEXTURE_2D );

    // set camera transform

    const Camera& camera = camera_control.camera;

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective( camera.get_fov_degrees(),
                    camera.get_aspect_ratio(),
                    camera.get_near_clip(),
                    camera.get_far_clip() );

    const Vector3& campos = camera.get_position();
    const Vector3 camref = camera.get_direction() + campos;
    const Vector3& camup = camera.get_up();

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    gluLookAt( campos.x, campos.y, campos.z,
               camref.x, camref.y, camref.z,
               camup.x,  camup.y,  camup.z );
    // set light data
    float arr[4];
    arr[3] = 1.0; // w is always 1

    scene.ambient_light.to_array( arr );
    glLightModelfv( GL_LIGHT_MODEL_AMBIENT, arr );

    glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE );

    const Scene::PointLightList& lights = scene.get_lights();

    for ( size_t i = 0; i < NUM_GL_LIGHTS && i < lights.size(); i++ ) {
        const PointLight& light = lights[i];
        glEnable( LightConstants[i] );
        light.color.to_array( arr );
        glLightfv( LightConstants[i], GL_DIFFUSE, arr );
        glLightfv( LightConstants[i], GL_SPECULAR, arr );
        glLightf( LightConstants[i], GL_CONSTANT_ATTENUATION, light.attenuation.constant );
        glLightf( LightConstants[i], GL_LINEAR_ATTENUATION, light.attenuation.linear );
        glLightf( LightConstants[i], GL_QUADRATIC_ATTENUATION, light.attenuation.quadratic );
        light.position.to_array( arr );
        glLightfv( LightConstants[i], GL_POSITION, arr );
    }
    // render each object

    const Scene::GeometryList& geometries = scene.get_geometries();

    for ( size_t i = 0; i < geometries.size(); ++i ) {
        const Geometry& geom = *geometries[i];
        Vector3 axis;
        real_t angle;

        glPushMatrix();

        glTranslated( geom.position.x, geom.position.y, geom.position.z );
        geom.orientation.to_axis_angle( &axis, &angle );
        glRotated( angle * ( 180.0 / PI ), axis.x, axis.y, axis.z );
        glScaled( geom.scale.x, geom.scale.y, geom.scale.z );

        geom.render();

        glPopMatrix();
    }

    glPopClientAttrib();
    glPopAttrib();
}
Ejemplo n.º 27
0
bool NMS_SceneRenderer::initRendering()
{
	bool fullscreen = false;
	int width = 600;
	int height = 400;
	int flags;
	char* windowTitle = "Demo 2";
	bool bpp = false;

	//try to initialize SDL
	if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) 
		{ return false; } 
	
	if (fullscreen) {
		flags = SDL_OPENGL | SDL_FULLSCREEN;
		SDL_ShowCursor(SDL_DISABLE);
		SDL_WM_GrabInput(SDL_GRAB_ON);
	}
	else
	{
		flags = SDL_OPENGL;
		SDL_ShowCursor(SDL_DISABLE);
		SDL_WM_GrabInput(SDL_GRAB_ON);
	}

	SDL_WM_SetCaption(windowTitle,NULL);  //Set the name of the window
	SDL_SetVideoMode(width, height, bpp, flags); //Set the window mode

	
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glViewport(0, 0, width, height); // Set the dimensions of the viewport
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glClearDepth(1.0f);									// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations
	glFrustum(    -0.5f,
                0.5f,
                -0.5f*(float)(height/width),
                0.5f*(float)(height/width),
                1.0f,
                500.0f);
		
	gluPerspective(60.0, (float)width/(float)height, 1.0, width);
	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	//Enable Light
	//glEnable(GL_TEXTURE_2D); //Initialize OpenGl and texture mapping
	//glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
	//glEnable(GL_COLOR_MATERIAL);							// Enable Smooth Shading
	glEnable(GL_DEPTH_TEST);
	glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask
	glShadeModel(GL_SMOOTH);
	//glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	currentTime=1;
	return true;
}
Ejemplo n.º 28
0
void CPostprocManager::ApplyBlurGauss(GLuint inOutTex, GLuint tempTex, int inWidth, int inHeight)
{
	// Set tempTex as our rendering target.
	pglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_BloomFbo);
	pglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tempTex, 0);
	
	// Get bloom shader, for a horizontal Gaussian blur pass.
	CShaderDefines defines2;
	defines2.Add(str_BLOOM_PASS_H, str_1);
	CShaderTechniquePtr tech = g_Renderer.GetShaderManager().LoadEffect(str_bloom,
			g_Renderer.GetSystemShaderDefines(), defines2);
	
	tech->BeginPass();
	CShaderProgramPtr shader = tech->GetShader();
	shader->BindTexture(str_renderedTex, inOutTex);
	shader->Uniform(str_texSize, inWidth, inHeight, 0.0f, 0.0f);
	
	glPushAttrib(GL_VIEWPORT_BIT); 
	glViewport(0, 0, inWidth, inHeight);
	
	glBegin(GL_QUADS);
	    glColor4f(1.f, 1.f, 1.f, 1.f);
	    glTexCoord2f(1.0, 1.0);	glVertex2f(1,1);
	    glTexCoord2f(0.0, 1.0);	glVertex2f(-1,1);
	    glTexCoord2f(0.0, 0.0);	glVertex2f(-1,-1);
	    glTexCoord2f(1.0, 0.0);	glVertex2f(1,-1);
	glEnd();
	
	glPopAttrib(); 
	tech->EndPass();
	
	// Set result texture as our render target.
	pglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_BloomFbo);
	pglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, inOutTex, 0);
	
	// Get bloom shader, for a vertical Gaussian blur pass.
	CShaderDefines defines3;
	defines3.Add(str_BLOOM_PASS_V, str_1);
	tech = g_Renderer.GetShaderManager().LoadEffect(str_bloom,
			g_Renderer.GetSystemShaderDefines(), defines3);
	
	tech->BeginPass();
	shader = tech->GetShader();
	
	// Our input texture to the shader is the output of the horizontal pass.
	shader->BindTexture(str_renderedTex, tempTex);
	shader->Uniform(str_texSize, inWidth, inHeight, 0.0f, 0.0f);
	
	glPushAttrib(GL_VIEWPORT_BIT); 
	glViewport(0, 0, inWidth, inHeight);
	
	glBegin(GL_QUADS);
	    glColor4f(1.f, 1.f, 1.f, 1.f);
	    glTexCoord2f(1.0, 1.0);	glVertex2f(1,1);
	    glTexCoord2f(0.0, 1.0);	glVertex2f(-1,1);
	    glTexCoord2f(0.0, 0.0);	glVertex2f(-1,-1);
	    glTexCoord2f(1.0, 0.0);	glVertex2f(1,-1);
	glEnd();
	
	glPopAttrib(); 
	tech->EndPass();
}
Ejemplo n.º 29
0
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
{
    // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
    ImGuiIO& io = ImGui::GetIO();
    int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
    int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
    if (fb_width == 0 || fb_height == 0)
        return;
    draw_data->ScaleClipRects(io.DisplayFramebufferScale);

    // We are using the OpenGL fixed pipeline to make the example code simpler to read!
    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
    GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnable(GL_TEXTURE_2D);
    //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context

    // Setup viewport, orthographic projection matrix
    glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    // Render command lists
    #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
        const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();
        glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos)));
        glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv)));
        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col)));

        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
                glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
            }
            idx_buffer += pcmd->ElemCount;
        }
    }
    #undef OFFSETOF

    // Restore modified state
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
}
Ejemplo n.º 30
0
// Displays text at a 2d screen coord. 0,0 is top left corner, add TEXT_DEPTH per Y to go down a line
//
// Note new param 'bResizeStringIfNecessary', this is so that if a string goes off the left hand edge of the window
//	it will now (instead of just not printing the entire string like OpenGL would normally do) move the print pos up
//	a char each time until it fits. It may take more time to do so only set the bool true if really needed.
//
// return value is a convenient xpos for next xpos along after this strlen...
//
int Text_DisplayFlat(LPCSTR psString, int x, int y, byte r, byte g, byte b, bool bResizeStringIfNecessary /* = false */)
{
	int iRetVal = x;

	if (!gbTextInhibit)	// this will also mean the non-existant cursor isn't moved on by the retval, but that shouldn't matter under this circumstance
	{
		// it appears I have to do this in MD3View or paint messages keep getting back here even after SysOnDestroy()...
		//
		if (!mdview.done)	
		{
			int iStrlen = strlen(psString);		
			GLboolean bRasterValid;

			Text_EnsureCreated();

			// (source indenting only to help with gl stack status)
 
			if (iStrlen)
			{
				glPushAttrib(GL_LIGHTING_BIT | GL_LIST_BIT | GL_TRANSFORM_BIT | GL_ENABLE_BIT);
				{				
					glMatrixMode(GL_PROJECTION);
					glPushMatrix();
					{
						glLoadIdentity();

						gluOrtho2D(0.0,(GLfloat) g_iScreenWidth, 0.0, (GLfloat) g_iScreenHeight);	
						glMatrixMode(GL_MODELVIEW);
						glPushMatrix();
						{
							glLoadIdentity();
							
							glDisable(GL_TEXTURE_2D);
							glDisable(GL_LIGHTING);

							glColor3ub(r,g,b);		
					//		glRasterPos2i(x,y);	// from bottom left

							// pre-dec to counter pre-inc coming up...
							//
							x-=TEXT_WIDTH;
							iStrlen+=1;
							psString--;

							do
							{
								x+=TEXT_WIDTH;
								iStrlen-=1;
								psString++;
								//
								glRasterPos2i(x,(g_iScreenHeight-y)-TEXT_DEPTH);				
								glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID,&bRasterValid);
							}
							while ( bResizeStringIfNecessary && !bRasterValid && iStrlen);
							
							if (iStrlen)	// because it may have all been clipped off the left
							{			
								glListBase(gFontOffset);
								glCallLists(iStrlen,GL_UNSIGNED_BYTE,(GLubyte *) psString);
								iRetVal += iStrlen*TEXT_WIDTH;
							}		
						}
						glPopMatrix();	// GL_MODELVIEW				
					}
					glMatrixMode(GL_PROJECTION);
					glPopMatrix();
					//
				}
				glPopAttrib();	
			}
		}
	}

	return iRetVal;
}