Exemplo n.º 1
0
int main(int argc, char *argv[]) try
{

	physics_driftmax = 0.0025f;

	GLWin glwin("point cloud push interaction");
	RSCam dcam;
	dcam.Init((argc == 2) ? argv[1] : NULL);
	Image<unsigned short> dimage(dcam.dcamera());

	glwin.ViewAngle = dcam.fov().y;
	float viewdist = 2.0f;
	float yaw = 120;
	int mousexold = 0;
	Mesh   mesh;

	bool   pause = false;
	bool   debuglines=false;
	int    center = 0;
	bool   chains = true;
	bool   usehull = false;
	std::vector<RigidBody*> rigidbodies;
	std::vector < std::pair<RigidBody*, RigidBody*>> links;
	for (float x = -0.2f; x < 0.2f; x+= 0.07f)  
		for(float z: {0.350f})
			for (float y = -0.2f; y <= 0.2f; y += 0.07f)
	{
				rigidbodies.push_back(new RigidBody({ AsShape(WingMeshDual(WingMeshCube(0.025f),0.028f)) }, { x,y,z }));
				//rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(0.025f)                       ) }, { x,y,z }));
				links.push_back({(y > -0.2f)?rigidbodies[rigidbodies.size() - 2]:NULL , rigidbodies.back()});
	}

	//rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(0.05f)) }, { 0,0,0.50f }));

	auto seesaw = new RigidBody({ AsShape(WingMeshBox({ 0.20f, 0.015f,  0.05f })) }, { 0,0,0.45f });
	rigidbodies.push_back(seesaw);

	glwin.keyboardfunc = [&](unsigned char key, int x, int y)->void
	{
		switch (std::tolower(key))
		{
		case 'q': case 27:  exit(0); break;   // 27 is ESC
		case ' ': pause = !pause; break;
		case 'c': chains = !chains; break;
		case 'd': debuglines = !debuglines; break;
		case 'h': usehull = !usehull; break;
		case 'r': for (auto &rb : rigidbodies) { rb->angular_momentum = rb->linear_momentum = float3(0.0f);rb->pose() = { rb->position_start,rb->orientation_start }; }  break;
		default:  std::cout << "unassigned key (" << (int)key << "): '" << key << "'\n";   break;
		}
	};

	if (dcam.dev->supports_option(rs::option::r200_lr_auto_exposure_enabled))
		dcam.dev->set_option(rs::option::r200_lr_auto_exposure_enabled, 1);

	while (glwin.WindowUp())
	{
		if (glwin.MouseState)
		{
			yaw += glwin.mousepos.x - mousexold;
		}
		mousexold = glwin.mousepos.x;
		viewdist *= powf(1.1f, (float)glwin.mousewheel);

		if (!pause)
			dimage = dcam.GetDepth();

		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glViewport(0, 0, glwin.res.x, glwin.res.y);
		glClearColor(0.1f, 0.1f, 0.15f, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		gluPerspective(glwin.ViewAngle, (double)glwin.aspect_ratio(), 0.01f, 50.0f);

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		gluLookAt(0, 0, viewdist, 0, 0, 0, 0, -1, 0);
		glEnable(GL_DEPTH_TEST);

		glTranslatef(0, 0, 0.35f);
		glRotatef(yaw, 0, 1, 0);
		glTranslatef(0, 0, -0.35f);

		std::vector<float3> pts;
		std::vector<float3> outliers;
		std::vector<float3> vpts;
		glDisable(GL_BLEND);

		float2 wrange = { 0.20f,0.60f };


		auto dp_image_c = Transform(dimage, [](unsigned short s) {return byte3((unsigned char)clamp(255 - s / 4, 0, 255)); });
		drawimage(dp_image_c, { 0.78f,0.22f }, { 0.2f,-0.2f }, 3);

		float depth_scale = (dcam.dev) ? dcam.dev->get_depth_scale() : 0.001f;  // to put into meters    // if file assume file is mm


		for (auto p : rect_iteration(dimage.dim())) // p is int2 from 0,0 to w,h of dcam
		{
			float d = dimage.pixel(p) * depth_scale;  // d is in meters, whereas depth[i] is in camera units  mm for R200, .125mm for SR300 ivycam
			if (p.x<5 || p.x> dimage.dim().x - 5 || p.y<5 || p.y>dimage.dim().y - 5) continue;  // crop, seems to be lots of noise at the edges
			if (d > 1.0f)  // just too far
				continue;  
			float3 v = dimage.cam.deprojectz(asfloat2(p), d);
			if (d>wrange.x && d < wrange.y) 
				pts.push_back(v);
			else
				outliers.push_back(v);
		}

		vpts = ObtainVoxelPointCloud(pts, 0.0082f, 8);


		std::vector<std::pair<float3, float3>> lines;
		std::vector<std::pair<float3, float3>> glines;

		if (1)// && pts.size())
		{
			std::vector<LimitLinear>  linears;
			std::vector<LimitAngular> angulars;
			physics_gravity = { 0,  (float) chains,0 };  // ugg y is down

			if(!usehull) for(auto rb:rigidbodies) 
			{
				if (!rb->shapes[0].planes.size())
					rb->shapes[0].planes = Planes(rb->shapes[0].verts, rb->shapes[0].tris);
				auto planes = Transform(rb->shapes[0].planes, [&](float4 p) { return rb->pose().TransformPlane(p);});
				rb->gravscale = (float)chains;
				float separation = FLT_MAX;
				float3 pushpoint = float3(0, 0, 0);  //
				float4 pushplane;
				for (auto p : vpts)
				{
						auto plane = mostabove(planes, p);
						float sep;
						if ((sep = dot(plane, float4(p, 1))) < separation)
						{
							pushpoint = p;
							pushplane = plane;
							separation = sep;
						}
				}
				if (separation > 0.1f)
					continue;
				float3 closestpoint = ProjectOntoPlane(pushplane, pushpoint);
				pushplane = float4({ -pushplane.xyz(), -dot(-pushplane.xyz(),pushpoint) });
				linears.push_back(ConstrainAlongDirection(NULL, pushpoint, rb, rb->pose().inverse()*closestpoint, pushplane.xyz(), 0, 100.0f)); //  FLT_MAX));
				lines.push_back({ closestpoint,pushpoint });
				auto cp=Separated(rb->shapes[0].verts, rb->position, rb->orientation, { pushpoint }, { 0,0,0 }, { 0,0,0,1 }, 1);
				glines.push_back({ cp.p0w, cp.p1w });
			}
			Append(linears, ConstrainPositionNailed(NULL, seesaw->position_start, seesaw, { 0, 0, 0 }));
			Append(angulars, ConstrainAngularRange(NULL, seesaw, { 0, 0, 0, 1 }, { 0, 0,-20 }, { 0, 0,20 }));

			if (chains) for (auto link : links)
				Append(linears, ConstrainPositionNailed(link.first,link.first? float3(0, 0.035f, 0) : link.second->position_start-float3(0, -0.035f, 0) , link.second, { 0,-0.035f,0 }));
			if(!pause)
				
				if(usehull && vpts.size()>5) 
					PhysicsUpdate(rigidbodies, linears, angulars, { &vpts });
				else 
					PhysicsUpdate(rigidbodies, linears, angulars, std::vector<std::vector<float3>*>());
		}


		glColor3f(1, 1, 1);
		glwirefrustumz(dcam.deprojectextents(), { 0.1f,1.0f });  // draw the camera frustum volume

		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glPointSize(1);
		glBegin(GL_POINTS);
		glColor3f(0, 1, 0.5f);
		for (auto p : pts)
			glVertex3fv(p);
		glColor3f(1, 0.15f, 0.15f);
		for (auto p : outliers)
			glVertex3fv(p);
		glEnd();

		glPointSize(3);
		glBegin(GL_POINTS);
		glColor3f(1, 1, 1);
		for (auto p : vpts)  // was: spts
			glVertex3fv(p);
		glEnd();

		glPopAttrib();

		if (debuglines)
		{
			glBegin(GL_LINES);
			glColor3f(0, 1, 1);
			if (0)for (auto line : lines)
				glVertex3fv(line.first), glVertex3fv(line.second);
			glColor3f(1, 1, 0);
			for (auto line : glines)
				glVertex3fv(line.first), glVertex3fv(line.second);
			glEnd();
		}
		if (usehull && vpts.size() > 5)
		{
			auto tris = calchull(vpts, 0);
			glBegin(GL_LINES);
			glColor3f(1, 1, 1);
			for (auto t : tris) for( int i : {0,1,1,2,2,0})
				glVertex3fv(vpts[t[i]]);
			glEnd();

		}
		if (chains)
		{
			glBegin(GL_LINES);
			glColor3f(1, 0, 1);
			for (auto link : links)
			{
				if(link.first) 
					glVertex3fv(link.first->pose()* float3(0, 0, 0)), glVertex3fv(link.first->pose()* float3(0, 0.035f, 0));
				glVertex3fv(link.second->pose()* float3(0, 0, 0)) , glVertex3fv(link.second->pose()* float3(0, -0.035f, 0));
			}
			glEnd();
		}
		glPushAttrib(GL_ALL_ATTRIB_BITS);
		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

		// Restore state
		glPopMatrix();  //should be currently in modelview mode
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glPopAttrib();
		glMatrixMode(GL_MODELVIEW);

		glwin.PrintString({ 0,0 }, "esc to quit.");
		glwin.PrintString({ 0,1 }, "[h] collision %s  ",(usehull)?"hull":"points");
		glwin.SwapBuffers();

	}
	return 0;
}
catch (const char *c)
{
	MessageBox(GetActiveWindow(), c, "FAIL", 0);
}
catch (std::exception e)
{
	MessageBox(GetActiveWindow(), e.what(), "FAIL", 0);
}
Exemplo n.º 2
0
PyObject* draw_path_fill( PyObject* self, PyObject* args )
{
    PyObject* pobj;
    PyObject* plist = NULL;
    
    PyObject* cacheobj;
    int displaylist;
    
    int i;
    int size;
    PyObject* item;
    static GLUtesselator* tess = NULL;
    static double* v = NULL;
    static int alloc = 0;
    int used = 0;
    
    int cset = 0;    // is there a current point?
    double sx, sy;   // start of subpath
    double cx, cy;   // current point

    double c[8];
    int j, k;
    double *xy;
    static double** blocks = NULL;
    static int block_alloc = 0;
    int block_used = 0;

    if ( !PyArg_ParseTuple( args, "O", &pobj ) )
	return NULL;

    delete_invalid_lists( pobj );
    
    cacheobj = PyObject_GetAttrString( pobj, "_fill_list" );
    if ( cacheobj && PyInt_Check(cacheobj) )
    {
	displaylist = PyInt_AsLong( cacheobj );
	glCallList( displaylist );
    }
    else
    {
	PyErr_Clear();  // don't care if attribute was not found
	
	// generate and store triangulation
	
	plist = PyObject_GetAttrString( pobj, "raw" );
	if ( plist == NULL || !PyList_Check( plist ) )
	{
	    Py_XDECREF( plist );
	    PyErr_SetString( DrawError, "bad path object" );
	    return NULL;
	}

	displaylist = glGenLists( 1 );
	glNewList( displaylist, GL_COMPILE_AND_EXECUTE );
    
	if ( tess == NULL )
	    tess = gluNewTess();
	
#ifdef SHOW_TRIANGULATION
	glPushAttrib( GL_LIGHTING_BIT );
	glShadeModel( GL_FLAT );
	gluTessCallback( tess, GLU_TESS_VERTEX, random_color_vertex );
#else
	gluTessCallback( tess, GLU_TESS_VERTEX, glVertex2dv );
#endif
	
	gluTessCallback( tess, GLU_TESS_BEGIN, glBegin );
	gluTessCallback( tess, GLU_TESS_END, glEnd );
	gluTessCallback( tess, GLU_TESS_COMBINE, combine_cb );
	gluTessProperty( tess, GLU_TESS_BOUNDARY_ONLY, GL_FALSE );
	
	size = PyList_Size( plist );
	if ( size > alloc )
	{
	    alloc = size + VERTEX_ALLOC_CHUNK;
	    v = realloc( v, alloc * 3 * sizeof( double ) );
	}
	memset( v, 0, alloc * 3 * sizeof( double ) );
	
#define VERTEX(x,y)  {v[used*3+0]=(x);v[used*3+1]=(y);gluTessVertex(tess,v+used*3,v+used*3);++used;}
	
	gluTessBeginPolygon( tess, NULL );
	for ( i = 0; i < size; ++i )
	{
	    item = PyList_GetItem( plist, i );
	    
	    switch( PyInt_AsLong( PyList_GetItem( item, 0 ) ) )
	    {
	      case S_CLOSE:
		VERTEX( sx, sy );
		gluTessEndContour( tess );
		cset = 0;
		break;
		
	      case S_MOVE:
		if ( cset ) gluTessEndContour( tess );
		gluTessBeginContour( tess );
		sx = cx = PyFloat_AsDouble( PyList_GetItem( item, 1 ) );
		sy = cy = PyFloat_AsDouble( PyList_GetItem( item, 2 ) );
		VERTEX( cx, cy );
		cset = 1;
		break;
		
	      case S_LINE:
		cx = PyFloat_AsDouble( PyList_GetItem( item, 1 ) );
		cy = PyFloat_AsDouble( PyList_GetItem( item, 2 ) );
		VERTEX( cx, cy );
		break;
		
	      case S_CURVE:
		if ( block_used + 1 > block_alloc )
		{
		    block_alloc += BLOCK_ALLOC_CHUNK;
		    blocks = realloc( blocks, block_alloc * sizeof( double* ) );
		}
		
		c[0] = cx;
		c[1] = cy;
		for ( j = 0; j < 6; ++j )
		    c[j+2] = PyFloat_AsDouble( PyList_GetItem( item, j+1 ) );
		xy = bezier_points( &k, 4, c, 0.0001, 0 );
		cx = c[6];
		cy = c[7];
		
		blocks[block_used] = malloc( (k-1) * 3 * sizeof( double ) );
		for ( j = 1; j < k; ++j )
		{
		    blocks[block_used][(j-1)*3+0] = xy[j*2];
		    blocks[block_used][(j-1)*3+1] = xy[j*2+1];
		    blocks[block_used][(j-1)*3+2] = 0.0;
		}
		
		for ( j = 0; j < k-1; ++j )
		    gluTessVertex( tess, blocks[block_used] + j*3, blocks[block_used] + j*3 );
		
		++block_used;
		break;
		
	      case S_QCURVE:
		if ( block_used + 1 > block_alloc )
		{
		    block_alloc += BLOCK_ALLOC_CHUNK;
		    blocks = realloc( blocks, block_alloc * sizeof( double* ) );
		}

		c[0] = cx;
		c[1] = cy;
		for ( j = 0; j < 4; ++j )
		    c[j+2] = PyFloat_AsDouble( PyList_GetItem( item, j+1 ) );
		xy = bezier_points( &k, 3, c, 0.0001, 0 );
		cx = c[4];
		cy = c[5];

		blocks[block_used] = malloc( (k-1) * 3 * sizeof( double ) );
		for ( j = 1; j < k; ++j )
		{
		    blocks[block_used][(j-1)*3+0] = xy[j*2];
		    blocks[block_used][(j-1)*3+1] = xy[j*2+1];
		    blocks[block_used][(j-1)*3+2] = 0.0;
		}
	    
		for ( j = 0; j < k-1; ++j )
		    gluTessVertex( tess, blocks[block_used] + j*3, blocks[block_used] + j*3 );

		++block_used;
		break;
	    }
	}

	if ( cset )
	    gluTessEndContour( tess );
	gluTessEndPolygon( tess );

	for ( i = 0; i < block_used; ++i )
	    free( blocks[i] );
	
#ifdef SHOW_TRIANGULATION
	glPopAttrib();
#endif

	glEndList();

	PyObject_SetAttrString( pobj, "_fill_list", PyInt_FromLong( displaylist ) );
    }

    Py_XDECREF( cacheobj );
    Py_XDECREF( plist );

    Py_INCREF( Py_None );
    return Py_None;
}
Exemplo n.º 3
0
void ccSSAOFilter::shade(GLuint texDepth, GLuint texColor, float zoom)
{
    if (!fbo || !shader)
    {
        //ccConsole::Warning("[ccSSAOFilter::shade] Internal error: structures not initialized!");
        return;
    }

    glPushAttrib(GL_ALL_ATTRIB_BITS);

    //we must use corner-based screen coordinates
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,0.0,1.0);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    fbo->start();
    fbo->setDrawBuffers1();

    shader->start();
    shader->setUniform1i("s2_Z",0);
    shader->setUniform1i("s2_R",1);
    shader->setUniform1i("s2_C",2);
    shader->setUniform1f("R",R);
    shader->setUniform1f("F",F);
    shader->setUniform1f("Kz",Kz);
    //shader->setUniform1i("N",N);
    shader->setUniform1i("B_REF",texReflect==0 ? 0 : 1);
    shader->setTabUniform3fv("P",SSAO_MAX_N,ssao_neighbours);

    glActiveTexture(GL_TEXTURE2);
    TEX_2D_ON;
    glBindTexture(GL_TEXTURE_2D,texColor);

    if (glIsTexture(texReflect))
    {
        glActiveTexture(GL_TEXTURE1);
        TEX_2D_ON;
        glBindTexture(GL_TEXTURE_2D,texReflect);
    }
    glActiveTexture(GL_TEXTURE0);
    //glBindTexture(GL_TEXTURE_2D,texDepth);

    ccFBOUtils::DisplayTexture2DCorner(texDepth,w,h);

    //glActiveTexture(GL_TEXTURE0);
    //glBindTexture(GL_TEXTURE_2D,0);

    if (glIsTexture(texReflect))
    {
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D,0);
        TEX_2D_OFF;
    }

    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D,0);
    TEX_2D_OFF;

    shader->stop();
    fbo->stop();

    if (bilateralFilter)
    {
        bilateralFilter->setParameters(bilateralGSize,bilateralGSigma,bilateralGSigmaZ);
        bilateralFilter->shade(texDepth,fbo->getColorTexture(0),zoom);
    }

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

    glPopAttrib();
}
Exemplo n.º 4
0
void
BufferCanvas::Commit(Canvas &other)
{
  assert(IsDefined());
  assert(active);
  assert(GetWidth() == other.GetWidth());
  assert(GetHeight() == other.GetHeight());

  if (frame_buffer != nullptr) {
    assert(OpenGL::translate.x == 0);
    assert(OpenGL::translate.y == 0);

    frame_buffer->Unbind();

    /* restore the old viewport */

    assert(OpenGL::translate == PixelPoint(0, 0));

#ifdef HAVE_GLES
    /* there's no glPopAttrib() on GL/ES; emulate it */
    glViewport(old_viewport[0], old_viewport[1],
               old_viewport[2], old_viewport[3]);
#else
    glPopAttrib();
#endif

#ifdef USE_GLSL
    OpenGL::projection_matrix = old_projection_matrix;
    OpenGL::UpdateShaderProjectionMatrix();
#else
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
#endif

    OpenGL::translate = old_translate;
    OpenGL::viewport_size = old_size;

#ifdef USE_GLSL
    glVertexAttrib4f(OpenGL::Attribute::TRANSLATE,
                     OpenGL::translate.x, OpenGL::translate.y, 0, 0);
#endif

#ifdef SOFTWARE_ROTATE_DISPLAY
    OpenGL::display_orientation = old_orientation;
#endif

    /* copy frame buffer to screen */
    CopyTo(other);
  } else {
    assert(offset == other.offset);

    /* copy screen to texture */
    CopyToTexture(*texture, GetRect());
  }

#ifndef NDEBUG
  active = false;
#endif
}
Exemplo n.º 5
0
void PlotGl::paintGLThread()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	bool bEnabled = m_bEnabled.load();
	if(!bEnabled) return;

	glMatrixMode(GL_MODELVIEW);
	t_real_gl glmat[16];
	{
		std::lock_guard<QMutex> _lck(m_mutex);
		tl::to_gl_array(m_matView, glmat);
	}
	glLoadMatrixd(glmat);


	glPushMatrix();
		glDisable(GL_LIGHTING);
		glDisable(GL_BLEND);
		glDisable(GL_TEXTURE_2D);
		glLineWidth(2.);
		glColor3d(0., 0., 0.);

		const t_real_gl dAxisScale = 1.8;
		glBegin(GL_LINES);
			glVertex3d(m_dXMin*dAxisScale, 0., 0.);
			glVertex3d(m_dXMax*dAxisScale, 0., 0.);
			glVertex3d(0., m_dYMin*dAxisScale, 0.);
			glVertex3d(0., m_dYMax*dAxisScale, 0.);
			glVertex3d(0., 0., m_dZMin*dAxisScale);
			glVertex3d(0., 0., m_dZMax*dAxisScale);
		glEnd();
	glPopMatrix();

	glEnable(GL_BLEND);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glDisable(GL_TEXTURE_2D);

	std::unique_lock<QMutex> _lck(m_mutex);
	std::size_t iPltIdx = 0;
	for(const PlotObjGl& obj : m_vecObjs)
	{
		int iLOD = 0;

		bool bColorSet = 0;
		if(obj.bSelected)
		{
			SetColor(0.25, 0.25, 0.25, 0.9);
			bColorSet = 1;
		}

		glPushMatrix();
		if(obj.plttype == PLOT_SPHERE)
		{
			glTranslated(obj.vecParams[0], obj.vecParams[1], obj.vecParams[2]);
			glScaled(obj.vecParams[3], obj.vecParams[3], obj.vecParams[3]);
		}
		else if(obj.plttype == PLOT_ELLIPSOID)
		{
			glTranslated(obj.vecParams[3], obj.vecParams[4], obj.vecParams[5]);

			t_real_gl dMatRot[] = {obj.vecParams[6], obj.vecParams[7], obj.vecParams[8], 0.,
				obj.vecParams[9], obj.vecParams[10], obj.vecParams[11], 0.,
				obj.vecParams[12], obj.vecParams[13], obj.vecParams[14], 0.,
				0., 0., 0., 1. };
			glMultMatrixd(dMatRot);
			glScaled(obj.vecParams[0], obj.vecParams[1], obj.vecParams[2]);
		}
		else
			tl::log_warn("Unknown plot object.");

		if(obj.bUseLOD)
		{
			t_real_gl dLenDist = tl::gl_proj_sphere_size(/*dRadius*/1.);
			//std::cout << "proj sphere size: " << dLenDist << std::endl;
			iLOD = dLenDist * 50.;
			if(iLOD >= int(sizeof(m_iLstSphere)/sizeof(*m_iLstSphere)))
				iLOD = sizeof(m_iLstSphere)/sizeof(*m_iLstSphere)-1;
			if(iLOD < 0) iLOD = 0;
			iLOD = sizeof(m_iLstSphere)/sizeof(*m_iLstSphere) - iLOD - 1;
			//std::cout << "dist: " << dLenDist << ", lod: " << iLOD << std::endl;
		}

		if(!bColorSet)
		{
			if(obj.vecColor.size())
				SetColor(obj.vecColor[0], obj.vecColor[1], obj.vecColor[2], obj.vecColor[3]);
			else
				SetColor(iPltIdx);
		}
		glCallList(m_iLstSphere[iLOD]);

		if(obj.bSelected && obj.strLabel.length() && m_pFont && m_pFont->IsOk())
		{
			glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_LIGHTING_BIT);
			m_pFont->BindTexture();
			glColor4d(0., 0., 0., 1.);
			m_pFont->DrawText(0., 0., 0., obj.strLabel);
			glPopAttrib();
		}

		glPopMatrix();

		++iPltIdx;
	}
	_lck.unlock();

	glPushMatrix();
		if(m_pFont && m_pFont->IsOk())
		{
			m_pFont->BindTexture();

			glColor4d(0., 0., 1., 1.);
			m_pFont->DrawText(m_dXMax*dAxisScale, 0., 0., m_strLabels[0].toStdString());
			m_pFont->DrawText(0., m_dYMax*dAxisScale , 0., m_strLabels[1].toStdString());
			m_pFont->DrawText(0., 0., m_dZMax*dAxisScale , m_strLabels[2].toStdString());

			glColor4d(0., 0., 0., 1.);
			m_pFont->DrawText(m_dXMin, 0., 0., tl::var_to_str(m_dXMin+m_dXMinMaxOffs, m_iPrec));
			m_pFont->DrawText(m_dXMax, 0., 0., tl::var_to_str(m_dXMax+m_dXMinMaxOffs, m_iPrec));
			m_pFont->DrawText(0., m_dYMin, 0., tl::var_to_str(m_dYMin+m_dYMinMaxOffs, m_iPrec));
			m_pFont->DrawText(0., m_dYMax, 0., tl::var_to_str(m_dYMax+m_dYMinMaxOffs, m_iPrec));
			m_pFont->DrawText(0., 0., m_dZMin, tl::var_to_str(m_dZMin+m_dZMinMaxOffs, m_iPrec));
			m_pFont->DrawText(0., 0., m_dZMax, tl::var_to_str(m_dZMax+m_dZMinMaxOffs, m_iPrec));
		}
	glPopMatrix();

	swapBuffers();
}
Exemplo n.º 6
0
void cal_render_bones(actor *act)
{
	float lines[1024][2][3];
	float points[1024][3];
	int nrLines;
	int nrPoints;
	int currLine;
	int currPoint;
	struct CalSkeleton *skel;

	skel=CalModel_GetSkeleton(act->calmodel);
	nrLines = CalSkeleton_GetBoneLines(skel,&lines[0][0][0]);

	glLineWidth(2.0f);
	glColor3f(1.0f, 1.0f, 1.0f);

	glLineStipple(1, 0x3030);
	glEnable(GL_LINE_STIPPLE);
	glBegin(GL_LINES);

	for(currLine = 0; currLine < nrLines; currLine++) {
    		glVertex3f(lines[currLine][0][0], lines[currLine][0][1], lines[currLine][0][2]);
    		glVertex3f(lines[currLine][1][0], lines[currLine][1][1], lines[currLine][1][2]);
	}

	glEnd();
	glDisable(GL_LINE_STIPPLE);

  	// draw the bone points
  	nrPoints = CalSkeleton_GetBonePoints(skel,&points[0][0]);

	glPointSize(4.0f);
	glColor3f(0.0f, 1.0f, 1.0f);
	glBegin(GL_POINTS);
	for(currPoint = 0; currPoint < nrPoints; currPoint++) {
		glVertex3f(points[currPoint][0], points[currPoint][1], points[currPoint][2]);
	}
	glEnd();

#ifdef DEBUG
	// draw the bones orientation
	if (render_bones_orientation) {
		float shift[3], pos[3];
		
		glLineWidth(3.0f);
		glBegin(GL_LINES);
		for (currPoint = nrPoints; currPoint--;) {
			shift[0] = 0.1; shift[1] = 0.0; shift[2] = 0.0;
			cal_get_actor_bone_local_position(act, currPoint, shift, pos);
			glColor3f(1.0, 0.0, 0.0);
			glVertex3f(points[currPoint][0], points[currPoint][1], points[currPoint][2]);
			glVertex3fv(pos);
			
			shift[0] = 0.0; shift[1] = 0.1; shift[2] = 0.0;
			cal_get_actor_bone_local_position(act, currPoint, shift, pos);
			glColor3f(0.0, 1.0, 0.0);
			glVertex3f(points[currPoint][0], points[currPoint][1], points[currPoint][2]);
			glVertex3fv(pos);
			
			shift[0] = 0.0; shift[1] = 0.0; shift[2] = 0.1;
			cal_get_actor_bone_local_position(act, currPoint, shift, pos);
			glColor3f(0.0, 0.0, 1.0);
			glVertex3f(points[currPoint][0], points[currPoint][1], points[currPoint][2]);
			glVertex3fv(pos);
		}
		glEnd();
	}

	// draw bones id
	if (render_bones_id) {
		GLdouble model[16], proj[16];
		GLint view[4];
		GLdouble px,py,pz;
		unsigned char buf[16];
		float font_size_x = SMALL_INGAME_FONT_X_LEN/ALT_INGAME_FONT_X_LEN;
		float font_size_y = SMALL_INGAME_FONT_Y_LEN/ALT_INGAME_FONT_X_LEN;

		glGetDoublev(GL_MODELVIEW_MATRIX, model);
		glGetDoublev(GL_PROJECTION_MATRIX, proj);
		glGetIntegerv(GL_VIEWPORT, view);
		
		glPushMatrix();
		glLoadIdentity();
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		
		glOrtho(view[0],view[2]+view[0],view[1],view[3]+view[1],0.0f,-1.0f);
		
		glPushAttrib(GL_ENABLE_BIT);
		
		glEnable(GL_TEXTURE_2D);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
		
		glColor4f(1.0, 0.0, 1.0, 1.0);
		
		for (currPoint = nrPoints; currPoint--;) {
			struct CalBone *bone;
			bone = CalSkeleton_GetBone(skel, currPoint);
			
			sprintf((char*)buf, "%d", currPoint);
			gluProject(points[currPoint][0], points[currPoint][1], points[currPoint][2], model, proj, view, &px, &py, &pz);
			draw_ortho_ingame_string(px, py, pz, buf, 1, font_size_x, font_size_y);
		}
		
		glPopAttrib();
		
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
	}
#endif // DEBUG

	glLineWidth(1.0f);

#ifdef OPENGL_TRACE
CHECK_GL_ERRORS();
#endif //OPENGL_TRACE

}
Exemplo n.º 7
0
void CAdvWater::UpdateWater(CGame* game)
{
	if (!mapInfo->water.forceRendering && !readMap->HasVisibleWater())
		return;

	glPushAttrib(GL_FOG_BIT);
	glPushAttrib(GL_COLOR_BUFFER_BIT);
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);

	bumpFBO.Bind();
	glViewport(0, 0, 128, 128);

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

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 1, 0, 1, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glColor3f(0.2f, 0.2f, 0.2f);

	CVertexArray* va = GetVertexArray();
	va->Initialize();
	va->EnlargeArrays(12, 0, VA_SIZE_T);

	glBindTexture(GL_TEXTURE_2D, rawBumpTexture[0]);

	va->AddVertexQT(ZeroVector, 0, 0 + gs->frameNum*0.0046f);
	va->AddVertexQT(  UpVector, 0, 2 + gs->frameNum*0.0046f);
	va->AddVertexQT(  XYVector, 2, 2 + gs->frameNum*0.0046f);
	va->AddVertexQT( RgtVector, 2, 0 + gs->frameNum*0.0046f);

	va->AddVertexQT(ZeroVector, 0, 0 + gs->frameNum*0.0026f);
	va->AddVertexQT(  UpVector, 0, 4 + gs->frameNum*0.0026f);
	va->AddVertexQT(  XYVector, 2, 4 + gs->frameNum*0.0026f);
	va->AddVertexQT( RgtVector, 2, 0 + gs->frameNum*0.0026f);

	va->AddVertexQT(ZeroVector, 0, 0 + gs->frameNum*0.0012f);
	va->AddVertexQT(  UpVector, 0, 8 + gs->frameNum*0.0012f);
	va->AddVertexQT(  XYVector, 2, 8 + gs->frameNum*0.0012f);
	va->AddVertexQT( RgtVector, 2, 0 + gs->frameNum*0.0012f);

	va->DrawArrayT(GL_QUADS);

	va->Initialize();
	glBindTexture(GL_TEXTURE_2D, rawBumpTexture[1]);

	va->AddVertexQT(ZeroVector, 0, 0 + gs->frameNum*0.0036f);
	va->AddVertexQT(  UpVector, 0, 1 + gs->frameNum*0.0036f);
	va->AddVertexQT(  XYVector, 1, 1 + gs->frameNum*0.0036f);
	va->AddVertexQT( RgtVector, 1, 0 + gs->frameNum*0.0036f);

	va->DrawArrayT(GL_QUADS);

	va->Initialize();
	glBindTexture(GL_TEXTURE_2D, rawBumpTexture[2]);

	va->AddVertexQT(ZeroVector, 0, 0 + gs->frameNum*0.0082f);
	va->AddVertexQT(  UpVector, 0, 1 + gs->frameNum*0.0082f);
	va->AddVertexQT(  XYVector, 1, 1 + gs->frameNum*0.0082f);
	va->AddVertexQT( RgtVector, 1, 0 + gs->frameNum*0.0082f);

	va->DrawArrayT(GL_QUADS);

	// this fixes a memory leak on ATI cards
	glBindTexture(GL_TEXTURE_2D, 0);

	glColor3f(1, 1, 1);

//	CCamera* realCam = camera;
//	camera = new CCamera(*realCam);
	char realCam[sizeof(CCamera)];
	new (realCam) CCamera(*camera); // anti-crash workaround for multithreading

	camera->forward.y *= -1.0f;
	camera->SetPos().y *= -1.0f;
	camera->Update();

	reflectFBO.Bind();
	glViewport(0, 0, 512, 512);
	glClear(GL_DEPTH_BUFFER_BIT);

	game->SetDrawMode(CGame::gameReflectionDraw);

	sky->Draw();

	glEnable(GL_CLIP_PLANE2);
	double plane[4] = {0, 1, 0, 0};
	glClipPlane(GL_CLIP_PLANE2, plane);
	drawReflection = true;

	readMap->GetGroundDrawer()->Draw(DrawPass::WaterReflection);
	unitDrawer->Draw(true);
	featureDrawer->Draw();
	unitDrawer->DrawCloakedUnits(true);
	featureDrawer->DrawFadeFeatures(true);
	projectileDrawer->Draw(true);
	eventHandler.DrawWorldReflection();

	game->SetDrawMode(CGame::gameNormalDraw);

	drawReflection = false;
	glDisable(GL_CLIP_PLANE2);

	FBO::Unbind();

	glViewport(globalRendering->viewPosX, 0, globalRendering->viewSizeX, globalRendering->viewSizeY);
	glClearColor(mapInfo->atmosphere.fogColor[0], mapInfo->atmosphere.fogColor[1], mapInfo->atmosphere.fogColor[2], 1);

//	delete camera;
//	camera = realCam;
	camera->~CCamera();
	new (camera) CCamera(*(reinterpret_cast<CCamera*>(realCam)));
	reinterpret_cast<CCamera*>(realCam)->~CCamera();

	camera->Update();
	glPopAttrib();
	glPopAttrib();
}
Exemplo n.º 8
0
void ClientOSRenderer::Render() {
  if (view_width_ == 0 || view_height_ == 0)
    return;

  DCHECK(initialized_);

  struct {
    float tu, tv;
    float x, y, z;
  } static vertices[] = {
    {0.0f, 1.0f, -1.0f, -1.0f, 0.0f},
    {1.0f, 1.0f,  1.0f, -1.0f, 0.0f},
    {1.0f, 0.0f,  1.0f,  1.0f, 0.0f},
    {0.0f, 0.0f, -1.0f,  1.0f, 0.0f}
  };

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); VERIFY_NO_ERROR;

  glMatrixMode(GL_MODELVIEW); VERIFY_NO_ERROR;
  glLoadIdentity(); VERIFY_NO_ERROR;

  // Match GL units to screen coordinates.
  glViewport(0, 0, view_width_, view_height_); VERIFY_NO_ERROR;
  glMatrixMode(GL_PROJECTION); VERIFY_NO_ERROR;
  glLoadIdentity(); VERIFY_NO_ERROR;

  // Draw the background gradient.
  glPushAttrib(GL_ALL_ATTRIB_BITS); VERIFY_NO_ERROR;
  // Don't check for errors until glEnd().
  glBegin(GL_QUADS);
  glColor4f(1.0, 0.0, 0.0, 1.0);  // red
  glVertex2f(-1.0, -1.0);
  glVertex2f(1.0, -1.0);
  glColor4f(0.0, 0.0, 1.0, 1.0);  // blue
  glVertex2f(1.0, 1.0);
  glVertex2f(-1.0, 1.0);
  glEnd(); VERIFY_NO_ERROR;
  glPopAttrib(); VERIFY_NO_ERROR;

  // Rotate the view based on the mouse spin.
  if (spin_x_ != 0) {
    glRotatef(-spin_x_, 1.0f, 0.0f, 0.0f); VERIFY_NO_ERROR;
  }
  if (spin_y_ != 0) {
    glRotatef(-spin_y_, 0.0f, 1.0f, 0.0f); VERIFY_NO_ERROR;
  }

  if (transparent_) {
    // Alpha blending style. Texture values have premultiplied alpha.
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); VERIFY_NO_ERROR;

    // Enable alpha blending.
    glEnable(GL_BLEND); VERIFY_NO_ERROR;
  }

  // Enable 2D textures.
  glEnable(GL_TEXTURE_2D); VERIFY_NO_ERROR;

  // Draw the facets with the texture.
  DCHECK_NE(texture_id_, 0U); VERIFY_NO_ERROR;
  glBindTexture(GL_TEXTURE_2D, texture_id_); VERIFY_NO_ERROR;
  glInterleavedArrays(GL_T2F_V3F, 0, vertices); VERIFY_NO_ERROR;
  glDrawArrays(GL_QUADS, 0, 4); VERIFY_NO_ERROR;

  // Disable 2D textures.
  glDisable(GL_TEXTURE_2D); VERIFY_NO_ERROR;

  if (transparent_) {
    // Disable alpha blending.
    glDisable(GL_BLEND); VERIFY_NO_ERROR;
  }

  // Draw a rectangle around the update region.
  if (show_update_rect_ && !update_rect_.IsEmpty()) {
    int left = update_rect_.x;
    int right = update_rect_.x + update_rect_.width;
    int top = update_rect_.y;
    int bottom = update_rect_.y + update_rect_.height;

#if defined(OS_LINUX)
    // Shrink the box so that top & right sides are drawn.
    top += 1;
    right -= 1;
#else
    // Shrink the box so that left & bottom sides are drawn.
    left += 1;
    bottom -= 1;
#endif

    glPushAttrib(GL_ALL_ATTRIB_BITS); VERIFY_NO_ERROR
    glMatrixMode(GL_PROJECTION); VERIFY_NO_ERROR;
    glPushMatrix(); VERIFY_NO_ERROR;
    glLoadIdentity(); VERIFY_NO_ERROR;
    glOrtho(0, view_width_, view_height_, 0, 0, 1); VERIFY_NO_ERROR;

    glLineWidth(1); VERIFY_NO_ERROR;
    glColor3f(1.0f, 0.0f, 0.0f); VERIFY_NO_ERROR;
    // Don't check for errors until glEnd().
    glBegin(GL_LINE_STRIP);
    glVertex2i(left, top);
    glVertex2i(right, top);
    glVertex2i(right, bottom);
    glVertex2i(left, bottom);
    glVertex2i(left, top);
    glEnd(); VERIFY_NO_ERROR;

    glPopMatrix(); VERIFY_NO_ERROR;
    glPopAttrib(); VERIFY_NO_ERROR;
  }
}
Exemplo n.º 9
0
void Viewer::MainLoop()
{
	Uint32 lastTurd = SDL_GetTicks();

	Uint32 t = SDL_GetTicks();
	int numFrames = 0;
	Uint32 lastFpsReadout = SDL_GetTicks();
	g_campos = vector3f(0.0f, 0.0f, m_cmesh->GetBoundingRadius());
	g_camorient = matrix4x4f::Identity();
	matrix4x4f modelRot = matrix4x4f::Identity();
	

	printf("Geom tree build in %dms\n", SDL_GetTicks() - t);

	Render::State::SetZnearZfar(1.0f, 10000.0f);

	for (;;) {
		PollEvents();
		Render::PrepareFrame();

		if (g_keyState[SDLK_LSHIFT] || g_keyState[SDLK_RSHIFT]) {
			if (g_keyState[SDLK_UP]) g_camorient = g_camorient * matrix4x4f::RotateXMatrix(g_frameTime);
			if (g_keyState[SDLK_DOWN]) g_camorient = g_camorient * matrix4x4f::RotateXMatrix(-g_frameTime);
			if (g_keyState[SDLK_LEFT]) g_camorient = g_camorient * matrix4x4f::RotateYMatrix(-g_frameTime);
			if (g_keyState[SDLK_RIGHT]) g_camorient = g_camorient * matrix4x4f::RotateYMatrix(g_frameTime);
			if (g_mouseButton[3]) {
				float rx = 0.01f*g_mouseMotion[1];
				float ry = 0.01f*g_mouseMotion[0];
				g_camorient = g_camorient * matrix4x4f::RotateXMatrix(rx);
				g_camorient = g_camorient * matrix4x4f::RotateYMatrix(ry);
				if (g_mouseButton[1]) {
					g_campos = g_campos - g_camorient * vector3f(0.0f,0.0f,1.0f) * 0.01 *
						m_model->GetDrawClipRadius();
				}
			}
		} else {
			if (g_keyState[SDLK_UP]) modelRot = modelRot * matrix4x4f::RotateXMatrix(g_frameTime);
			if (g_keyState[SDLK_DOWN]) modelRot = modelRot * matrix4x4f::RotateXMatrix(-g_frameTime);
			if (g_keyState[SDLK_LEFT]) modelRot = modelRot * matrix4x4f::RotateYMatrix(-g_frameTime);
			if (g_keyState[SDLK_RIGHT]) modelRot = modelRot * matrix4x4f::RotateYMatrix(g_frameTime);
			if (g_mouseButton[3]) {
				float rx = 0.01f*g_mouseMotion[1];
				float ry = 0.01f*g_mouseMotion[0];
				modelRot = modelRot * matrix4x4f::RotateXMatrix(rx);
				modelRot = modelRot * matrix4x4f::RotateYMatrix(ry);
			}
		}
		if (g_keyState[SDLK_EQUALS]) g_campos = g_campos - g_camorient * vector3f(0.0f,0.0f,1.0f);
		if (g_keyState[SDLK_MINUS]) g_campos = g_campos + g_camorient * vector3f(0.0f,0.0f,1.0f);
		if (g_keyState[SDLK_PAGEUP]) g_campos = g_campos - g_camorient * vector3f(0.0f,0.0f,1.0f);
		if (g_keyState[SDLK_PAGEDOWN]) g_campos = g_campos + g_camorient * vector3f(0.0f,0.0f,1.0f);

//		geom->MoveTo(modelRot, vector3d(0.0,0.0,0.0));

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		float fracH = g_height / (float)g_width;
		glFrustum(-1, 1, -fracH, fracH, 1.0f, 10000.0f);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glClearColor(0,0,0,0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		SetSbreParams();

		int beforeDrawTriStats = LmrModelGetStatsTris();
	
		if (g_renderType == 0) {
			glPushAttrib(GL_ALL_ATTRIB_BITS);
			matrix4x4f m = g_camorient.InverseOf() * matrix4x4f::Translation(-g_campos) * modelRot.InverseOf();
			if (g_doBenchmark) {
				for (int i=0; i<1000; i++) m_model->Render(m, &params);
			} else {
				m_model->Render(m, &params);
			}
			glPopAttrib();
		} else if (g_renderType == 1) {
			glPushMatrix();
			matrix4x4f m = g_camorient.InverseOf() * matrix4x4f::Translation(-g_campos) * modelRot.InverseOf();
			glMultMatrixf(&m[0]);
			render_coll_mesh(m_cmesh);
			glPopMatrix();
		} else {
			matrix4x4f tran = modelRot * g_camorient;//.InverseOf();
			vector3d forward = tran * vector3d(0.0,0.0,-1.0);
			vector3d up = tran * vector3d(0.0,1.0,0.0);
			raytraceCollMesh(modelRot * g_campos, up, forward, m_space);
		}
		Render::State::UseProgram(0);
		Render::UnbindAllBuffers();

		{
			char buf[128];
			Aabb aabb = m_cmesh->GetAabb();
			snprintf(buf, sizeof(buf), "%d triangles, collision mesh size: %.1fx%.1fx%.1f (radius %.1f)",
					(g_renderType == 0 ? 
						LmrModelGetStatsTris() - beforeDrawTriStats :
						m_cmesh->m_numTris),
					aabb.max.x-aabb.min.x,
					aabb.max.y-aabb.min.y,
					aabb.max.z-aabb.min.z,
					aabb.GetBoundingRadius());
			m_trisReadout->SetText(buf);
		}
		
		Render::PostProcess();
		Gui::Draw();
		
		glError();
		Render::SwapBuffers();
		numFrames++;
		g_frameTime = (SDL_GetTicks() - lastTurd) * 0.001f;
		lastTurd = SDL_GetTicks();
	
		if (SDL_GetTicks() - lastFpsReadout > 1000) {
			int numTris = LmrModelGetStatsTris();
			LmrModelClearStatsTris();
			printf("%d fps, %.3f Million tris/sec\n", numFrames, numTris/1000000.0f);
			numFrames = 0;
			lastFpsReadout = SDL_GetTicks();
		}

		//space->Collide(onCollision);
	}
}
Exemplo n.º 10
0
/* virtual */
bool
hwRenderEffect::execute()
{
	MHardwareRenderer *pRenderer = MHardwareRenderer::theRenderer();
	if (!pRenderer)
		return false;

	const MString & backEndStr = pRenderer->backEndString();
	unsigned int width = 0, height = 0;

	MStatus stat = 
		pRenderer->getBufferSize( backEndStr, width, height );
	if (width <= 0 || height <= 0)
		return false;

	unsigned int exposureNum;
	unsigned int totalExposureCount;
	pRenderer->getCurrentExposureNumber( backEndStr, exposureNum );
	pRenderer->getTotalExposureCount( backEndStr, totalExposureCount );

	// Perform some post-rendering. Invert the image.
	bool xxxx = true;
	if ( xxxx && mLocation == MHardwareRenderer::kPostRendering )
	{
		cout<<"Call EXP["<<exposureNum<<"/"<<totalExposureCount
			<<"] hwRenderEffect::execute("<<width<<", "<<height
			<<") -- "<<fName.asChar()<<endl;

		MHardwareRenderer::BufferPixelFormat colFmt;
		stat = pRenderer->getColorBufferPixelFormat( backEndStr, colFmt );
		void *pixels = 0;
		unsigned int data_type = GL_UNSIGNED_BYTE; 
		unsigned int format = GL_RGBA;

		unsigned int totalSize = width*height*4;

		if (totalSize == 0)
			return false;

		if (colFmt == MHardwareRenderer::kRGBA_Fix8)
		{
			data_type = GL_UNSIGNED_BYTE; 
			format = GL_RGBA;
			pixels = new unsigned char[totalSize];
		}
#ifdef _SUPPORT_16_FLOAT_
		else if (MHardwareRenderer::kRGBA_Float16)
		{		
			data_type = GL_HALF_FLOAT; 
			format = GL_RGBA;
			pixels = new half[totalSize];
		}
#endif
		glPushAttrib(GL_ALL_ATTRIB_BITS); 

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

		glPixelZoom( 1.0f, 1.0f );
		glPixelStorei(GL_PACK_ALIGNMENT, 1);
		glReadPixels(0, 0, width, height, format, data_type, pixels);

		unsigned char *pixelPtr = (unsigned char*)pixels;
		if (pixelPtr)
		{
			unsigned int numPixels = width * height;
			for (unsigned int i=0; i < numPixels; i++)
			{
				*pixelPtr = (255 - *pixelPtr);	
				pixelPtr++;
				*pixelPtr = (255 - *pixelPtr);	
				pixelPtr++;			
				*pixelPtr = (255 - *pixelPtr);	
				pixelPtr++;
				*pixelPtr = 255;	
				pixelPtr++;
			}
		}

		glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
		glRasterPos2i( -1, -1 );

		// We only want to clobber RGB. Leave alpha as is.
		glColorMask( 1, 1, 1, 0 );

		// For orthographic views, we need to make sure that depth
		// test is disabled, otherwise the pixels will not draw.
		glDisable(GL_DEPTH_TEST);

		glDrawPixels(width, height, format, data_type, pixels);	

		if (pixels)
		{
			if (colFmt == MHardwareRenderer::kRGBA_Fix8)
			{
				unsigned char *pixelPtr2 = (unsigned char*)pixels;
				delete[] pixelPtr2;
			}
#ifdef _SUPPORT_16_FLOAT_
			else
			{
				half pixelPtr2 = (half*)pixels;
				delete[] pixelPtr2;
			}
#endif
		}


		glPopAttrib();
	}
	else
	{
		// Perform some pre-rendering, pre-exposure. Draw coloured
		// triangles.
		if ( (mLocation == MHardwareRenderer::kPreRendering ) ||
			 ( mLocation == MHardwareRenderer::kPreExposure) )
		{
			cout<<"Call EXP["<<exposureNum<<"/"<<totalExposureCount
				<<"] hwRenderEffect::execute("<<width<<", "<<height
				<<") -- "<<fName.asChar()<<endl;

			glPushAttrib(GL_ALL_ATTRIB_BITS); 

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

			glShadeModel(GL_SMOOTH);
			glDisable(GL_DEPTH_TEST);
			glEnable(GL_BLEND);
			glBlendFunc(GL_ONE, GL_ZERO);

			glColorMask( 1, 1, 1, 0 );
			glBegin(GL_QUADS);
			glColor4f(1.0f,1.0f,1.0f,0.5f);
			glVertex3f( -1.0f, 1.0f, 0.0f);
			glColor4f(0.0f,1.0f,1.0f,0.5f);
			glVertex3f( 0.0f, 1.0f, 0.0f);
			glColor4f(0.0f,1.0f,1.0f,0.5f);
			glVertex3f(-1.0f,-1.0f, 0.0f);
			glColor4f(1.0f,0.0f,1.0f,0.5f);
			glVertex3f( 1.0f,-1.0f, 0.0f);
			glEnd();

			glEnable(GL_DEPTH_TEST);
			glDisable(GL_BLEND);

			glPopAttrib();

		}

		// Do some post exposure. Nothing for now...
		else if ( mLocation == MHardwareRenderer::kPostExposure )
		{
			cout<<"Call EXP["<<exposureNum<<"/"<<totalExposureCount
				<<"] hwRenderEffect::execute("<<width<<", "<<height<<") -- POST-EXPOSURE"<<endl;
		}
	}

	return true;
}
Exemplo n.º 11
0
void draw_s2fishdome(CAMERA cam) {
  
  // draw a fisheye / warped projection of the geometry
  double r, near, far;
  XYZ vp, vd, vr, vl;
  XYZ vright, vleft, vup;

  // Calculate various view vectors 
  vp = cam.vp;
  vd = cam.vd;
  vr = CrossProduct(vd,cam.vu);
  vl = CrossProduct(cam.vu,vd);
  vd = ArbitraryRotate(vd,cam.fishrotate,vr);
  vup = CrossProduct(vr,vd);
  vright = VectorAdd(vr,vd);
  vleft = VectorAdd(vl,vd);
  near = VectorLength(_s2priv_pmin(),_s2priv_pmax()) / 100;
  far  = MAX(cam.focallength,VectorLength(_s2priv_pmin(),
					     _s2priv_pmax())) * 20;
  
  // Left
  glDrawBuffer(GL_BACK);
  glReadBuffer(GL_BACK);
  glViewport(0,0,TEXTURESIZE,TEXTURESIZE);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  s2Perspective(90.0,1.0,near,far);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  s2LookAt(vp.x,vp.y,vp.z,vp.x+vleft.x,vp.y+vleft.y,vp.z+vleft.z,vup.x,vup.y,vup.z);
  MakeLighting();
  MakeMaterial();
  MakeGeometry(FALSE, FALSE);
  glBindTexture(GL_TEXTURE_2D,walltextureid[2]);
  glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,TEXTURESIZE,TEXTURESIZE);
    
  // Right
  glDrawBuffer(GL_BACK);
  glReadBuffer(GL_BACK);
  glViewport(0,0,TEXTURESIZE,TEXTURESIZE);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  s2Perspective(90.0,1.0,near,far);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  s2LookAt(vp.x,vp.y,vp.z,vp.x+vright.x,vp.y+vright.y,vp.z+vright.z,vup.x,vup.y,vup.z);
  MakeLighting();
  MakeMaterial();
  MakeGeometry(FALSE, FALSE);
  glBindTexture(GL_TEXTURE_2D,walltextureid[3]);
  glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,TEXTURESIZE,TEXTURESIZE);
  
  // Top 
  glDrawBuffer(GL_BACK);
  glReadBuffer(GL_BACK);
  glViewport(0,0,TEXTURESIZE,TEXTURESIZE);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  s2Perspective(90.0,1.0,near,far);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  s2LookAt(vp.x,vp.y,vp.z,vp.x+vup.x,vp.y+vup.y,vp.z+vup.z,-vright.x,-vright.y,-vright.z);
  MakeLighting();
  MakeMaterial();
  MakeGeometry(FALSE, FALSE);
  glBindTexture(GL_TEXTURE_2D,walltextureid[0]);
  glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,TEXTURESIZE,TEXTURESIZE);
  
  // Bottom 
  glDrawBuffer(GL_BACK);
  glReadBuffer(GL_BACK);
  glViewport(0,0,TEXTURESIZE,TEXTURESIZE);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  s2Perspective(90.0,1.0,near,far);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  s2LookAt(vp.x,vp.y,vp.z,vp.x-vup.x,vp.y-vup.y,vp.z-vup.z,-vleft.x,-vleft.y,-vleft.z);
  MakeLighting();
  MakeMaterial();
  MakeGeometry(FALSE, FALSE);
  glBindTexture(GL_TEXTURE_2D,walltextureid[1]);
  glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,TEXTURESIZE,TEXTURESIZE);
  
  // Remember the graphics state and return it at the end
  glPushAttrib(GL_ALL_ATTRIB_BITS);
  glDisable(GL_LIGHTING);
  glDisable(GL_ALPHA_TEST);
  glDisable(GL_COLOR_MATERIAL);
  glDisable(GL_DITHER);
  //glDisable(GL_FOG);
  glDisable(GL_LINE_SMOOTH);
  glDisable(GL_LINE_STIPPLE);
  glDisable(GL_SCISSOR_TEST);
  glDisable(GL_STENCIL_TEST);
  
  // Setup projections for the dome
  glDrawBuffer(GL_BACK);
  if (_s2fd_options->dometype == WARPMAP)
    glClearColor(0.0,0.0,0.0,0.0);
  else
    glClearColor(0.05,0.05,0.05,0.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glViewport(0,0,_s2fd_options->screenwidth,_s2fd_options->screenheight);
  r = _s2fd_options->screenwidth / (double)_s2fd_options->screenheight;
  switch (_s2fd_options->dometype) {
  case TRUNCTOP:
  case TRUNCBOTTOM:
    glOrtho(-r*0.75,r*0.75,-0.75,0.75,0.1,10.0);
    break;
  case HSPHERICAL:
    glOrtho(-r*0.75,r*0.75,-0.75,0.75,0.1,10.0);
    break;
  case VSPHERICAL:
  case WARPMAP:
  default:
    glOrtho(-r,r,-1.0,1.0,0.1,10.0);
    break;
  }
    
  // Create camera projection for dome
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  switch (_s2fd_options->dometype) {
  case TRUNCBOTTOM:
    s2LookAt(0.0,-1.0,0.25,0.0,0.0,0.25,0.0,0.0,1.0);
    break;
  case TRUNCTOP:
    s2LookAt(0.0,-1.0,-0.25,0.0,0.0,-0.25,0.0,0.0,1.0);
    break;
  case HSPHERICAL:
  case VSPHERICAL:
  case WARPMAP:
  default:
    s2LookAt(0.0,-1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0);
    break;
  }
    
  // Finally draw the dome geometry
  glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
  glColor3f(1.0,1.0,1.0);
  DrawDome(TRUE,FALSE);

  _s2_fadeinout();
  
  DrawExtras();
  glPopAttrib();
  
}
Exemplo n.º 12
0
/* This function draws a single specific console; if you only use one console in
 * your program, use Draw() instead */
void OGLCONSOLE_Render(OGLCONSOLE_Console console)
{
    /* Don't render hidden console */
    if (C->visible == 0 && C->transitionComplete == 0) return;

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadMatrixd(C->pMatrix);
 
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadMatrixd(C->mvMatrix);

    glPushAttrib(GL_ALL_ATTRIB_BITS);

/*    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE);*/

    /* TODO: This SHOULD become an option at some point because the
     * infrastructure for "real" consoles in the game (like you could walk up to
     * a computer terminal and manipulate a console on a computer using
     * oglconsole) already exists; you'd want depth testing in that case */
    glDisable(GL_DEPTH_TEST);

    /* With SDL, we have SDL_GetTicks(), so we can do a slide transition */
#ifdef OGLCONSOLE_SLIDE
    if (C->transitionComplete) {
      unsigned int t = SDL_GetTicks();
      if (t < C->transitionComplete) {
        double d = (C->transitionComplete - t) / (double)SLIDE_MS;
        if (!C->visible)
          d = 1 - d;
        glTranslated(0, d, 0);
      } else {
        C->transitionComplete = 0;
        if (!C->visible)
          return;
      }
    }
#endif

#if 0
    /* Render hiding / showing console in a special manner. Zero means hidden. 1
     * means visible. All other values are traveling toward zero or one. TODO:
     * Make this time dependent */
    if (C->visibility != 1)
    {
        double d; /* bra size */
        int v = C->visibility;

        /* Count down in both directions */
        if (v < 0)
        {
            v ^= -1;
            C->visibility++;
        }
        else
        {
            v = SLIDE_STEPS - v;
            C->visibility--;
        }

        d = 0.04 * v;
        glTranslated(0, 1-d, 0);
    }
#endif

    /* First we draw our console's background TODO: Add something fancy? */
    glDisable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//    glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR);
    glColor4d(.1,0,0, 0.5);

    glBegin(GL_QUADS);
    glVertex3d(0,0,0);
    glVertex3d(1,0,0);
    glVertex3d(1,1,0);
    glVertex3d(0,1,0);
    glEnd();

    // Change blend mode for drawing text
    glBlendFunc(GL_ONE, GL_ONE);

    /* Select the console font */
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, OGLCONSOLE_glFontHandle);

    /* Recolor text */
    glColor3d(0,1,0);

    /* Render console contents */
    glBegin(GL_QUADS);
    {
        /* Graphical line, and line in lines[] */
        int gLine, tLine = C->lineScrollIndex;

        /* Iterate through each line being displayed */
        for (gLine = 0; gLine < C->textHeight; gLine++)
        {
            /* Draw this line of text adjusting for user scrolling up/down */
            OGLCONSOLE_DrawString(C->lines + (tLine * C->textWidth),
                    0,
                    (C->textHeight - gLine) * C->characterHeight,
                    C->characterWidth,
                    C->characterHeight,
                    0);

            /* Grab next line of text using wheel-queue wrapping */
            if (++tLine >= C->maxLines) tLine = 0;
        }

        /* Here we draw the current commandline, it will either be a line from
         * the command history or the line being edited atm */
        if (C->historyScrollIndex >= 0)
        {
            glColor3d(1,0,0);
            OGLCONSOLE_DrawString(
                    C->history[C->historyScrollIndex],
                    0, 0,
                    C->characterWidth,
                    C->characterHeight,
                    0);
        }
        else
        {
            /* Draw input line cyan */
            glColor3d(0,1,1);
            OGLCONSOLE_DrawString(C->inputLine,
                    0, 0,
                    C->characterWidth,
                    C->characterHeight,
                    0);

            /* Draw cursor beige */
            glColor3d(1,1,.5);
            OGLCONSOLE_DrawCharacter('_',
                    C->inputCursorPos * C->characterWidth, 0,
                    C->characterWidth,
                    C->characterHeight,
                    0);
        }
    }
    glEnd();

    /* Relinquish our rendering settings */
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();

    glPopAttrib();
}
Exemplo n.º 13
0
static void
draw(NVGcontext *nvg, struct zr_command_queue *queue, int width, int height)
{
    const struct zr_command *cmd;
    glPushAttrib(GL_ENABLE_BIT|GL_COLOR_BUFFER_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);
    glEnable(GL_TEXTURE_2D);

    nvgBeginFrame(nvg, width, height, ((float)width/(float)height));
    zr_foreach_command(cmd, queue) {
        switch (cmd->type) {
        case ZR_COMMAND_NOP: break;
        case ZR_COMMAND_SCISSOR: {
            const struct zr_command_scissor *s = zr_command(scissor, cmd);
            nvgScissor(nvg, s->x, s->y, s->w, s->h);
        } break;
        case ZR_COMMAND_LINE: {
            const struct zr_command_line *l = zr_command(line, cmd);
            nvgBeginPath(nvg);
            nvgMoveTo(nvg, l->begin.x, l->begin.y);
            nvgLineTo(nvg, l->end.x, l->end.y);
            nvgFillColor(nvg, nvgRGBA(l->color.r, l->color.g, l->color.b, l->color.a));
            nvgFill(nvg);
        } break;
        case ZR_COMMAND_CURVE: {
            const struct zr_command_curve *q = zr_command(curve, cmd);
            nvgBeginPath(nvg);
            nvgMoveTo(nvg, q->begin.x, q->begin.y);
            nvgBezierTo(nvg, q->ctrl[0].x, q->ctrl[0].y, q->ctrl[1].x,
                q->ctrl[1].y, q->end.x, q->end.y);
            nvgStrokeColor(nvg, nvgRGBA(q->color.r, q->color.g, q->color.b, q->color.a));
            nvgStrokeWidth(nvg, 3);
            nvgStroke(nvg);
        } break;
        case ZR_COMMAND_RECT: {
            const struct zr_command_rect *r = zr_command(rect, cmd);
            nvgBeginPath(nvg);
            nvgRoundedRect(nvg, r->x, r->y, r->w, r->h, r->rounding);
            nvgFillColor(nvg, nvgRGBA(r->color.r, r->color.g, r->color.b, r->color.a));
            nvgFill(nvg);
        } break;
        case ZR_COMMAND_CIRCLE: {
            const struct zr_command_circle *c = zr_command(circle, cmd);
            nvgBeginPath(nvg);
            nvgCircle(nvg, c->x + (c->w/2.0f), c->y + c->w/2.0f, c->w/2.0f);
            nvgFillColor(nvg, nvgRGBA(c->color.r, c->color.g, c->color.b, c->color.a));
            nvgFill(nvg);
        } break;
        case ZR_COMMAND_TRIANGLE: {
            const struct zr_command_triangle *t = zr_command(triangle, cmd);
            nvgBeginPath(nvg);
            nvgMoveTo(nvg, t->a.x, t->a.y);
            nvgLineTo(nvg, t->b.x, t->b.y);
            nvgLineTo(nvg, t->c.x, t->c.y);
            nvgLineTo(nvg, t->a.x, t->a.y);
            nvgFillColor(nvg, nvgRGBA(t->color.r, t->color.g, t->color.b, t->color.a));
            nvgFill(nvg);
        } break;
        case ZR_COMMAND_TEXT: {
            const struct zr_command_text *t = zr_command(text, cmd);
            nvgBeginPath(nvg);
            nvgRoundedRect(nvg, t->x, t->y, t->w, t->h, 0);
            nvgFillColor(nvg, nvgRGBA(t->background.r, t->background.g,
                t->background.b, t->background.a));
            nvgFill(nvg);

            nvgBeginPath(nvg);
            nvgFillColor(nvg, nvgRGBA(t->foreground.r, t->foreground.g,
                t->foreground.b, t->foreground.a));
            nvgFontSize(nvg, (float)t->height);
            nvgTextAlign(nvg, NVG_ALIGN_MIDDLE);
            nvgText(nvg, t->x, t->y + t->h * 0.5f, t->string, &t->string[t->length]);
            nvgFill(nvg);
        } break;
        case ZR_COMMAND_IMAGE: {
            int w, h;
            NVGpaint imgpaint;
            const struct zr_command_image *i = zr_command(image, cmd);
            nvgImageSize(nvg, i->img.handle.id, &w, &h);
            nvgBeginPath(nvg);
            nvgRect(nvg, i->x, i->y, i->w, i->h);
            nvgFillPaint(nvg, nvgImagePattern(nvg,
                i->x, i->y, i->w, i->h, 0, i->img.handle.id, 1));
            nvgFill(nvg);

        } break;
        case ZR_COMMAND_ARC:
        default: break;
        }
    }
    zr_command_queue_clear(queue);

    nvgResetScissor(nvg);
    nvgEndFrame(nvg);
    glPopAttrib();
}
Exemplo n.º 14
0
void calglDisplayBar3D(struct CALGLInfoBar* infoBar){
	static GLfloat minimumDistanceX = 0;
	static GLfloat minimumDistanceY = 0;
	static GLint sub_width;
	static GLint sub_height;
	static GLfloat smallDimension = 5.0f;
	static GLfloat normalDimension = 10.0f;
	GLint i = 0;
	GLfloat internalDistance = 0.0f;

	if(calglGetGlobalSettings()->onlyModel){
		return;
	}

	sub_width = window3D->sub_width;
	sub_height = window3D->sub_height;

	minimumDistanceX = (0.1f)*sub_width;
	minimumDistanceY = (0.1f)*sub_height;

	glPushAttrib(GL_LIGHTING_BIT);{
		glDisable(GL_LIGHTING);

		glPushMatrix();{
			glDepthMask(GL_FALSE);
			glDisable(GL_DEPTH_TEST);

			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();

			gluOrtho2D(0, sub_width, 0, sub_height); //left,right,bottom,top
			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();	

			if(infoBar->height >= infoBar->width){ // h >= w
				infoBar->xPosition = sub_width - minimumDistanceX - infoBar->width;
				infoBar->yPosition = sub_height - minimumDistanceY;

				glBegin(GL_QUADS);{
					switch(infoBar->infoUse){
					case CALGL_TYPE_INFO_USE_GRAY_SCALE: 
						glColor3f(1.0f, 1.0f, 1.0f);
						break;
					case CALGL_TYPE_INFO_USE_RED_SCALE:
						glColor3f(1.0f, 1.0f, 0.0f);
						break;
					case CALGL_TYPE_INFO_USE_GREEN_SCALE:
						glColor3f(0.0f, 1.0f, 0.0f);
						break;
					case CALGL_TYPE_INFO_USE_BLUE_SCALE:
						glColor3f(0.0f, 0.0f, 1.0f);
						break;
					default:
						glColor3f(1.0f, 1.0f, 1.0f);
						break;
					}
					glVertex2f(infoBar->xPosition + infoBar->width, infoBar->yPosition);
					glVertex2f(infoBar->xPosition, infoBar->yPosition);

					switch(infoBar->infoUse){
					case CALGL_TYPE_INFO_USE_RED_SCALE:
						glColor3f(1.0f, 0.0f, 0.0f);
						break;
					default:
						glColor3f(0.0f, 0.0f, 0.0f);
						break;
					}
					glVertex2f(infoBar->xPosition, infoBar->yPosition - infoBar->height);
					glVertex2f(infoBar->xPosition + infoBar->width, infoBar->yPosition - infoBar->height);
				}glEnd();

				glColor3f(1.0f, 1.0f, 1.0f);
				calglPrintString3D(infoBar->xPosition + infoBar->width + normalDimension*3, infoBar->yPosition, calglGetString3D(*infoBar->max));
				calglPrintString3D(infoBar->xPosition + infoBar->width + normalDimension*3, infoBar->yPosition - infoBar->height, calglGetString3D(*infoBar->min));

				internalDistance = infoBar->height/10.0f; 

				for(i = 0; i<11; i++){
					glBegin(GL_LINES); {
						if(i%5==0){
							glVertex2f(infoBar->xPosition + infoBar->width, infoBar->yPosition - i*internalDistance);
							glVertex2f(infoBar->xPosition + infoBar->width + normalDimension*2, infoBar->yPosition - i*internalDistance);
						} else {
							glVertex2f(infoBar->xPosition + infoBar->width, infoBar->yPosition - i*internalDistance);
							glVertex2f(infoBar->xPosition + infoBar->width + smallDimension*2, infoBar->yPosition - i*internalDistance);
						}
					} glEnd();
				}
			} else { // w > h
				infoBar->xPosition = minimumDistanceX;
				infoBar->yPosition = minimumDistanceY + infoBar->height;

				glBegin(GL_QUADS);{
					switch(infoBar->infoUse){
					case CALGL_TYPE_INFO_USE_RED_SCALE:
						glColor3f(1.0f, 0.0f, 0.0f);
						break;
					default:
						glColor3f(0.0f, 0.0f, 0.0f);
						break;
					}		
					glVertex2f(infoBar->xPosition, infoBar->yPosition);
					glVertex2f(infoBar->xPosition, infoBar->yPosition - infoBar->height);					

					switch(infoBar->infoUse){
					case CALGL_TYPE_INFO_USE_GRAY_SCALE: 
						glColor3f(1.0f, 1.0f, 1.0f);
						break;
					case CALGL_TYPE_INFO_USE_RED_SCALE:
						glColor3f(1.0f, 1.0f, 0.0f);
						break;
					case CALGL_TYPE_INFO_USE_GREEN_SCALE:
						glColor3f(0.0f, 1.0f, 0.0f);
						break;
					case CALGL_TYPE_INFO_USE_BLUE_SCALE:
						glColor3f(0.0f, 0.0f, 1.0f);
						break;
					default:
						glColor3f(1.0f, 1.0f, 1.0f);
						break;
					}
					glVertex2f(infoBar->xPosition + infoBar->width, infoBar->yPosition - infoBar->height);
					glVertex2f(infoBar->xPosition + infoBar->width, infoBar->yPosition);
				}glEnd();

				glColor3f(1.0f, 1.0f, 1.0f);
				calglPrintString3D(infoBar->xPosition + infoBar->width, infoBar->yPosition - infoBar->height - normalDimension*3, calglGetString3D(*infoBar->max));
				calglPrintString3D(infoBar->xPosition, infoBar->yPosition - infoBar->height - normalDimension*3, calglGetString3D(*infoBar->min));

				internalDistance = infoBar->width/10.0f; 

				for(i = 0; i<11; i++){
					glBegin(GL_LINES); {
						if(i%5==0){
							glVertex2f(infoBar->xPosition + i*internalDistance, infoBar->yPosition - infoBar->height);
							glVertex2f(infoBar->xPosition + i*internalDistance, infoBar->yPosition - infoBar->height - normalDimension*2);
						} else {
							glVertex2f(infoBar->xPosition + i*internalDistance, infoBar->yPosition - infoBar->height);
							glVertex2f(infoBar->xPosition + i*internalDistance, infoBar->yPosition - infoBar->height - smallDimension*2);
						}
					} glEnd();
				}
			}

			// Print name
			glColor3f(1.0f, 1.0f, 1.0f);
			calglPrintConstString3D(infoBar->xPosition, infoBar->yPosition + 21, infoBar->substateName);

			glDepthMask(GL_TRUE);
		}glPopMatrix();
	}glPopAttrib();

	calglSubReshapeWindow3D(sub_width, sub_height);
}
Exemplo n.º 15
0
        void large_rocky_body::draw(const simulation_context *sim_context, const drawing_context *draw_context)
        {
            lithosphere *litho = get_lithosphere();

            if (litho)
            {
                vector pos_in_view = get_modelview() * vector::ZERO;

                gsgl::real_t radius = gsgl::max_val(get_polar_radius(), get_equatorial_radius());
                gsgl::real_t dist = pos_in_view.mag();
                gsgl::real_t zdist = -pos_in_view.get_z();
                assert(zdist > 0);

                gsgl::real_t far_plane = zdist + (radius * 1.1f);
                gsgl::real_t near_plane = zdist - (radius * 1.1f);
                if (near_plane <= 0)
                    near_plane = 1;

                display::scoped_perspective proj(*draw_context->screen, draw_context->cam->get_field_of_view(), draw_context->screen->get_aspect_ratio(), near_plane, far_plane);
                display::scoped_color cc(*draw_context->screen, color::WHITE);

                gsgl::real_t screen_width = utils::pixel_size(dist, radius, draw_context->cam->get_field_of_view(), draw_context->screen->get_height());

                if (screen_width < MIN_PIXEL_WIDTH)
                {
                    display::scoped_state state(*draw_context->screen, draw_context->display_flags(this, drawing_context::RENDER_NO_LIGHTING));

                    set_flags(get_draw_results(), node::NODE_DREW_POINT);
                    draw_context->screen->draw_point(vector::ZERO, MIN_PIXEL_WIDTH);
                }
                else
                {
                    display::scoped_state state(*draw_context->screen, draw_context->display_flags(this));

                    draw_context->screen->clear(display::CLEAR_DEPTH);
                    display::scoped_modelview mv(*draw_context->screen, &litho->get_modelview());

                    litho->draw(sim_context, draw_context);
                }

                // draw name
                draw_name(draw_context);
            }
            else
            {
                celestial_body::draw(sim_context, draw_context);
            }

#if 0
            lithosphere *litho = get_lithosphere();
            if (litho)
            {
                glPushAttrib(GL_ALL_ATTRIB_BITS);                                                                   CHECK_GL_ERRORS();
                glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);                                                      CHECK_GL_ERRORS();

                vector ep = utils::pos_in_eye_space(this);

                gsgl::real_t radius = gsgl::max_val(get_polar_radius(), get_equatorial_radius());
                gsgl::real_t dist = ep.mag();
                gsgl::real_t zdist = -ep.get_z();
                gsgl::real_t far_plane = zdist + (radius * 1.1f);
                gsgl::real_t near_plane = zdist - (radius * 1.1f);
                if (near_plane <= 0)
                    near_plane = 1;

                glMatrixMode(GL_PROJECTION);                                                                        CHECK_GL_ERRORS();
                glLoadIdentity();                                                                                   CHECK_GL_ERRORS();
                gluPerspective(draw_context->cam->get_field_of_view(), draw_context->screen->get_aspect_ratio(), near_plane, far_plane);  CHECK_GL_ERRORS();

                // check to see if we're out of range
                gsgl::real_t screen_width = utils::pixel_size(dist, radius, draw_context->cam->get_field_of_view(), draw_context->screen->get_height());

                color::WHITE.bind();

                if (screen_width < MIN_PIXEL_WIDTH)
                {
                    get_draw_results() |= node::NODE_DREW_POINT;
                    draw_point(MIN_PIXEL_WIDTH);
                }
                else
                {
                    glClearDepth(1);                                                                                CHECK_GL_ERRORS();
                    glClear(GL_DEPTH_BUFFER_BIT);                                                                   CHECK_GL_ERRORS();
                    glEnable(GL_DEPTH_TEST);                                                                        CHECK_GL_ERRORS();

                    glEnable(GL_CULL_FACE);                                                                         CHECK_GL_ERRORS();
                    glPolygonMode(GL_FRONT_AND_BACK, (draw_context->render_flags & drawing_context::RENDER_WIREFRAME) ? GL_LINE : GL_FILL);     CHECK_GL_ERRORS();

                    // set up lighting
                    if (!(draw_context->render_flags & drawing_context::RENDER_NO_LIGHTING) && !(get_draw_flags() & NODE_DRAW_UNLIT))
                    {
                        glEnable(GL_LIGHTING);                                                                          CHECK_GL_ERRORS();

                        glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);                                            CHECK_GL_ERRORS();
                        glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);                                               CHECK_GL_ERRORS();
                        //glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);

                        glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color::WHITE.get_val());                         CHECK_GL_ERRORS();
                        glMaterialfv(GL_FRONT, GL_SPECULAR, color::BLACK.get_val());                                    CHECK_GL_ERRORS();
                        glMaterialfv(GL_FRONT, GL_EMISSION, color::BLACK.get_val());                                    CHECK_GL_ERRORS();
                        glMaterialf(GL_FRONT, GL_SHININESS, 8);                                                         CHECK_GL_ERRORS();
                    }

                    // set up texturing
                    if (!(draw_context->render_flags & drawing_context::RENDER_NO_TEXTURES))
                    {
                        glEnable(GL_TEXTURE_2D);
                    }

                    // draw lithosphere
                    glMatrixMode(GL_MODELVIEW);
                    glPushMatrix();
                    glLoadMatrixf(litho->get_modelview().ptr());
                    
                    litho->draw(sim_context, draw_context);

                    glMatrixMode(GL_MODELVIEW);
                    glPopMatrix();
                }

                glPopClientAttrib();                                                                                CHECK_GL_ERRORS();
                glPopAttrib();                                                                                      CHECK_GL_ERRORS();

                draw_name(draw_context, 1, far_plane);
            }
            else
            {
                celestial_body::draw(sim_context, draw_context);
            }
#endif
        } // large_rocky_body::draw()
Exemplo n.º 16
0
static int
draw_screen (ModeInfo *mi, Bool mesh_p, Bool sweep_p)
{
  sonar_configuration *sp = &sps[MI_SCREEN(mi)];
  int wire = MI_IS_WIREFRAME(mi);
  int polys = 0;
  int i;
  int th_steps, r_steps, r_skip, th_skip, th_skip2, outer_r;
  GLfloat curvature = M_PI * 0.4;
  GLfloat r0, r1, z0, z1, zoff;
  XYZ *ring;

  static const GLfloat glass[4]  = {0.0, 0.4, 0.0, 0.5};
  static const GLfloat lines[4]  = {0.0, 0.7, 0.0, 0.5};
  static const GLfloat sweepc[4] = {0.2, 1.0, 0.2, 0.5};
  static const GLfloat spec[4]   = {1.0, 1.0, 1.0, 1.0};
  static const GLfloat shiny     = 20.0;

  if (wire && !(mesh_p || sweep_p)) return 0;

  glPushAttrib (GL_ENABLE_BIT);
  glDisable (GL_TEXTURE_2D);

  glFrontFace (GL_CCW);
  th_steps = 36 * 4;    /* must be a multiple of th_skip2 divisor */
  r_steps = 40;
  r_skip = 1;
  th_skip = 1;
  th_skip2 = 1;
  outer_r = 0;

  glMaterialfv (GL_FRONT, GL_SPECULAR,  spec);
  glMateriali  (GL_FRONT, GL_SHININESS, shiny);
  glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, mesh_p ? lines : glass);
  if (wire) glColor3fv (lines);

  if (mesh_p) 
    {
      th_skip  = th_steps / 12;
      th_skip2 = th_steps / 36;
      r_skip = r_steps / 3;
      outer_r = r_steps * 0.93;

      if (! wire)
        glLineWidth (sp->line_thickness);
    }

  ring = (XYZ *) calloc (th_steps, sizeof(*ring));

  for (i = 0; i < th_steps; i++)
    {
      double a = M_PI * 2 * i / th_steps;
      ring[i].x = cos(a);
      ring[i].y = sin(a);
    }

  /* place the bottom of the disc on the xy plane. */
  zoff = cos (curvature/2 * (M_PI/2)) / 2;

  for (i = r_steps; i > 0; i--)
    {
      int j0, j1;

      r0 = i     / (GLfloat) r_steps;
      r1 = (i+1) / (GLfloat) r_steps;

      if (r1 > 1) r1 = 1; /* avoid asin lossage */

      z0 = cos (curvature/2 * asin (r0)) / 2 - zoff;
      z1 = cos (curvature/2 * asin (r1)) / 2 - zoff;

      glBegin(wire || mesh_p ? GL_LINES : GL_QUAD_STRIP);
      for (j0 = 0; j0 <= th_steps; j0++)
        {
          if (mesh_p && 
              (i < outer_r
               ? (j0 % th_skip != 0)
               : (j0 % th_skip2 != 0)))
            continue;

          if (sweep_p)
            {
              GLfloat color[4];
              GLfloat r = 1 - (j0 / (GLfloat) (th_steps * sweep_size));
#if 0
              color[0] = glass[0] + (sweepc[0] - glass[0]) * r;
              color[1] = glass[1] + (sweepc[1] - glass[1]) * r;
              color[2] = glass[2] + (sweepc[2] - glass[2]) * r;
              color[3] = glass[3];
#else
              color[0] = sweepc[0];
              color[1] = sweepc[1];
              color[2] = sweepc[2];
              color[3] = r;
#endif
              glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color);
            }

          j1 = j0 % th_steps;
          glNormal3f (r0 * ring[j1].x, r0 * ring[j1].y, z0);
          glVertex3f (r0 * ring[j1].x, r0 * ring[j1].y, z0);
          glNormal3f (r1 * ring[j1].x, r1 * ring[j1].y, z1);
          glVertex3f (r1 * ring[j1].x, r1 * ring[j1].y, z1);
          polys++;

          if (sweep_p && j0 >= th_steps * sweep_size)
            break;
          if (sweep_p && wire)
            break;
        }
      glEnd();

      if (mesh_p &&
          (i == outer_r ||
           i == r_steps ||
           (i % r_skip == 0 &&
            i < r_steps - r_skip)))
        {
          glBegin(GL_LINE_LOOP);
          for (j0 = 0; j0 < th_steps; j0++)
            {
              glNormal3f (r0 * ring[j0].x, r0 * ring[j0].y, z0);
              glVertex3f (r0 * ring[j0].x, r0 * ring[j0].y, z0);
              polys++;
            }
          glEnd();
        }
    }

  /* one more polygon for the middle */
  if (!wire && !sweep_p)
    {
      glBegin(wire || mesh_p ? GL_LINE_LOOP : GL_POLYGON);
      glNormal3f (0, 0, 1);
      for (i = 0; i < th_steps; i++)
        {
          glNormal3f (r0 * ring[i].x, r0 * ring[i].y, z0);
          glVertex3f (r0 * ring[i].x, r0 * ring[i].y, z0);
        }
      polys++;
      glEnd();
    }

  glPopAttrib();
  free (ring);

  return polys;
}
Exemplo n.º 17
0
/**
 * Renders to resize FBO
 */
static void RenderToResizeFBO( int captureWidth, int captureHeight )
{
	// Stretch and copy the image to the correct area of the destination (black-bordering if necessary)
	float captureAspect = (float)captureHeight / (float)captureWidth;
	float srcAspect = (float)gWindowHeight / (float)gWindowWidth;

	Rect destRect;

	// Determine the destination rectangle
	if (captureAspect >= srcAspect)
	{
		float scale = (float)captureWidth / (float)gWindowWidth;

		destRect.left = 0;
		destRect.right = captureWidth-1;
		destRect.top = (int)( ((float)captureHeight - (float)gWindowHeight*scale) / 2 );
		destRect.bottom = (int)( ((float)captureHeight + (float)gWindowHeight*scale) / 2 );
	}
	else
	{
		float scale = (float)captureHeight / (float)gWindowHeight;

		destRect.top = 0;
		destRect.bottom = captureHeight-1;
		destRect.left = (int)( ((float)captureWidth - (float)gWindowWidth*scale) / 2 );
		destRect.right = (int)( ((float)captureWidth + (float)gWindowWidth*scale) / 2 );
	}

	// render to resize FBO
    glBindFramebuffer(GL_FRAMEBUFFER, gResizeFBO);
	
	// push viewport & clear color
	glPushAttrib(GL_VIEWPORT_BIT | GL_COLOR_BUFFER_BIT);

	glClearColor(0,0,0,0);
	glClear(GL_COLOR_BUFFER_BIT);
	
	// set viewport to dest rect
	glViewport( destRect.left, destRect.top, 
				destRect.right - destRect.left + 1, 
				destRect.bottom - destRect.top + 1);	

    // invert texcoord because opengl's backbuffer starts from bottom
                          /*pos*/  /*texcoord*/
	const float quad[] = { 0,1,    0,0,
	                       0,0,    0,1,
	                       1,1,    1,0,
	                       1,0,    1,1 };

	glDepthMask(false);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_ALPHA_TEST);
	glDisable(GL_BLEND);

	// setup matrix
	{
		// set modeview to identity
		glPushMatrix();
		glLoadIdentity();

		// set 2D projection
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		gluOrtho2D(0,1,0,1);
	}
		
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, gSceneTexture);

	glVertexPointer(  2, GL_FLOAT, sizeof(float)*4, quad);
	glTexCoordPointer(2, GL_FLOAT, sizeof(float)*4, quad+2);

	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

	glBindTexture(GL_TEXTURE_2D, 0);

	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);

	glDepthMask(true);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	// restore matrix
	{
		// restore projection
		glPopMatrix();

		// restore modelview
	    glMatrixMode(GL_MODELVIEW);	
		glPopMatrix();
	}	

	// restor viewport & clear color
	glPopAttrib();
}
Exemplo n.º 18
0
/////////////////////////////////////////////////////////
// render
//
/////////////////////////////////////////////////////////
void teapot :: render(GemState *state)
{
  GLenum type = m_drawType;
  switch(m_drawType){
  case GL_LINE_LOOP: type=GL_LINE;  break;    
  case GL_POINTS   : type=GL_POINT; break;
  case GL_DEFAULT_GEM: // default
  case GL_POLYGON  : type=GL_FILL;  break;
  }
#ifdef GLU_TRUE
  switch(m_drawType){
  case GLU_LINE : type=GL_LINE;  break;    
  case GLU_POINT: type=GL_POINT; break;
  case GLU_FILL : type=GL_FILL;  break;
  }
#endif

  float p[4][4][3], q[4][4][3], r[4][4][3], s[4][4][3];
  long i, j, k, l;

  TexCoord*texCoords=NULL;
  int texType=0;
  int texNum=0;
  bool lighting=false;
  state->get(GemState::_GL_TEX_COORDS, texCoords);
  state->get(GemState::_GL_TEX_TYPE, texType);
  state->get(GemState::_GL_TEX_NUMCOORDS, texNum);
  state->get(GemState::_GL_LIGHTING, lighting);

  if (texType && texNum>=4) {
    m_texCoords[0][0]=texCoords[0].s;m_texCoords[0][1]=texCoords[0].t;
    m_texCoords[1][0]=texCoords[1].s;m_texCoords[1][1]=texCoords[1].t;
    m_texCoords[2][0]=texCoords[2].s;m_texCoords[2][1]=texCoords[2].t;
    m_texCoords[3][0]=texCoords[3].s;m_texCoords[3][1]=texCoords[3].t;  
  }

  glPushAttrib(GL_ENABLE_BIT | GL_EVAL_BIT);
  glEnable(GL_AUTO_NORMAL);
  glEnable(GL_NORMALIZE);
  glEnable(GL_MAP2_VERTEX_3);
  glEnable(GL_MAP2_TEXTURE_COORD_2);
  glPushMatrix();
  glRotatef(270.0, 1.0, 0.0, 0.0);
  glScalef(0.5 * m_size, -0.5 * m_size, 0.5 * m_size);
  glTranslatef(0.0, 0.0, -1.5);
  for (i = 0; i < 10; i++) {
    for (j = 0; j < 4; j++) {
      for (k = 0; k < 4; k++) {
        for (l = 0; l < 3; l++) {
          p[j][k][l] = teapot_cpdata[teapot_patchdata[i][j * 4 + k]][l];
          q[j][k][l] = teapot_cpdata[teapot_patchdata[i][j * 4 + (3 - k)]][l];
          if (l == 1)
            q[j][k][l] *= -1.0;
          if (i < 6) {
            r[j][k][l] =
              teapot_cpdata[teapot_patchdata[i][j * 4 + (3 - k)]][l];
            if (l == 0)
              r[j][k][l] *= -1.0;
            s[j][k][l] = teapot_cpdata[teapot_patchdata[i][j * 4 + k]][l];
            if (l == 0)
              s[j][k][l] *= -1.0;
            if (l == 1)
              s[j][k][l] *= -1.0;
          }
        }
      }
    }
    glMap2f(GL_MAP2_TEXTURE_COORD_2, 0, 1, 2, 2, 0, 1, 4, 2,
      &m_texCoords[0][0]);
    glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, 4, 0, 1, 12, 4,
      &p[0][0][0]);
    glMapGrid2f(m_numSlices, 0.0, 1.0, m_numSlices, 0.0, 1.0);
    glEvalMesh2(type, 0, m_numSlices, 0, m_numSlices);
    glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, 4, 0, 1, 12, 4,
      &q[0][0][0]);
    glEvalMesh2(type, 0, m_numSlices, 0, m_numSlices);
    if (i < 6) {
      glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, 4, 0, 1, 12, 4,
        &r[0][0][0]);
      glEvalMesh2(type, 0, m_numSlices, 0, m_numSlices);
      glMap2f(GL_MAP2_VERTEX_3, 0, 1, 3, 4, 0, 1, 12, 4,
        &s[0][0][0]);
      glEvalMesh2(type, 0, m_numSlices, 0, m_numSlices);
    }
  }
  glPopMatrix();
  glPopAttrib();
}
Exemplo n.º 19
0
void cal_render_actor(actor *act, Uint32 use_lightning, Uint32 use_textures, Uint32 use_glow)
{
	struct CalRenderer *pCalRenderer;
	int meshCount,meshId,submeshCount/*,submeshId, vertexCount*/;
	float points[1024][3];
	static float meshVertices[30000][3];
	static float meshNormals[30000][3];
	static float meshTextureCoordinates[30000][2];
	static CalIndex meshFaces[50000][3];
	struct CalSkeleton *skel;
	struct CalMesh *_mesh;
	struct CalCoreMesh *_coremesh;
	struct CalCoreMesh *_weaponmesh;
	struct CalCoreMesh *_shieldmesh;
	//int boneid=-1;
	float reverse_scale;
	//int glow=-1;
	
	if(act->calmodel==NULL) {
		return;//Wtf!?
	}
	skel=CalModel_GetSkeleton(act->calmodel);

	glPushMatrix();
	// actor model rescaling
	if(actors_defs[act->actor_type].actor_scale != 1.0){
		glScalef(actors_defs[act->actor_type].actor_scale, actors_defs[act->actor_type].actor_scale, actors_defs[act->actor_type].actor_scale);
	}
	// the dynamic scaling
	if(act->scale != 1.0f){
		glScalef(act->scale,act->scale,act->scale);
	}

#ifdef	DYNAMIC_ANIMATIONS
	if(act->last_anim_update < cur_time)
		if(act->cur_anim.duration_scale > 0.0f)
			CalModel_Update(act->calmodel, (((cur_time-act->last_anim_update)*act->cur_anim.duration_scale)/1000.0));
	build_actor_bounding_box(act);
	missiles_rotate_actor_bones(act);
	if (use_animation_program)
	{
		set_transformation_buffers(act);
	}
	act->last_anim_update= cur_time;
#endif	//DYNAMIC_ANIMATIONS

	// get the renderer of the model
#ifdef DEBUG
	if (render_mesh) {
#endif
		pCalRenderer = CalModel_GetRenderer(act->calmodel);
		// begin the rendering loop
		if(CalRenderer_BeginRendering(pCalRenderer)){
			// set global OpenGL states
			if(!act->ghost && act->has_alpha){
				glEnable(GL_ALPHA_TEST);
				glAlphaFunc(GL_GREATER,0.06f);
				glEnable(GL_BLEND);
				glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
				//glDisable(GL_CULL_FACE);
			}

			// will use vertex arrays, so enable them
			glEnableClientState(GL_VERTEX_ARRAY);

			// get the number of meshes
			meshCount = CalRenderer_GetMeshCount(pCalRenderer);

			// check for weapons or shields being worn
			if (act->is_enhanced_model) {
				if(actors_defs[act->actor_type].weapon[act->cur_weapon].mesh_index!=-1) _weaponmesh=CalCoreModel_GetCoreMesh(actors_defs[act->actor_type].coremodel,actors_defs[act->actor_type].weapon[act->cur_weapon].mesh_index);
				else _weaponmesh=NULL;
				if(act->body_parts->shield_meshindex!=-1) _shieldmesh=CalCoreModel_GetCoreMesh(actors_defs[act->actor_type].coremodel,act->body_parts->shield_meshindex);
				else _shieldmesh=NULL;
			} else {
				// non-enhanced never have weapon or shields
				_weaponmesh=NULL;
				_shieldmesh=NULL;
			}
			
			// render all meshes of the model
			for(meshId = 0; meshId < meshCount; meshId++){
				// get the number of submeshes
   				submeshCount = CalRenderer_GetSubmeshCount(pCalRenderer,meshId);

				_mesh=CalModel_GetAttachedMesh(act->calmodel,meshId);//Get current rendered mesh
				_coremesh=CalMesh_GetCoreMesh(_mesh);//Get the coremesh
				
				if(act->is_enhanced_model && (_weaponmesh || _shieldmesh)) {
					//Special treatment for weapons and shields only for enhanced models
					int glow=-1;
					int boneid=-1;
					
					if (_coremesh==_weaponmesh) boneid=26;//If it's a weapon snap to WeaponR bone
					else if (_coremesh==_shieldmesh) boneid=21;//If it's a shield snap to WeaponL bone
					if (boneid!=-1) {
						glPushMatrix();
						reverse_scale= 1.0/actors_defs[act->actor_type].skel_scale;
						CalSkeleton_GetBonePoints(skel,&points[0][0]);

						glTranslatef(points[boneid][0],points[boneid][1],points[boneid][2]);
						glScalef(reverse_scale,reverse_scale,reverse_scale);
						glTranslatef(-points[boneid][0],-points[boneid][1],-points[boneid][2]);

						// find the proper place to bind this object to
						switch(boneid){
							case 26:
								if(actors_defs[act->actor_type].weapon[act->cur_weapon].glow>0){
									glow=actors_defs[act->actor_type].weapon[act->cur_weapon].glow;
								}
								break;
							case 21:
								if(actors_defs[act->actor_type].shield[act->cur_shield].glow>0){
									glow=actors_defs[act->actor_type].shield[act->cur_shield].glow;
								}
							default:
								break;
						}
					}

					// now check for a glowing weapon
					if(glow>0 && use_glow){
						glEnable(GL_COLOR_MATERIAL);
						glBlendFunc(GL_ONE,GL_SRC_ALPHA);
						if(!act->ghost && !(act->buffs & BUFF_INVISIBILITY)) {
							glEnable(GL_BLEND);
							glDisable(GL_LIGHTING);
						}

						if(use_shadow_mapping){
							glPushAttrib(GL_TEXTURE_BIT|GL_ENABLE_BIT);
							ELglActiveTextureARB(shadow_unit);
							glDisable(depth_texture_target);
							disable_texgen();
							ELglActiveTextureARB(GL_TEXTURE0);
						}

						glColor4f(glow_colors[glow].r, glow_colors[glow].g, glow_colors[glow].b, 0.5f);
						glPushMatrix();
						glScalef(0.99f, 0.99f, 0.99f);
						render_submesh(meshId, submeshCount, pCalRenderer, meshVertices, meshNormals, meshTextureCoordinates, meshFaces, 0, use_textures);
						glPopMatrix();

						glColor4f(glow_colors[glow].r, glow_colors[glow].g, glow_colors[glow].b, 0.85f);
						render_submesh(meshId, submeshCount, pCalRenderer, meshVertices, meshNormals, meshTextureCoordinates, meshFaces, 0, use_textures);
						glColor4f(glow_colors[glow].r, glow_colors[glow].g, glow_colors[glow].b, 0.99f);
						glPushMatrix();
						glScalef(1.01f, 1.01f, 1.01f);
						render_submesh(meshId, submeshCount, pCalRenderer, meshVertices, meshNormals, meshTextureCoordinates, meshFaces, 0, use_textures);
						glPopMatrix();

						if(use_shadow_mapping){
							glPopAttrib();
						}
						glColor3f(1.0f, 1.0f, 1.0f);
						glDisable(GL_COLOR_MATERIAL);
						if(!act->ghost && !(act->buffs & BUFF_INVISIBILITY)) {
							glDisable(GL_BLEND);
							glEnable(GL_LIGHTING);
						} else {
							glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
							if((act->buffs & BUFF_INVISIBILITY)) {
								glColor4f(1.0f, 1.0f, 1.0f, 0.25f);
							}
						}
					} else {
						// enhanced actors without glowing items
						render_submesh(meshId, submeshCount, pCalRenderer, meshVertices, meshNormals, meshTextureCoordinates, meshFaces, use_lightning, use_textures);
					}
					if(boneid >= 0){
						//if this was a weapon or shield, restore the transformation matrix
						glPopMatrix();
					}
				} else {
					// non-enhanced actors, or enhanced without attached meshes
					render_submesh(meshId, submeshCount, pCalRenderer, meshVertices, meshNormals, meshTextureCoordinates, meshFaces, use_lightning, use_textures);
				}
			}

			// clear vertex array state
			glDisableClientState(GL_NORMAL_ARRAY);
			glDisableClientState(GL_VERTEX_ARRAY);
			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
			if(!act->ghost && act->has_alpha){
				glDisable(GL_ALPHA_TEST);
				//glEnable(GL_CULL_FACE);
				glDisable(GL_BLEND);
			}

			// end the rendering
			CalRenderer_EndRendering(pCalRenderer);
		}
#ifdef DEBUG
	}
#endif

	glColor3f(1,1,1);

#ifdef DEBUG
	if(render_skeleton)
	{
		glDisable(GL_LIGHTING);
		glDisable(GL_DEPTH_TEST);
		glDisable(GL_TEXTURE_2D);
		
		cal_render_bones(act);
		
		glEnable(GL_LIGHTING);
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_TEXTURE_2D);
	}
#endif
	glPopMatrix();
#ifdef OPENGL_TRACE
CHECK_GL_ERRORS();
#endif //OPENGL_TRACE
}
Exemplo n.º 20
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 unsigned 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, farTextureID);
		glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, oldPixels);
		memset(oldPixels + texSizeX*oldTexSizeY*4, 0, texSizeX*(texSizeY - oldTexSizeY)*4);

		GLuint newFarTextureID;
		glGenTextures(1, &newFarTextureID);
		glBindTexture(GL_TEXTURE_2D, newFarTextureID);
		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, &farTextureID);
		farTextureID = newFarTextureID;

		fbo.AttachTexture(farTextureID);
		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_3DO) {
		// 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();

	cache[obj->team][model->id] = ++usedFarTextures;
}
Exemplo n.º 21
0
Arquivo: wm.c Projeto: retzkek/scatter
void wmDrawWindows(int w, int h)
{
  GLint matrixMode;
  GLboolean lightingOn;

  int i;
  int bx, by, bw, bh;
  char *ch;
  
  // save current state
  lightingOn= glIsEnabled(GL_LIGHTING);        /* lighting on? */
  if (lightingOn) glDisable(GL_LIGHTING);
  glGetIntegerv(GL_MATRIX_MODE, &matrixMode);  /* matrix mode? */
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();
  gluOrtho2D(0, w, h, 0); // set scale to window dimensions, so that coords=pixels
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  glPushAttrib(GL_COLOR_BUFFER_BIT);       /* save current colour */

  
  for (i=0;i<nWindows;i++) {
    glPushMatrix();
    
    GLuint texmid, texend;
    
    // draw expand/collapse button
    glEnable(GL_TEXTURE_2D);
    glColor4f(1.0, 1.0, 1.0,1.0);
    if (ws[i].bstate == WM_BUTTON_DOWN) {
      texend=btnPressedEnd;
      texmid=btnPressedMid;
    } else if (ws[i].bstate == WM_BUTTON_HOVER) {
      texend=btnHoverEnd;
      texmid=btnHoverMid;
    } else {
      texend=btnNormalEnd;
      texmid=btnNormalMid;
    }
    if (ws[i].side == WM_WINDOW_LEFT || ws[i].side == WM_WINDOW_RIGHT) {
      glBindTexture(GL_TEXTURE_2D,texend);
      glBegin( GL_QUADS );
      glTexCoord2f(0,0); glVertex2i(ws[i].bx,          ws[i].by);
      glTexCoord2f(0,1); glVertex2i(ws[i].bx+ws[i].bw, ws[i].by);
      glTexCoord2f(1,1); glVertex2i(ws[i].bx+ws[i].bw, ws[i].by+24);
      glTexCoord2f(1,0); glVertex2i(ws[i].bx,          ws[i].by+24);
      glTexCoord2f(1,0); glVertex2i(ws[i].bx,          ws[i].by+ws[i].bh-24);
      glTexCoord2f(1,1); glVertex2i(ws[i].bx+ws[i].bw, ws[i].by+ws[i].bh-24);
      glTexCoord2f(0,1); glVertex2i(ws[i].bx+ws[i].bw, ws[i].by+ws[i].bh);
      glTexCoord2f(0,0); glVertex2i(ws[i].bx,          ws[i].by+ws[i].bh);
      glEnd();
      glBindTexture(GL_TEXTURE_2D,texmid);
      glBegin( GL_QUADS );
      glTexCoord2f(0,0); glVertex2i(ws[i].bx,          ws[i].by+24);
      glTexCoord2f(0,1); glVertex2i(ws[i].bx+ws[i].bw, ws[i].by+24);
      glTexCoord2f(1,1); glVertex2i(ws[i].bx+ws[i].bw, ws[i].by+ws[i].bh-24);
      glTexCoord2f(1,0); glVertex2i(ws[i].bx,          ws[i].by+ws[i].bh-24);
      glEnd();
    } else {
      glBindTexture(GL_TEXTURE_2D,texend);
      glBegin( GL_QUADS );
      glTexCoord2f(0,0); glVertex2i(ws[i].bx,          ws[i].by);
      glTexCoord2f(0,1); glVertex2i(ws[i].bx,          ws[i].by+ws[i].bh);
      glTexCoord2f(1,1); glVertex2i(ws[i].bx+24,       ws[i].by+ws[i].bh);
      glTexCoord2f(1,0); glVertex2i(ws[i].bx+24,       ws[i].by);
      
      glTexCoord2f(1,0); glVertex2i(ws[i].bx+ws[i].bw-24, ws[i].by);
      glTexCoord2f(1,1); glVertex2i(ws[i].bx+ws[i].bw-24, ws[i].by+ws[i].bh);
      glTexCoord2f(0,1); glVertex2i(ws[i].bx+ws[i].bw,    ws[i].by+ws[i].bh);
      glTexCoord2f(0,0); glVertex2i(ws[i].bx+ws[i].bw,    ws[i].by);
      glEnd();
      glBindTexture(GL_TEXTURE_2D,texmid);
      glBegin( GL_QUADS );
      glTexCoord2f(0,0); glVertex2i(ws[i].bx+24,          ws[i].by);
      glTexCoord2f(1,0); glVertex2i(ws[i].bx+ws[i].bw-24, ws[i].by);
      glTexCoord2f(1,1); glVertex2i(ws[i].bx+ws[i].bw-24, ws[i].by+ws[i].bh);
      glTexCoord2f(0,1); glVertex2i(ws[i].bx+24,          ws[i].by+ws[i].bh);
      glEnd();
    }

    glDisable(GL_TEXTURE_2D);
    // button text
    glColor4f(0.0,0.0,0.0,1.0);
    glLineWidth(1);
    glPushMatrix();
    glLoadIdentity();
    glTranslatef(ws[i].blx,ws[i].bly,0.0);
    glScalef(0.1,-0.1,1.0);
    glRotatef(ws[i].blr,0.0,0.0,1.0);
    for (ch=ws[i].label;*ch;ch++)
      glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, *ch);
    glPopMatrix();
    
    // draw window
    if (ws[i].state == WM_WINDOW_EXPANDED) {
      glTranslatef(ws[i].x, ws[i].y, 0.0); // move to window location
      ws[i].drawFunc(ws[i].w, ws[i].h);
    } 
    
    glPopMatrix();
  }

  
  // restore state
  glPopAttrib();
  glPopMatrix();
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
  glMatrixMode(matrixMode);
  if (lightingOn) glEnable(GL_LIGHTING);
}
Exemplo n.º 22
0
static void fghTeapot( GLint grid, GLdouble scale, GLenum type )
{
#if defined(_WIN32_WCE)
		int i, numV=sizeof(strip_vertices)/4, numI=sizeof(strip_normals)/4;
#else
    double p[4][4][3], q[4][4][3], r[4][4][3], s[4][4][3];
    long i, j, k, l;
#endif

    glPushAttrib( GL_ENABLE_BIT | GL_EVAL_BIT );
    glEnable( GL_AUTO_NORMAL );
    glEnable( GL_NORMALIZE );
    glEnable( GL_MAP2_VERTEX_3 );
    glEnable( GL_MAP2_TEXTURE_COORD_2 );

    glPushMatrix();
    glRotated( 270.0, 1.0, 0.0, 0.0 );
    glScaled( 0.5 * scale, 0.5 * scale, 0.5 * scale );
    glTranslated( 0.0, 0.0, -1.5 );

#if defined(_WIN32_WCE)
    glRotated( 90.0, 1.0, 0.0, 0.0 );
    glBegin( GL_TRIANGLE_STRIP );

    for( i = 0; i < numV-1; i++ )
    {
        int vidx = strip_vertices[i],
            nidx = strip_normals[i];

        if( vidx != -1 )
        {
            glNormal3fv( normals[nidx]  );
            glVertex3fv( vertices[vidx] );
        }
        else
        {
            glEnd();
            glBegin( GL_TRIANGLE_STRIP );
        }
    }

    glEnd();
#else
    for (i = 0; i < 10; i++) {
      for (j = 0; j < 4; j++) {
        for (k = 0; k < 4; k++) {
          for (l = 0; l < 3; l++) {
            p[j][k][l] = cpdata[patchdata[i][j * 4 + k]][l];
            q[j][k][l] = cpdata[patchdata[i][j * 4 + (3 - k)]][l];
            if (l == 1)
              q[j][k][l] *= -1.0;
            if (i < 6) {
              r[j][k][l] =
                cpdata[patchdata[i][j * 4 + (3 - k)]][l];
              if (l == 0)
                r[j][k][l] *= -1.0;
              s[j][k][l] = cpdata[patchdata[i][j * 4 + k]][l];
              if (l == 0)
                s[j][k][l] *= -1.0;
              if (l == 1)
                s[j][k][l] *= -1.0;
            }
          }
        }
      }

      glMap2d(GL_MAP2_TEXTURE_COORD_2, 0.0, 1.0, 2, 2, 0.0, 1.0, 4, 2,
        &tex[0][0][0]);
      glMap2d(GL_MAP2_VERTEX_3, 0.0, 1.0, 3, 4, 0.0, 1.0, 12, 4,
        &p[0][0][0]);
      glMapGrid2d(grid, 0.0, 1.0, grid, 0.0, 1.0);
      glEvalMesh2(type, 0, grid, 0, grid);
      glMap2d(GL_MAP2_VERTEX_3, 0.0, 1.0, 3, 4, 0.0, 1.0, 12, 4,
        &q[0][0][0]);
      glEvalMesh2(type, 0, grid, 0, grid);
      if (i < 6) {
        glMap2d(GL_MAP2_VERTEX_3, 0.0, 1.0, 3, 4, 0.0, 1.0, 12, 4,
          &r[0][0][0]);
        glEvalMesh2(type, 0, grid, 0, grid);
        glMap2d(GL_MAP2_VERTEX_3, 0.0, 1.0, 3, 4, 0.0, 1.0, 12, 4,
          &s[0][0][0]);
        glEvalMesh2(type, 0, grid, 0, grid);
      }
    }
#endif  /* defined(_WIN32_WCE) */

    glPopMatrix();
    glPopAttrib();
}
int PsychDrawText(double xStart, double yStart, int textLen, double* text)
{
	int i;
	GLuint ti;
	QChar* myUniChars = new QChar[textLen];
	
	// On first invocation after init we need to generate a useless texture object.
	// This is a weird workaround for some weird bug somewhere in FTGL...
	if (_firstCall) {
		_firstCall = false;
		glGenTextures(1, &ti);
	}
	
	// Check if rebuild of font face needed due to parameter
	// change. Reload/Rebuild font face if so, check for errors:
	if (_needsRebuild && PsychRebuildFont()) return(1);

	// Synthesize Unicode QString from double vector:
	for(i = 0; i < textLen; i++) {
		myUniChars[i] = QChar((unsigned int) text[i]); 
	}	
	QString	uniCodeText = QString(myUniChars, textLen);  
	delete [] myUniChars;
	
	glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
	glPushAttrib(GL_ALL_ATTRIB_BITS);
	glPixelStorei( GL_UNPACK_ALIGNMENT, 1);
	glEnable( GL_TEXTURE_2D );
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluOrtho2D(_vxs, _vxs + _vw, _vys, _vys + _vh);
	glMatrixMode(GL_MODELVIEW);
	
	// Set text color: This will be filtered by OGLFT for redundant settings:
	if (faceT) {
		faceT->setForegroundColor( _fgcolor[0], _fgcolor[1], _fgcolor[2], _fgcolor[3]);
	}
	else {
		faceM->setForegroundColor( _fgcolor[0], _fgcolor[1], _fgcolor[2], _fgcolor[3]);
	}

	// Rendering of background quad requested? -- True if background alpha > 0.
	if (_bgcolor[3] > 0) {
		// Yes. Compute bounding box of "to be drawn" text and render a quad in background color:
		float xmin, ymin, xmax, ymax;
		PsychMeasureText(textLen, text, &xmin, &ymin, &xmax, &ymax);
		glColor4fv(&(_bgcolor[0]));
		glRectf(xmin + xStart, ymin + yStart, xmax + xStart, ymax + yStart);
	}
	
	// Draw the text at selected start location:
	if (faceT) {
		faceT->draw(xStart, yStart, uniCodeText);
	}
	else {
		faceM->draw(xStart, yStart, uniCodeText);
	}
	
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glDisable( GL_TEXTURE_2D );
	glPopAttrib();
	glPopClientAttrib();
	
	// Ready!
	return(0);	
}
Exemplo n.º 24
0
//--------------------------------------------------------------
void testApp::draw(){
	

			windowCamera.begin();
		
			glPushMatrix();
			//unflip the camera
			//glScalef(1.0, -1.0, 1.0);
			glScalef(4.0, -3.0, 1);
	
			fuxShader.begin();
			
			fuxShader.setUniform1f("eyeMultiply", shaderMultiply);
			fuxShader.setUniformTexture("eyeTexDepth", eyeCam.getTextureReference(), 0);
	
			if	(enableEffects1)
			{
				glPushMatrix();
					glTranslatef(0, 0, effectsTranslate1);
					gridCam.draw(GL_LINES);
				glPopMatrix();
			}

			if	(enableEffects2)
			{
				glPushMatrix();
					glTranslatef(0, 0, effectsTranslate2);
						glPushAttrib(GL_POLYGON_BIT);
							glFrontFace(GL_CW);
							glPointSize(2.5f);
							gridCam.drawDisplayList(GL_POINTS);
						glPopAttrib();
				glPopMatrix();
			}
	
			
			if	(enableEffects3)
			{
				glPushMatrix();
					glTranslatef(0, 0, effectsTranslate3);
						glPushAttrib(GL_POLYGON_BIT);
							 glFrontFace(GL_CW);
							 glPolygonMode(GL_FRONT, GL_LINE);
							 glPolygonMode(GL_BACK, GL_LINE);
							 gridCam.drawDisplayList(GL_TRIANGLE_STRIP);
						glPopAttrib();
				glPopMatrix();
			}
			
			if	(enableEffects4)
			{
				glPushMatrix();
					glTranslatef(0, 0, effectsTranslate4);
						glPushAttrib(GL_POLYGON_BIT);
								glPointSize(5.f);
								gridCam.drawDisplayList(GL_POINTS);
						glPopAttrib();	
				glPopMatrix();
			}


			glPopMatrix();
		
			fuxShader.end();


		windowCamera.end();
	
	
		if (enableGui == true) {
			ofDisableBlendMode();
		hGui * gui = hGui::getInstance();
		gui->draw();
			ofEnableBlendMode(OF_BLENDMODE_ADD);
		}	
	

	
	
}
Exemplo n.º 25
0
		void GLRenderWindow::refresh()
		{			
			RenderWindow::refresh();

			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();

			glPushAttrib(GL_TEXTURE_BIT);
			glPushAttrib(GL_DEPTH_BUFFER_BIT);

#ifdef USE_GLPAINTPIXELS
			glDrawPixels(m_fmt.getWidth(), m_fmt.getHeight(), FB_TEXTURE_FORMAT, FB_TEXTURE_DATATYPE, m_pixels.get());
#else
			glBindTexture(FB_TEXTURE_TARGET, m_screenTexID);
			glTexSubImage2D(FB_TEXTURE_TARGET, 0, 0, 0, m_fmt.getWidth(), m_fmt.getHeight(), 
					FB_TEXTURE_FORMAT, FB_TEXTURE_DATATYPE, m_pixels.get());                

			glEnable(FB_TEXTURE_TARGET);
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
#endif

			glDisable(GL_DEPTH_TEST);
			glMatrixMode(GL_PROJECTION);
			glPushMatrix();

			glLoadIdentity();

			glPushAttrib(GL_VIEWPORT_BIT);
#ifndef USE_GLPAINTPIXELS
			glViewport(0, 0, down_sampling_factor_*m_fmt.getWidth(), down_sampling_factor_*m_fmt.getHeight());
			float aspectRatio = static_cast<float>(m_fmt.getWidth()) / m_fmt.getHeight();
			glOrtho(-aspectRatio, aspectRatio, -1.0f, 1.0f, -1.0f, 1.0f);
			
			
			float origWidth = static_cast<float>(m_fmt.getWidth());
			float newWidth = (origWidth + fabs(stereo_delta_));
			float newRatio = origWidth / newWidth;
			float deltaRatio = 1. - newRatio;
				
			glBegin(GL_QUADS);
			
			if (stereo_delta_ <= 0.)
			{
				glTexCoord2f(0.0f+deltaRatio, 0.0f);
				glVertex2f(-aspectRatio, -1.0f);
			
				glTexCoord2f(1.0f, 0.0f );
				glVertex2f(aspectRatio, -1.0f);	

				glTexCoord2f(1.0f, 1.0f );
				glVertex2f(aspectRatio, 1.0f);	

				glTexCoord2f(0.0f+deltaRatio, 1.0f);
				glVertex2f(-aspectRatio, 1.0f);
			}
			else
			{
				glTexCoord2f(0.0f, 0.0f);
				glVertex2f(-aspectRatio, -1.0f);
			
				glTexCoord2f(1.0f-deltaRatio, 0.0f );
				glVertex2f(aspectRatio, -1.0f);	

				glTexCoord2f(1.0f-deltaRatio, 1.0f );
				glVertex2f(aspectRatio, 1.0f);	

				glTexCoord2f(0.0f, 1.0f);
				glVertex2f(-aspectRatio, 1.0f);
			}


			glEnd();
#endif
			glPopAttrib();

			glPopMatrix();	
			glMatrixMode(GL_MODELVIEW);				

			glPopAttrib();
			glPopAttrib();
		}
void GUIinfoSelection::PrivateDraw()
{


	glPushAttrib(GL_CURRENT_BIT);

	glColor4f(0.0, 0.0, 0.0, 0.5);
	glBindTexture(GL_TEXTURE_2D, 0);

	Quad(0, 0, w, h);

	glColor3f(0, 1, 0);

	map<UnitDef*,GroupUnitsInfo> lstUnits;
	
	char buf[500];

	int i = 0;
	set<CUnit*>::iterator ui;
	if(selectedUnits.selectedGroup!=-1){
		for(ui=grouphandler->groups[selectedUnits.selectedGroup]->units.begin();ui!=grouphandler->groups[selectedUnits.selectedGroup]->units.end();++ui){
			i++;
			lstUnits[(*ui)->unitDef].number = lstUnits[(*ui)->unitDef].number+1;
			lstUnits[(*ui)->unitDef].health = (int)(lstUnits[(*ui)->unitDef].health+(*ui)->health);
			lstUnits[(*ui)->unitDef].maxHealth = (int)(lstUnits[(*ui)->unitDef].maxHealth+(*ui)->maxHealth);
			lstUnits[(*ui)->unitDef].id = (*ui)->unitDef->id;
			if ((*ui)->stockpileWeapon) {
				lstUnits[(*ui)->unitDef].numStockpiled = lstUnits[(*ui)->unitDef].numStockpiled + (*ui)->stockpileWeapon->numStockpiled;
				lstUnits[(*ui)->unitDef].numStockpileQued = lstUnits[(*ui)->unitDef].numStockpileQued + (*ui)->stockpileWeapon->numStockpileQued;
			}
		}
	} else {
		for(ui=selectedUnits.selectedUnits.begin();ui!=selectedUnits.selectedUnits.end();++ui){
			i++;
			lstUnits[(*ui)->unitDef].number = lstUnits[(*ui)->unitDef].number+1;
			lstUnits[(*ui)->unitDef].health = (int)(lstUnits[(*ui)->unitDef].health+(*ui)->health);
			lstUnits[(*ui)->unitDef].maxHealth = (int)(lstUnits[(*ui)->unitDef].maxHealth+(*ui)->maxHealth);
			lstUnits[(*ui)->unitDef].id = (*ui)->unitDef->id;
			if ((*ui)->stockpileWeapon) {
				lstUnits[(*ui)->unitDef].numStockpiled = lstUnits[(*ui)->unitDef].numStockpiled + (*ui)->stockpileWeapon->numStockpiled;
				lstUnits[(*ui)->unitDef].numStockpileQued = lstUnits[(*ui)->unitDef].numStockpileQued + (*ui)->stockpileWeapon->numStockpileQued;
			}
		}
	}
	i=0;
	map<UnitDef*,GroupUnitsInfo>::iterator lsti;
	for(lsti=lstUnits.begin();lsti!=lstUnits.end();lsti++){
		i++;
		float hpp = (float)(lsti->second.health)/(lsti->second.maxHealth);		
		if(hpp>0.5f)
			glColor3f(1.0f-((hpp-0.5f)*2.0f),1.0f,0.0);
		else
			glColor3f(1.0f,hpp*2.0f,0.0);
		sprintf(buf,"%d x",lsti->second.number);
		guifont->Print(13,buildPicSize*i,1,buf);
		glBindTexture(GL_TEXTURE_2D,lsti->first->unitimage);
		int x=48;
		int y=buildPicSize*(i-1)+buildPicSize/2;
		glColor3f(1.0, 1.0, 1.0);
		DrawTexturedQuad(x,	y, buildPicSize, buildPicSize);	
		if (lsti->second.numStockpiled != 0 || lsti->second.numStockpileQued != 0) {
			glColor3f(1.0f,1.0,0.0);
			sprintf(buf,"(%d/%d)",lsti->second.numStockpiled,lsti->second.numStockpileQued);
			guifont->Print(50,buildPicSize*i,1,buf);
		}
	}
	
	h=(i+(i!=0))* buildPicSize;
	glPopAttrib();
}
Exemplo n.º 27
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_ImplSdl_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, 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]);
}
Exemplo n.º 28
0
//----------------------------------------------------------
void ofGLRenderer::draw(const ofMesh & vertexData, ofPolyRenderMode renderType, bool useColors, bool useTextures, bool useNormals) const{
		if (bSmoothHinted) const_cast<ofGLRenderer*>(this)->startSmoothing();
#ifndef TARGET_OPENGLES
		glPushAttrib(GL_POLYGON_BIT);
		glPolygonMode(GL_FRONT_AND_BACK, ofGetGLPolyMode(renderType));
		draw(vertexData,useColors,useTextures,useNormals);
		glPopAttrib(); //TODO: GLES doesnt support polygon mode, add renderType to gl renderer?
#else
		if(vertexData.getNumVertices()){
			glEnableClientState(GL_VERTEX_ARRAY);
			glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), vertexData.getVerticesPointer());
		}
		if(vertexData.getNumNormals() && useNormals){
			glEnableClientState(GL_NORMAL_ARRAY);
			glNormalPointer(GL_FLOAT, 0, vertexData.getNormalsPointer());
		}
		if(vertexData.getNumColors() && useColors){
			glEnableClientState(GL_COLOR_ARRAY);
			glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), vertexData.getColorsPointer());
		}

		if(vertexData.getNumTexCoords() && useTextures){
			set<int>::iterator textureLocation = textureLocationsEnabled.begin();
			for(;textureLocation!=textureLocationsEnabled.end();textureLocation++){
				glActiveTexture(GL_TEXTURE0+*textureLocation);
				glClientActiveTexture(GL_TEXTURE0+*textureLocation);
				glEnableClientState(GL_TEXTURE_COORD_ARRAY);
				glTexCoordPointer(2, GL_FLOAT, sizeof(ofVec2f), &vertexData.getTexCoordsPointer()->x);
			}
			glActiveTexture(GL_TEXTURE0);
			glClientActiveTexture(GL_TEXTURE0);
		}

		GLenum drawMode;
		switch(renderType){
		case OF_MESH_POINTS:
			drawMode = GL_POINTS;
			break;
		case OF_MESH_WIREFRAME:
			drawMode = GL_LINES;
			break;
		case OF_MESH_FILL:
			drawMode = ofGetGLPrimitiveMode(vertexData.getMode());
			break;
		default:
			drawMode = ofGetGLPrimitiveMode(vertexData.getMode());
			break;
		}

		if(vertexData.getNumIndices()){
			glDrawElements(drawMode, vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer());
		}else{
			glDrawArrays(drawMode, 0, vertexData.getNumVertices());
		}
		if(vertexData.getNumColors() && useColors){
			glDisableClientState(GL_COLOR_ARRAY);
		}
		if(vertexData.getNumNormals() && useNormals){
			glDisableClientState(GL_NORMAL_ARRAY);
		}
		if(vertexData.getNumTexCoords() && useTextures){
			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
		}
#endif
		if (bSmoothHinted) const_cast<ofGLRenderer*>(this)->endSmoothing();
}
Exemplo n.º 29
0
void FBO::end() {
	glPopAttrib(); eglGetError();
	unbind();
}
Exemplo n.º 30
0
// Rendu de l'environnement (pour la réflexion de l'eau ou non)
void SceneTerrain::RenderEnvironment(bool bWaterReflection, bool bDepthMap)
{
	ResourceManager& res = ResourceManager::getInstance();
	VarManager& var = VarManager::getInstance();
	Camera& cam = Camera::getInstance();

	vec4 white(1.0f, 1.0f, 1.0f, 1.0f);
	vec4 black(0.0f, 0.0f, 0.0f, 1.0f);
	vec4 orange(1.0f, 0.5f, 0.0f, 1.0f);
	vec4 yellow(1.0f, 1.0f, 0.8f, 1.0f);
	float sun_cosy = cosf(m_vSunAngle.y);

	glPushAttrib(GL_ENABLE_BIT);


	if(!bDepthMap)
	{


		
		vec4 vSunColor = white.lerp(orange, yellow, 0.25f + sun_cosy * 0.75f);


		if(cam.getEye().y < var.getf("water_height"))
		{
			bWaterReflection = false;
			var.set("enable_underwater", true);
		}
		else
		{
			var.set("enable_underwater", false);
		}


		// Affichage du ciel et du soleil
		Sky::getInstance().DrawSkyAndSun( Camera::getInstance().getEye(), vec3(m_vSunVector), m_pSkybox->getHandle(), bWaterReflection );



		// Si c'est pour la réflexion, on dessine la scène à l'envers
		if(bWaterReflection) {
			glDisable(GL_CULL_FACE);
			glLoadIdentity();
			
			glScalef(-1.0f, 1.0f, 1.0f);
			cam.RenderLookAt(true, var.getf("water_height"));
		}

		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		vec3 zeros(0.0f, 0.0f, 0.0f);
		glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, zeros);
		glLightfv(GL_LIGHT0, GL_POSITION, m_vSunVector);
		glLightfv(GL_LIGHT0, GL_AMBIENT, white);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, vSunColor);
		glLightfv(GL_LIGHT0, GL_SPECULAR, vSunColor);

	}

	// Affichage des maisons à l'arrache
	m_pShaderLighting->Activate();
	{
		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, white/6);
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);

		res.getTexture2D("wall_diffuse.jpg")->Bind(0);
		res.getTexture2D("wall_NM_height.tga")->Bind(1);

		m_pShaderLighting->UniformTexture("texDiffuse", 0);
		m_pShaderLighting->UniformTexture("texNormalHeightMap", 1);
		m_pShaderLighting->Uniform("mode", 1);
		m_pShaderLighting->Uniform("enable_shadow_mapping", 0);
		m_pShaderLighting->Uniform("tile_factor", 2.0f);

		glPushMatrix();
		glTranslatef(172.0f, 5.18f, 175.2f);
		res.getMesh("terrain_house.obj")->Draw();
		glPopMatrix();

		glPushMatrix();
		glTranslatef(19.0f, 35.8f, -123.1f);
		res.getMesh("terrain_house.obj")->Draw();
		glPopMatrix();

		glPushMatrix();
		glTranslatef(1.338f, 18.02f, 259.0f);
		res.getMesh("terrain_house.obj")->Draw();
		glPopMatrix();

		glPushMatrix();
		glTranslatef(178.6f, 32.42f, 26.31f);
		res.getMesh("terrain_house.obj")->Draw();
		glPopMatrix();

		res.getTexture2D("wall_NM_height.tga")->Unbind(1);
		res.getTexture2D("wall_diffuse.jpg")->Unbind(0);
	}
	m_pShaderLighting->Deactivate();


	if(!bDepthMap)
	{
		vec4 vGroundAmbient = white.lerp(white*0.2f, black, sun_cosy);
		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, vGroundAmbient);
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white);
		glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
		glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50.0f);



		glMatrixMode(GL_TEXTURE);
		glActiveTexture(GL_TEXTURE0);
		glLoadMatrixf( m_matSunModelviewProj );
		glMatrixMode(GL_MODELVIEW);

		// Activation des textures
		GLuint idx=0;
		for(GLuint i=0; i<m_tTextures.size(); i++)
			m_tTextures[i]->Bind(idx++);
		m_pTerrainDiffuseMap->Bind(idx++);
		if(!bDepthMap) {
			for(GLuint i=0; i<TERRAIN_SHADOWMAPS_COUNT; i++)
				m_fboDepthMapFromLight[i].Bind(idx++);
		}

		// Affichage du terrain
		m_pShaderTerrain->Activate();
		{
			m_pShaderTerrain->Uniform("detail_scale", 120.0f);
			m_pShaderTerrain->Uniform("diffuse_scale", 70.0f);

			m_pShaderTerrain->Uniform("water_height", var.getf("water_height"));
			m_pShaderTerrain->Uniform("water_reflection_rendering", bWaterReflection);

			m_pShaderTerrain->Uniform("time", Timer::getInstance().getCurrentTime());

			m_pShaderTerrain->UniformTexture("texNormalHeightMap", 0);
			m_pShaderTerrain->UniformTexture("texDiffuse0", 1);
			m_pShaderTerrain->UniformTexture("texDiffuse1", 2);
			m_pShaderTerrain->UniformTexture("texDiffuse2", 3);
			m_pShaderTerrain->UniformTexture("texWaterCaustics", 4);
			m_pShaderTerrain->UniformTexture("texDiffuseMap", 5);
			m_pShaderTerrain->UniformTexture("texDepthMapFromLight0", 6);
			m_pShaderTerrain->UniformTexture("texDepthMapFromLight1", 7);

			m_pShaderTerrain->Uniform("depth_map_size", 512);

			int ret = m_pTerrain->DrawGround(bWaterReflection);
			var.set(bWaterReflection? "terrain_chunks_reflected_drawn" : "terrain_chunks_drawn", ret);

			m_pTerrain->DrawInfinitePlane(Camera::getInstance().getEye(), 2.0f*var.getf("cam_zfar"));
		}
		m_pShaderTerrain->Deactivate();

		
		// Désactivation des textures
		if(!bDepthMap) {
			for(GLint i=TERRAIN_SHADOWMAPS_COUNT-1; i>=0; i--)
				m_fboDepthMapFromLight[i].Unbind(--idx);
		}
		m_pTerrainDiffuseMap->Unbind(--idx);
		for(GLint i=(GLint)m_tTextures.size()-1; i>=0; i--)
			m_tTextures[i]->Unbind(--idx);
		

		// Affichage de l'herbe
		if(!bWaterReflection)
		{
			glEnable(GL_BLEND);
			m_pShaderGrass->Activate();
			{
				res.getTexture2D("grass_billboards.tga")->Bind(0);
				for(GLuint i=0; i<TERRAIN_SHADOWMAPS_COUNT; i++)
					m_fboDepthMapFromLight[i].Bind(1+i);

				m_pShaderGrass->UniformTexture("texDiffuse", 0);
				m_pShaderGrass->UniformTexture("texDepthMapFromLight0", 1);
				m_pShaderGrass->UniformTexture("texDepthMapFromLight1", 2);
				m_pShaderGrass->Uniform("depth_map_size", 512);

				m_pShaderGrass->Uniform("time", Timer::getInstance().getCurrentTime());
				m_pShaderGrass->Uniform("lod_metric", TERRAIN_GRASS_MAX_DISTANCE);

					m_pTerrain->DrawGrass(bWaterReflection);

				for(GLint i=TERRAIN_SHADOWMAPS_COUNT-1; i>=0; i--)
					m_fboDepthMapFromLight[i].Unbind(1+i);
				res.getTexture2D("grass_billboards.tga")->Unbind(0);
			}
			m_pShaderGrass->Deactivate();
			glDisable(GL_BLEND);
		}

		glMatrixMode(GL_TEXTURE);
		glActiveTexture(GL_TEXTURE0);
		glLoadIdentity();
		glMatrixMode(GL_MODELVIEW);
	}


	m_pShaderTree->Activate();
	{
		glMatrixMode(GL_TEXTURE);
		glActiveTexture(GL_TEXTURE0);
		glLoadMatrixf( Frustum::getInstance().getModelviewInvMatrix() );
		glMatrixMode(GL_MODELVIEW);

		GLuint idx=0;
		res.getTexture2D("palm_texture.tga")->Bind(idx++);
		if(!bDepthMap) {
			for(GLuint i=0; i<TERRAIN_SHADOWMAPS_COUNT; i++)
				m_fboDepthMapFromLight[i].Bind(idx++);
		}


		m_pShaderTree->UniformTexture("texDiffuse", 0);
		m_pShaderTree->UniformTexture("texDepthMapFromLight0", 1);
		m_pShaderTree->UniformTexture("texDepthMapFromLight1", 2);

		m_pShaderTree->Uniform("time", Timer::getInstance().getCurrentTime());

			m_pTerrain->DrawObjects(bWaterReflection);


		res.getTexture2D("palm_texture.tga")->Unbind(--idx);
		if(!bDepthMap) {
			for(GLint i=TERRAIN_SHADOWMAPS_COUNT-1; i>=0; i--)
				m_fboDepthMapFromLight[i].Unbind(--idx);
		}

		glMatrixMode(GL_TEXTURE);
		glActiveTexture(GL_TEXTURE0);
		glLoadIdentity();
		glMatrixMode(GL_MODELVIEW);
	}
	m_pShaderTree->Deactivate();



	glPopAttrib();

}