Ejemplo n.º 1
0
/*
=============
RB_ARB2_CreateDrawInteractions

=============
*/
void RB_ARB2_CreateDrawInteractions( const drawSurf_t *surf ) {
#if !defined(GL_ES_VERSION_2_0)
	if ( !surf ) {
		return;
	}

	// perform setup here that will be constant for all interactions
	GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE | GLS_DEPTHMASK | backEnd.depthFunc );

	// bind the vertex program
	if ( r_testARBProgram.GetBool() ) {
		glBindProgramARB( GL_VERTEX_PROGRAM_ARB, VPROG_TEST );
		glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, FPROG_TEST );
	} else {
		glBindProgramARB( GL_VERTEX_PROGRAM_ARB, VPROG_INTERACTION );
		glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, FPROG_INTERACTION );
	}

	glEnable(GL_VERTEX_PROGRAM_ARB);
	glEnable(GL_FRAGMENT_PROGRAM_ARB);

	// enable the vertex arrays
	glEnableVertexAttribArrayARB( 8 );
	glEnableVertexAttribArrayARB( 9 );
	glEnableVertexAttribArrayARB( 10 );
	glEnableVertexAttribArrayARB( 11 );
	glEnableClientState( GL_COLOR_ARRAY );

	// texture 0 is the normalization cube map for the vector towards the light
	GL_SelectTextureNoClient( 0 );
	if ( backEnd.vLight->lightShader->IsAmbientLight() ) {
		globalImages->ambientNormalMap->Bind();
	} else {
		globalImages->normalCubeMapImage->Bind();
	}

	// texture 6 is the specular lookup table
	GL_SelectTextureNoClient( 6 );
	if ( r_testARBProgram.GetBool() ) {
		globalImages->specular2DTableImage->Bind();	// variable specularity in alpha channel
	} else {
		globalImages->specularTableImage->Bind();
	}


	for ( ; surf ; surf=surf->nextOnLight ) {
		// perform setup here that will not change over multiple interaction passes

		// set the vertex pointers
		idDrawVert	*ac = (idDrawVert *)vertexCache.Position( surf->geo->ambientCache );
		glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( idDrawVert ), ac->color );
		glVertexAttribPointerARB( 11, 3, GL_FLOAT, false, sizeof( idDrawVert ), ac->normal.ToFloatPtr() );
		glVertexAttribPointerARB( 10, 3, GL_FLOAT, false, sizeof( idDrawVert ), ac->tangents[1].ToFloatPtr() );
		glVertexAttribPointerARB( 9, 3, GL_FLOAT, false, sizeof( idDrawVert ), ac->tangents[0].ToFloatPtr() );
		glVertexAttribPointerARB( 8, 2, GL_FLOAT, false, sizeof( idDrawVert ), ac->st.ToFloatPtr() );
		glVertexPointer( 3, GL_FLOAT, sizeof( idDrawVert ), ac->xyz.ToFloatPtr() );

		// this may cause RB_ARB2_DrawInteraction to be exacuted multiple
		// times with different colors and images if the surface or light have multiple layers
		RB_CreateSingleDrawInteractions( surf, RB_ARB2_DrawInteraction );
	}

	glDisableVertexAttribArrayARB( 8 );
	glDisableVertexAttribArrayARB( 9 );
	glDisableVertexAttribArrayARB( 10 );
	glDisableVertexAttribArrayARB( 11 );
	glDisableClientState( GL_COLOR_ARRAY );

	// disable features
	GL_SelectTextureNoClient( 6 );
	globalImages->BindNull();

	GL_SelectTextureNoClient( 5 );
	globalImages->BindNull();

	GL_SelectTextureNoClient( 4 );
	globalImages->BindNull();

	GL_SelectTextureNoClient( 3 );
	globalImages->BindNull();

	GL_SelectTextureNoClient( 2 );
	globalImages->BindNull();

	GL_SelectTextureNoClient( 1 );
	globalImages->BindNull();

	backEnd.glState.currenttmu = -1;
	GL_SelectTexture( 0 );

	glDisable(GL_VERTEX_PROGRAM_ARB);
	glDisable(GL_FRAGMENT_PROGRAM_ARB);
#endif
}
Ejemplo n.º 2
0
void Mesh::Render() const {
#ifdef IPHONE
  ASSERT(0);
#else
  // Rebuild rendering data if necessary
  if (num_groups_ == -1) {
    short group_v0;
    bool need_new_group = true;
    num_groups_ = 0;

    // Loop through each triangle
    for (int i = 0; i < num_triangles_; i++) {
      // Begin a new rendering group if appropriate
      if (need_new_group) {
        // Allocate data if necessary
        if (num_groups_allocated_ <= num_groups_) {
          num_groups_allocated_ = 3 + num_groups_allocated_*2;
          group_start_ = (short*)realloc(group_start_, num_groups_allocated_*sizeof(short));
          group_size_ = (short*)realloc(group_size_, num_groups_allocated_*sizeof(short));
          if (colors_ != 0) {
            group_is_fixed_color_ = (bool*)realloc(group_is_fixed_color_,
              num_groups_allocated_*sizeof(bool));
          }
          if (normals_ != 0) {
            group_is_fixed_normal_ = (bool*)realloc(group_is_fixed_normal_,
              num_groups_allocated_*sizeof(bool));
          }
        }

        // Begin the new group
        group_start_[num_groups_] = i;
        if (group_is_fixed_color_ != 0)
          group_is_fixed_color_[num_groups_] = true;
        if (group_is_fixed_normal_ != 0)
          group_is_fixed_normal_[num_groups_] = true;
        group_v0 = vertex_indices_[3*i];
        need_new_group = false;
      }

      // Process each vertex in this triangle
      for (int j = 0; j < 3; j++) {
        int v = vertex_indices_[3*i+j];
        if (colors_ != 0 && colors_[v] != colors_[group_v0])
          group_is_fixed_color_[num_groups_] = false;
        if (normals_ != 0 && normals_[v] != normals_[group_v0])
          group_is_fixed_normal_[num_groups_] = false;
      }

      // End this group if appropriate
      if (i == num_triangles_-1 || (textures_ != 0 && textures_[i+1] != textures_[i])) {
        group_size_[num_groups_] = (i+1) - group_start_[num_groups_];
        num_groups_++;
        need_new_group = true;
      }
    }
  }

  // Render the mesh. First specific the vertex array pointers.
	glVertexPointer(3, GL_FLOAT, 0, points_);
  if (normals_ != 0) glNormalPointer(GL_FLOAT, 0, normals_);
  if (colors_ != 0) glColorPointer(4, GL_FLOAT, 0, colors_);
  if (texture_coords_ != 0) glTexCoordPointer(2, GL_FLOAT, 0, texture_coords_);
    
	// Loop through each rendering group
  for (int i = 0; i < num_groups_; i++) {
    int start = group_start_[i], v0 = vertex_indices_[3*start];

		// Set the texture
    if (textures_ != 0 && textures_[start] != 0) {
      glEnableClientState(GL_TEXTURE_COORD_ARRAY);
      GlUtils::SetTexture(textures_[start]);
    } else {
      glDisableClientState(GL_TEXTURE_COORD_ARRAY);
      GlUtils::SetNoTexture();
    }

    // Set the normal
    if (normals_ != 0 && !group_is_fixed_normal_[i]) {
      glEnableClientState(GL_NORMAL_ARRAY);
    } else {
      glDisableClientState(GL_NORMAL_ARRAY);
      if (normals_ != 0) glNormal3fv(&normals_[3*v0]);
    }

    // Set the color
    if (colors_ != 0 && !group_is_fixed_color_[i]) {
      glEnableClientState(GL_COLOR_ARRAY);
    } else {
      glDisableClientState(GL_COLOR_ARRAY);
      if (colors_ != 0) glColor4fv(&colors_[4*v0]);
    }

		// Render the group
    glDrawElements(GL_TRIANGLES, 3*group_size_[i], GL_UNSIGNED_SHORT,
      vertex_indices_ + 3*group_start_[i]);
	}
  GlUtils::SetNoTexture();
#endif
}
Ejemplo n.º 3
0
static void APIENTRY logColorPointer( GLint size, GLenum type, GLsizei stride, const void* pointer ) {
	QGL_Log( "glColorPointer( %d, %s, %d, MEM )\n", size, TypeToString( type ), stride );
	glColorPointer( size, type, stride, pointer );
}
Ejemplo n.º 4
0
void Texture2D::draw()
{
#if USE_OPENGL1
	glDisable(GL_LIGHTING);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_NORMAL_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glEnable(GL_TEXTURE_2D);
	
	// texture transparency
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
#endif
	
	glVertexPointer(2, GL_FLOAT, 0, _vertices);
	glColorPointer(4, GL_UNSIGNED_BYTE, 0, _colors);
	
#if USE_OPENGL1
	// Render using the appropriate version of OpenGL
	
	//	glScalef(kObjectScale, kObjectScale, kObjectScale);
	
	// Draw object
	glTranslatef(_position[0], _position[1], 0.0);
	//glRotatef(-obj3D.rotation, 0, 0, 1);
	//glScalef(obj3D.scale, obj3D.scale, 1.0);
	
	glBindTexture(GL_TEXTURE_2D, _textureID);
	glVertexPointer(2, GL_FLOAT, 0, (const GLvoid*)vertices);
	glTexCoordPointer(2, GL_FLOAT, 0, (const GLvoid*)texCoords);
	//	glNormalPointer(GL_FLOAT, 0, (const GLvoid*)obj3D.normals);
	glDrawElements(GL_TRIANGLES, obj3D.numIndices, GL_UNSIGNED_SHORT, (const GLvoid*)obj3D.indices);
	
#else
	
	
	// OpenGL 2
	
	glUseProgram(_shaderProgramID);
	glVertexAttribPointer(_vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)_vertices);
//	glVertexAttribPointer(_normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)_normals);
	glVertexAttribPointer(_textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)_indices);
	glEnableVertexAttribArray(_vertexHandle);
//	glEnableVertexAttribArray(_normalHandle);
	glEnableVertexAttribArray(_textureCoordHandle);
	
	/*
	 TODO
	 
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, _textureID);
	 
	 // TODO
	 glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (const GLfloat*)&modelViewProjection.data[0]);
	 
	 glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (const GLvoid*)squareIndices);
	 */
#endif
	
	
	
	glDisable(GL_BLEND);
	
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
    
#if USE_OPENGL1
	glDisable(GL_TEXTURE_2D);
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_NORMAL_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
#else
	glDisableVertexAttribArray( _vertexHandle );
	glDisableVertexAttribArray( _normalHandle );
	glDisableVertexAttribArray( _textureCoordHandle );
#endif
}
Ejemplo n.º 5
0
bool cgfxVaryingParameter::bind(const sourceStreamInfo& source) const
{
	// should assert(dataBufferId > 0) here
	// ...
	
	static MGLFunctionTable *gGLFT = 0;
    if ( 0 == gGLFT )
        gGLFT = MHardwareRenderer::theRenderer()->glFunctionTable();
	
	const unsigned int stride = source.fStride;
	const unsigned int offset = source.fOffset;
	const unsigned int dimension  = source.fDimension;
	const unsigned int elementSize  = source.fElementSize;
	const GLuint bufferId = source.fDataBufferId;

	gGLFT->glBindBufferARB(MGL_ARRAY_BUFFER_ARB, bufferId);

	#define GLOBJECT_BUFFER_OFFSET(i) ((char *)NULL + (i)) // For GLObject offsets

	switch( fGLType)
	{
		case glRegister::kPosition:
			glStateCache::instance().enablePosition();
			glVertexPointer(dimension, GL_FLOAT, stride*elementSize, GLOBJECT_BUFFER_OFFSET(offset));
			break;

		case glRegister::kNormal:
			glStateCache::instance().enableNormal();
			glNormalPointer(GL_FLOAT, stride*elementSize, GLOBJECT_BUFFER_OFFSET(offset));
			break;

		case glRegister::kTexCoord:
			if( fGLIndex < glStateCache::sMaxTextureUnits)
			{
				glStateCache::instance().enableAndActivateTexCoord( fGLIndex);
				glTexCoordPointer(dimension, GL_FLOAT, stride*elementSize, GLOBJECT_BUFFER_OFFSET(offset));
			}
			break;

		case glRegister::kColor:
			glStateCache::instance().enableColor();
			glColorPointer(dimension, GL_FLOAT, stride*elementSize, GLOBJECT_BUFFER_OFFSET(offset));
			break;

		case glRegister::kSecondaryColor:
			glStateCache::instance().enableSecondaryColor();
			if( glStateCache::glVertexAttribPointer) 
				glStateCache::glSecondaryColorPointer(dimension, GL_FLOAT, stride*elementSize, GLOBJECT_BUFFER_OFFSET(offset));
			break;

		case glRegister::kVertexAttrib:
			glStateCache::instance().enableVertexAttrib( fGLIndex);
			if( glStateCache::glVertexAttribPointer) 
				glStateCache::glVertexAttribPointer( fGLIndex, dimension, GL_FLOAT, GL_FALSE, stride*elementSize, GLOBJECT_BUFFER_OFFSET(offset));

			if(source.fSourceType == cgfxVertexAttribute::kPosition) {
				glStateCache::instance().enablePosition();
				glVertexPointer(dimension, GL_FLOAT, stride*elementSize, GLOBJECT_BUFFER_OFFSET(offset));
			}
			break;

		/// TODO add secondaryColor, vertexWeight, vertexAttrib, fog
		default:
			return false;  //these we don't support yet
	}

	return true;
}
Ejemplo n.º 6
0
// virtual (default)
void LLVertexBuffer::setupVertexBuffer(U32 data_mask) const
{
	LLMemType mt(LLMemType::MTYPE_VERTEX_DATA);
	stop_glerror();
	volatile U8* base = useVBOs() ? NULL : mMappedData;
	S32 stride = mStride;

	if ((data_mask & mTypeMask) != data_mask)
	{
		llerrs << "LLVertexBuffer::setupVertexBuffer missing required components for supplied data mask." << llendl;
	}

	if (data_mask & MAP_NORMAL)
	{
		glNormalPointer(GL_FLOAT, stride, (void*)(base + mOffsets[TYPE_NORMAL]));
	}
	if (data_mask & MAP_TEXCOORD3)
	{
		glClientActiveTextureARB(GL_TEXTURE3_ARB);
		glTexCoordPointer(2,GL_FLOAT, stride, (void*)(base + mOffsets[TYPE_TEXCOORD3]));
		glClientActiveTextureARB(GL_TEXTURE0_ARB);
	}
	if (data_mask & MAP_TEXCOORD2)
	{
		glClientActiveTextureARB(GL_TEXTURE2_ARB);
		glTexCoordPointer(2,GL_FLOAT, stride, (void*)(base + mOffsets[TYPE_TEXCOORD2]));
		glClientActiveTextureARB(GL_TEXTURE0_ARB);
	}
	if (data_mask & MAP_TEXCOORD1)
	{
		glClientActiveTextureARB(GL_TEXTURE1_ARB);
		glTexCoordPointer(2,GL_FLOAT, stride, (void*)(base + mOffsets[TYPE_TEXCOORD1]));
		glClientActiveTextureARB(GL_TEXTURE0_ARB);
	}
	if (data_mask & MAP_BINORMAL)
	{
		glClientActiveTextureARB(GL_TEXTURE2_ARB);
		glTexCoordPointer(3,GL_FLOAT, stride, (void*)(base + mOffsets[TYPE_BINORMAL]));
		glClientActiveTextureARB(GL_TEXTURE0_ARB);
	}
	if (data_mask & MAP_TEXCOORD0)
	{
		glTexCoordPointer(2,GL_FLOAT, stride, (void*)(base + mOffsets[TYPE_TEXCOORD0]));
	}
	if (data_mask & MAP_COLOR)
	{
		glColorPointer(4, GL_UNSIGNED_BYTE, stride, (void*)(base + mOffsets[TYPE_COLOR]));
	}
	
	if (data_mask & MAP_WEIGHT)
	{
		glVertexAttribPointerARB(1, 1, GL_FLOAT, FALSE, stride, (void*)(base + mOffsets[TYPE_WEIGHT]));
	}
	if (data_mask & MAP_CLOTHWEIGHT)
	{
		glVertexAttribPointerARB(4, 4, GL_FLOAT, TRUE,  stride, (void*)(base + mOffsets[TYPE_CLOTHWEIGHT]));
	}
	if (data_mask & MAP_VERTEX)
	{
		glVertexPointer(3,GL_FLOAT, stride, (void*)(base + 0));
	}

	llglassertok();
}
Ejemplo n.º 7
0
void drawContext::drawView()
{
  OrthofFromGModel();

  glMatrixMode(GL_MODELVIEW);
  // fill the background
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  if(CTX::instance()->bgGradient){
    glPushMatrix();
    glLoadIdentity();
    const GLfloat squareVertices[] = {
      (GLfloat)_top,	(GLfloat)_left, 2*_far,
      (GLfloat)_top,	(GLfloat)_right, 2*_far,
      (GLfloat)_bottom,	(GLfloat)_left, 2*_far,
      (GLfloat)_bottom,	(GLfloat)_right, 2*_far,
    };
    const GLubyte squareColors[] = {
      255, 255, 255, 255,
      255, 255, 255, 255,
      190, 200, 255, 255,
      190, 200, 255, 255,
    };
    glVertexPointer(3, GL_FLOAT, 0, squareVertices);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors);
    glEnableClientState(GL_COLOR_ARRAY);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glPopMatrix();
  }
  checkGlError("Draw background");

  glLoadIdentity();
  glScalef(_scale[0], _scale[1], _scale[2]);
  glTranslatef(_translate[0], _translate[1], _translate[2]);

  if(CTX::instance()->rotationCenterCg)
    glTranslatef(CTX::instance()->cg[0],
                 CTX::instance()->cg[1],
                 CTX::instance()->cg[2]);
  else
    glTranslatef(CTX::instance()->rotationCenter[0],
                 CTX::instance()->rotationCenter[1],
                 CTX::instance()->rotationCenter[2]);

  buildRotationMatrix();
  glMultMatrixf(_rotatef);

  if(CTX::instance()->rotationCenterCg)
    glTranslatef(-CTX::instance()->cg[0],
                 -CTX::instance()->cg[1],
                 -CTX::instance()->cg[2]);
  else
    glTranslatef(-CTX::instance()->rotationCenter[0],
                 -CTX::instance()->rotationCenter[1],
                 -CTX::instance()->rotationCenter[2]);

  checkGlError("Initialize position");

  glEnable(GL_DEPTH_TEST);

  drawMesh();
  checkGlError("Draw mesh");
  drawGeom();
  checkGlError("Draw geometry");
  drawPost();
  checkGlError("Draw post-pro");
  glDisable(GL_DEPTH_TEST);
  drawScale();
  checkGlError("Draw scales");
  drawAxes();
  checkGlError("Draw axes");
}
Ejemplo n.º 8
0
//----------------------------------------------------------
void ofGLRenderer::draw(ofMesh & vertexData, ofPolyRenderMode renderType, bool useColors, bool useTextures, bool useNormals){
		if (bSmoothHinted) 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) endSmoothing();
}
Ejemplo n.º 9
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)
{
    // We are using the OpenGL fixed pipeline to make the example code simpler to read!
    // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
    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 orthographic projection matrix
    const float width = ImGui::GetIO().DisplaySize.x;
    const float height = ImGui::GetIO().DisplaySize.y;
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0f, width, height, 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)(height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, 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, 0);
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);

	bool done = false;

	SDL_Event event;

	glViewport(0, 0, 800, 600);
	glMatrixMode(GL_PROJECTION);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(0.0, 0.0, 0.0);
	glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0);  //multiplies current matrix



	GLuint texture;
	GLuint texture2;
	GLuint texture3;

	texture = LoadTexture("gear.png");
	texture2 = LoadTexture("shocked.png");
	texture3 = LoadTexture("rocket.png");


	float lastFrameTicks = 0.0f;
	float increment = 0.0f;

	while (!done) {

		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}

		}
		glClearColor(1.0, 1.0, 1.0, 0.0);
		glClear(GL_COLOR_BUFFER_BIT);
		glDrawArrays(GL_QUADS, 0, 4);
		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;
		increment += ticks;
		DrawSprite(texture, -0.1, 0.4, lastFrameTicks * 100.0);
		DrawSprite(texture, -0.7, -0.4, -lastFrameTicks * 100.0);
		DrawSprite2(texture2, (increment/200)-0.9, 0.0, 0.0);
		DrawSprite(texture3, (increment/200)-1.3, 0.0, 0.0);

		glLoadIdentity();
		GLfloat redblock[] = { 0.25f, 0.25f, -0.25f, 0.25f, -0.25f, 0.1f, 0.25f, 0.1f };
		glVertexPointer(2, GL_FLOAT, 0, redblock);
		glEnableClientState(GL_VERTEX_ARRAY);
		GLfloat blockColor[] = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f };
		glColorPointer(3, GL_FLOAT, 0, blockColor);
		glEnableClientState(GL_COLOR_ARRAY);
		glTranslated(1.0, 0.0, 0.0);
		glRotatef(90.0f, 0.0f, 0.0f, 1.0f);
		glDrawArrays(GL_QUADS,0,4);
		glDisableClientState(GL_COLOR_ARRAY);
		SDL_GL_SwapWindow(displayWindow);
	}

	SDL_Quit();
	return 0;
}
// OpenGL2 Render function.
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. 
void ImGui_ImplGlfwGL2_RenderDrawData(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, polygon fill.
    GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); 
    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);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound

    // 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
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
        const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
        glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)));
        glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_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;
        }
    }

    // Restore modified state
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
    glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
    glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
Ejemplo n.º 12
0
  void MeshRenderer :: renderToImage(cv::Mat4b& image, int flags)
  {
    ntk_assert(m_vertex_buffer_object.initialized,
               "Renderer not initialized! Call setPose and setMesh.");

    ntk::TimeCount tc_gl_current("make_current", 2);
    m_pbuffer->makeCurrent();
    tc_gl_current.stop();

    ntk::TimeCount tc_gl_render("gl_render", 2);

    if (flags & WIREFRAME)
      glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    VertexBufferObject& vbo = m_vertex_buffer_object;
    glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbo.vertex_id);

    if (vbo.has_texcoords)
    {
      glEnable(GL_TEXTURE_2D);
      glBindTexture(GL_TEXTURE_2D, vbo.texture_id);
    }
    else
    {
      glDisable(GL_TEXTURE_2D);
    }

    if (vbo.has_texcoords)
      glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    if (vbo.has_color)
      glEnableClientState(GL_COLOR_ARRAY);
    else
      glColor3f(1.0f,0.f,0.f);

    glEnableClientState(GL_VERTEX_ARRAY);

    glVertexPointer(3, GL_FLOAT, 0, 0);
    if (vbo.has_color)
      glColorPointer(3, GL_UNSIGNED_BYTE, 0, ((char*) NULL) + vbo.color_offset);

    if (vbo.has_texcoords)
      glTexCoordPointer(2, GL_FLOAT, 0, ((char*) NULL) + vbo.texture_offset);

    if (vbo.has_faces)
    {
      glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vbo.faces_id);
      glNormal3f(0, 0, 1);
      glDrawElements(GL_TRIANGLES, vbo.nb_faces*3, GL_UNSIGNED_INT, 0);
    }
    else
    {
      glDrawArrays(GL_POINTS,
                   0,
                   vbo.nb_vertices);
    }

    glDisableClientState(GL_VERTEX_ARRAY);

    if (vbo.has_color)
      glDisableClientState(GL_COLOR_ARRAY);

    if (vbo.has_texcoords)
      glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    // bind with 0, so, switch back to normal pointer operation
    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

    if (vbo.has_faces)
    {
      glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
    }

    glFinish();
    tc_gl_render.stop();

    ntk::TimeCount tc_image("to_image", 2);
    QImage qimage = m_pbuffer->toImage();
    tc_image.stop();

    ntk::TimeCount tc_depth_buffer("compute_depth_buffer", 2);
    computeDepthBuffer();
    tc_depth_buffer.stop();

    ntk::TimeCount tc_convert("convert_to_cv", 2);
    for (int r = 0; r < qimage.height(); ++r)
      for (int c = 0; c < qimage.width(); ++c)
      {
      QRgb pixel = qimage.pixel(c,r);
      Vec4b color (qBlue(pixel), qGreen(pixel), qRed(pixel), qAlpha(pixel));
      m_color_buffer(r,c) = color;
      float a = qAlpha(pixel)/255.f;
      if (a > 0)
      {
        Vec4b old_color = image(r,c);
        image(r,c) = Vec4b(old_color[0]*(1-a) + color[0]*a,
                           old_color[1]*(1-a) + color[1]*a,
                           old_color[2]*(1-a) + color[2]*a,
                           255);
      }
    }    
    tc_convert.stop();
  }
Ejemplo n.º 13
0
static void drawArrays(drawContext *ctx, GEntity *e, VertexArray *va, GLint type,
                       bool useNormalArray, int forceColor=0, unsigned int color=0)
{
  if(!va || !va->getNumVertices()) return;

  // If we want to be enable picking of individual elements we need to
  // draw each one separately
  bool select = (ctx->render_mode == drawContext::GMSH_SELECT &&
                 CTX::instance()->pickElements && e->model() == GModel::current());
  if(select) {
    if(va->getNumElementPointers() == va->getNumVertices()){
      for(int i = 0; i < va->getNumVertices(); i += va->getNumVerticesPerElement()){
        glPushName(va->getNumVerticesPerElement());
        glPushName(i);
        glBegin(type);
        for(int j = 0; j < va->getNumVerticesPerElement(); j++)
          glVertex3fv(va->getVertexArray(3 * (i + j)));
        glEnd();
        glPopName();
        glPopName();
      }
      return;
    }
  }

  glVertexPointer(3, GL_FLOAT, 0, va->getVertexArray());
  glEnableClientState(GL_VERTEX_ARRAY);

  if(useNormalArray){
    glEnable(GL_LIGHTING);
    glNormalPointer(GL_BYTE, 0, va->getNormalArray());
    glEnableClientState(GL_NORMAL_ARRAY);
  }
  else
    glDisableClientState(GL_NORMAL_ARRAY);

  if(forceColor){
    glDisableClientState(GL_COLOR_ARRAY);
    glColor4ubv((GLubyte *) & color);
  }
  else if(CTX::instance()->pickElements ||
          (!e->getSelection() && (CTX::instance()->mesh.colorCarousel == 0 ||
                                  CTX::instance()->mesh.colorCarousel == 3))){
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, va->getColorArray());
    glEnableClientState(GL_COLOR_ARRAY);
  }
  else{
    glDisableClientState(GL_COLOR_ARRAY);
    color = getColorByEntity(e);
    glColor4ubv((GLubyte *) & color);
  }

  if(va->getNumVerticesPerElement() > 2 && CTX::instance()->polygonOffset)
    glEnable(GL_POLYGON_OFFSET_FILL);

  glDrawArrays(type, 0, va->getNumVertices());

  glDisable(GL_POLYGON_OFFSET_FILL);
  glDisable(GL_LIGHTING);

  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_NORMAL_ARRAY);
  glDisableClientState(GL_COLOR_ARRAY);
}
void CCParticleSystemPoint::draw()
{
	if (m_nParticleIdx==0)
	{
		return;
	}

	// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
	// Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY
	// Unneeded states: GL_TEXTURE_COORD_ARRAY
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);

	glBindTexture(GL_TEXTURE_2D, m_pTexture->getName());

	glEnable(GL_POINT_SPRITE_OES);
	glTexEnvi( GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE );	

#define kPointSize sizeof(m_pVertices[0])

#if CC_USES_VBO
	glBindBuffer(GL_ARRAY_BUFFER, m_uVerticesID);

#if CC_ENABLE_CACHE_TEXTTURE_DATA
    glBufferData(GL_ARRAY_BUFFER, sizeof(ccPointSprite)*m_nTotalParticles, m_pVertices, GL_DYNAMIC_DRAW);
#endif

	glVertexPointer(2,GL_FLOAT,kPointSize,0);

	glColorPointer(4, GL_FLOAT, kPointSize,(GLvoid*) offsetof(ccPointSprite,colors) );

	glEnableClientState(GL_POINT_SIZE_ARRAY_OES);
	glPointSizePointerOES(GL_FLOAT,kPointSize,(GLvoid*) offsetof(ccPointSprite,size) );
#else // Uses Vertex Array List
    int offset = (int)m_pVertices;
    glVertexPointer(2,GL_FLOAT, kPointSize, (GLvoid*) offset);

    int diff = offsetof(ccPointSprite, colors);
    glColorPointer(4, GL_FLOAT, kPointSize, (GLvoid*) (offset+diff));

    glEnableClientState(GL_POINT_SIZE_ARRAY_OES);
    diff = offsetof(ccPointSprite, size);
    glPointSizePointerOES(GL_FLOAT, kPointSize, (GLvoid*) (offset+diff));
#endif 

    bool newBlend = (m_tBlendFunc.src != CC_BLEND_SRC || m_tBlendFunc.dst != CC_BLEND_DST) ? true : false;
	if( newBlend ) 
	{
		glBlendFunc( m_tBlendFunc.src, m_tBlendFunc.dst );
	}

	glDrawArrays(GL_POINTS, 0, m_nParticleIdx);

	// restore blend state
	if( newBlend )
		glBlendFunc( CC_BLEND_SRC, CC_BLEND_DST);

#if CC_USES_VBO
	// unbind VBO buffer
	glBindBuffer(GL_ARRAY_BUFFER, 0);
#endif

	glDisableClientState(GL_POINT_SIZE_ARRAY_OES);
	glDisable(GL_POINT_SPRITE_OES);

	// restore GL default state
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
Ejemplo n.º 15
0
void RudeSkinnedMesh::Render()
{
	RUDE_PERF_START(kPerfRudeSkinMeshRender);
	
	//int numbonemats;
	//glGetIntegerv(GL_MAX_PALETTE_MATRICES_OES, &numbonemats);
	//printf("bonemats %d\n", numbonemats);
	
	glMatrixMode(GL_MODELVIEW);
	PVRTMATRIX viewmat;
	glGetFloatv(GL_MODELVIEW_MATRIX, viewmat.f);
	
	RGL.Enable(kBackfaceCull, true);
	
	glCullFace(GL_FRONT);
	glFrontFace(GL_CW);
	
	
	//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
	//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	
	RGL.EnableClient(kVertexArray, true);
	RGL.EnableClient(kTextureCoordArray, true);
	
	//glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
	
	if(m_animate)
	{
		glEnable(GL_MATRIX_PALETTE_OES);
		glEnableClientState(GL_MATRIX_INDEX_ARRAY_OES);
		glEnableClientState(GL_WEIGHT_ARRAY_OES);
	}
	
	//glScalef(m_scale.x(), m_scale.y(), m_scale.z());
	
	for(int i = 0; i < m_model.nNumNode; i++)
	{
		SPODNode *node = &m_model.pNode[i];
		
		if(!node->pszName)
			continue;
		if(node->pszName[0] != 'M')
			continue;
		
		SPODMaterial *material = &m_model.pMaterial[node->nIdxMaterial];
		SPODMesh *mesh = &m_model.pMesh[node->nIdx];
		
		if(m_animate)
		{
			glMatrixIndexPointerOES(mesh->sBoneIdx.n, GL_UNSIGNED_BYTE, mesh->sBoneIdx.nStride, mesh->pInterleaved + (long) mesh->sBoneIdx.pData);
			glWeightPointerOES(mesh->sBoneWeight.n, GL_FLOAT, mesh->sBoneWeight.nStride, mesh->pInterleaved + (long) mesh->sBoneWeight.pData);
		}
		
		int textureid = material->nIdxTexDiffuse;
		if(textureid >= 0)
			RudeTextureManager::GetInstance()->SetTexture(m_textures[textureid]);
		
		unsigned short *indices	= (unsigned short*) mesh->sFaces.pData;
		
		glVertexPointer(3, GL_FLOAT, mesh->sVertex.nStride, mesh->pInterleaved + (long)mesh->sVertex.pData);
		
		glTexCoordPointer(2, GL_FLOAT, mesh->psUVW->nStride, mesh->pInterleaved + (long)mesh->psUVW->pData);
		
		if((mesh->sVtxColours.n > 0) && (mesh->sVtxColours.eType == EPODDataRGBA))
		{
			RGL.EnableClient(kColorArray, true);
			glColorPointer(4, GL_UNSIGNED_BYTE, mesh->sVtxColours.nStride, mesh->pInterleaved + (long)mesh->sVtxColours.pData);
		}
		else
			RGL.EnableClient(kColorArray, false);
		
		int totalbatchcnt = 0;
		
		for(int b = 0; b < mesh->sBoneBatches.nBatchCnt; b++)
		{
			int batchcnt = mesh->sBoneBatches.pnBatchBoneCnt[b];

			if(m_animate)
			{
				glMatrixMode(GL_MATRIX_PALETTE_OES);
			
				for(int j = 0; j < batchcnt; ++j)
				{
					glCurrentPaletteMatrixOES(j);
					
					// Generates the world matrix for the given bone in this batch.
					PVRTMATRIX	mBoneWorld;
					int i32NodeID = mesh->sBoneBatches.pnBatches[j + totalbatchcnt];
					m_model.GetBoneWorldMatrix(mBoneWorld, *node, m_model.pNode[i32NodeID]);
					
					// Multiply the bone's world matrix by the view matrix to put it in view space
					PVRTMatrixMultiply(mBoneWorld, mBoneWorld, viewmat);
					
					// Load the bone matrix into the current palette matrix.
					glLoadMatrixf(mBoneWorld.f);
				}
			}
			
			totalbatchcnt += batchcnt;
			
			int offset = mesh->sBoneBatches.pnBatchOffset[b] * 3;
			int end = mesh->sBoneBatches.pnBatchOffset[b+1] * 3;
			
			if(b == (mesh->sBoneBatches.nBatchCnt - 1))
				end = mesh->nNumFaces*3;
			
			int numidx = (end - offset);
			
			glDrawElements(GL_TRIANGLES, numidx, GL_UNSIGNED_SHORT, &indices[offset]);
		}
	
	}
	
	glDisable(GL_MATRIX_PALETTE_OES);
	glDisableClientState(GL_MATRIX_INDEX_ARRAY_OES);
	glDisableClientState(GL_WEIGHT_ARRAY_OES);
	
	RUDE_PERF_STOP(kPerfRudeSkinMeshRender);
}
Ejemplo n.º 16
0
void VertexArrayRenderer::DisplayImpl() const {
	if( m_alpha_threshold > 0.f ) {
		glAlphaFunc( GL_GREATER, m_alpha_threshold );
		glEnable( GL_ALPHA_TEST );
	}

	if( m_dirty ) {
		// Disclaimer:
		// const_cast IS safe to use in ANY non-static method of
		// Renderer. Because we make sure that the only instance
		// that can be constructed is the singleton instance and
		// that the singleton instance is non-const, we don't have
		// to fear that some member variable is non-mutable. This
		// is a nice hack to please certain people who require const
		// methods in the most exotic places without having to declare
		// half the member variables and methods as mutable. Then
		// again this might be all wrong...

		// Refresh array data if out of sync
		const_cast<VertexArrayRenderer*>( this )->RefreshArray();
	}

	glVertexPointer( 2, GL_FLOAT, 0, &m_vertex_data[0] );
	glColorPointer( 4, GL_UNSIGNED_BYTE, 0, &m_color_data[0] );
	glTexCoordPointer( 2, GL_FLOAT, 0, &m_texture_data[0] );

	// Not needed, constantly kept enabled by SFML... -_-
	//glEnableClientState( GL_VERTEX_ARRAY );
	//glEnableClientState( GL_COLOR_ARRAY );
	//glEnableClientState( GL_TEXTURE_COORD_ARRAY );

	glEnable( GL_SCISSOR_TEST );

	std::size_t current_atlas_page = 0;

	sf::Texture::bind( m_texture_atlas[0].get() );

	for( const auto& batch : m_batches ) {
		auto viewport = batch.viewport;

		if( batch.custom_draw ) {
			sf::Vector2i destination( viewport->GetDestinationOrigin() );
			sf::Vector2u size( viewport->GetSize() );

			glViewport( destination.x, m_window_size.y - destination.y - size.y, size.x, size.y );

			// Draw canvas.
			( *batch.custom_draw_callback )();

			glViewport( 0, 0, m_window_size.x, m_window_size.y );

			sf::Texture::bind( m_texture_atlas[current_atlas_page].get() );
		}
		else {
			if( viewport && ( ( *viewport ) != ( *m_default_viewport ) ) ) {
				auto destination_origin = viewport->GetDestinationOrigin();
				auto size = viewport->GetSize();

				glScissor(
					static_cast<int>( destination_origin.x ),
					m_window_size.y - static_cast<int>( destination_origin.y + size.y ),
					static_cast<int>( size.x ),
					static_cast<int>( size.y )
				);
			}
			else {
				glScissor( 0, 0, m_window_size.x, m_window_size.y );
			}

			if( batch.index_count ) {
				if( batch.atlas_page != current_atlas_page ) {
					current_atlas_page = batch.atlas_page;

					sf::Texture::bind( m_texture_atlas[current_atlas_page].get() );
				}

				glDrawElements(
					GL_TRIANGLES,
					batch.index_count,
					GL_UNSIGNED_INT,
					reinterpret_cast<const char*>( &m_index_data[0] ) + ( batch.start_index * sizeof( GLuint ) )
				);
			}
		}
	}

	glDisable( GL_SCISSOR_TEST );

	//glDisableClientState( GL_TEXTURE_COORD_ARRAY );
	//glDisableClientState( GL_COLOR_ARRAY );
	//glDisableClientState( GL_VERTEX_ARRAY );

	m_dirty = false;

	if( m_alpha_threshold > 0.f ) {
		glDisable( GL_ALPHA_TEST );
		glAlphaFunc( GL_GREATER, 0.f );
	}
}
Ejemplo n.º 17
0
static void
draw(void)
{
   if ( use_ztrick ) {
      static GLboolean flip = GL_FALSE;
      static const GLfloat vert[4][3] = {
	 { -1, -1, -0.999 },
	 {  1, -1, -0.999 },
	 {  1,  1, -0.999 },
	 { -1,  1, -0.999 }
      };
      static const GLfloat col[4][3] = {
	 { 1.0, 0.6, 0.0 },
	 { 1.0, 0.6, 0.0 },
	 { 0.0, 0.0, 0.0 },
	 { 0.0, 0.0, 0.0 },
      };
      
      if ( flip ) {
	 glDepthRange(0, 0.5);
	 glDepthFunc(GL_LEQUAL);
      }
      else {
	 glDepthRange(1.0, 0.4999);
	 glDepthFunc(GL_GEQUAL);
      }

      flip = !flip;

      /* The famous Quake "Z trick" only works when the whole screen is
       * re-drawn each frame.
       */

      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      glOrtho(-1, 1, -1, 1, -1, 1);
      glDisable(GL_LIGHTING);
      glShadeModel(GL_SMOOTH);

      glEnableClientState( GL_VERTEX_ARRAY );
      glEnableClientState( GL_COLOR_ARRAY );
      glVertexPointer( 3, GL_FLOAT, 0, vert );
      glColorPointer( 3, GL_FLOAT, 0, col );
      glDrawArrays( GL_POLYGON, 0, 4 );
      glDisableClientState( GL_COLOR_ARRAY );
      glDisableClientState( GL_VERTEX_ARRAY );

      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      glFrustum(-aspectX, aspectX, -aspectY, aspectY, 5.0, 60.0);

      glEnable(GL_LIGHTING);

      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
      glTranslatef(0.0, 0.0, -45.0);
   }
   else {
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   }

   glPushMatrix();
   glRotatef(view_rotx, 1.0, 0.0, 0.0);
   glRotatef(view_roty, 0.0, 1.0, 0.0);
   glRotatef(view_rotz, 0.0, 0.0, 1.0);

   glPushMatrix();
   glTranslatef(-3.0, -2.0, 0.0);
   glRotatef(angle, 0.0, 0.0, 1.0);
   glCallList(gear1);
   glPopMatrix();

   glPushMatrix();
   glTranslatef(3.1, -2.0, 0.0);
   glRotatef(-2.0 * angle - 9.0, 0.0, 0.0, 1.0);
   glCallList(gear2);
   glPopMatrix();

   glPushMatrix();
   glTranslatef(-3.1, 4.2, 0.0);
   glRotatef(-2.0 * angle - 25.0, 0.0, 0.0, 1.0);
   glCallList(gear3);
   glPopMatrix();

   glPopMatrix();
}
Ejemplo n.º 18
0
void WoodInit(void) {
	glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ) ; //set the clear back ground color;
	glShadeModel(GL_SMOOTH); //GL_FLAT | GL_SMOOTH

	WoodInitLight();

	glEnable(GL_DEPTH_TEST);


	//start init for tex
	{
		//glEnable( GL_TEXTURE_2D );
		//glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE ); 
		MakeCheckImage();
		glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
		glGenTextures( 1, &g_uTexName );
		glBindTexture( GL_TEXTURE_2D, g_uTexName );

		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );

		glTexImage2D( GL_TEXTURE_2D, 0 , GL_RGBA, G_IMG_TEX_WIDTH,G_IMG_TEX_HEIGHT,0, GL_RGBA, GL_UNSIGNED_BYTE,g_ImgTex  );
	}




	//glEnable(GL_MULTISAMPLE_ARB);
	//glEnable(GL_MULTISAMPLE);
	//glEnable(GL_POLYGON_SMOOTH);
	//glEnable(GL_LINE_SMOOTH);

	//glEnable ( GL_POLYGON_SMOOTH ); //GL_POLYGON_SMOOTH | GL_LINE_SMOOTH 
	//glEnable ( GL_LINE_SMOOTH );

	//glHint ( GL_LINE_SMOOTH, GL_DONT_CARE );
	//glHint ( GL_POLYGON_SMOOTH, GL_DONT_CARE );

	//glEnable ( GL_BLEND );

	//glBlendFunc ( GL_SRC_ALPHA_SATURATE, GL_ONE);


	/*
	glMatrixMode(GL_PROJECTION); //initialize viewing values...
	glLoadIdentity(); //??
	glOrtho(0.0,1.0,0.0,1.0,-1.0,1.0); //??
	*/
	glLineWidth(2.0);

	glEnableClientState(GL_COLOR_ARRAY);
	glEnableClientState(GL_VERTEX_ARRAY);

	glColorPointer( 4,GL_FLOAT,0,g_colors );
	glVertexPointer( 3,GL_FLOAT,0,g_vertices );

	//glList Start
	{
		g_iCacheList = glGenLists( 1 );
		glNewList( g_iCacheList,GL_COMPILE );
		//glTexCoord2f(0.0,0.0);

		glEnable(GL_TEXTURE_2D);
		glBindTexture( GL_TEXTURE_2D, g_uTexName );

		glNormal3f( 0.0f, 0.0f, 1.0f);
		glDrawElements (GL_POLYGON, 4, GL_UNSIGNED_BYTE, g_indices[0]); //前

		glNormal3f( 0.0f, -1.0f, 0.0f);
		glDrawElements (GL_POLYGON, 4, GL_UNSIGNED_BYTE, g_indices[1]); //下

		glNormal3f( 1.0f, 0.0f, 0.0f);
		glDrawElements (GL_POLYGON, 4, GL_UNSIGNED_BYTE, g_indices[2]); //右

		glNormal3f( 0.0f, 1.0f, 0.0f);
		glDrawElements (GL_POLYGON, 4, GL_UNSIGNED_BYTE, g_indices[3]); //上

		glNormal3f( -1.0f, 0.0f, 0.0f);
		glDrawElements (GL_POLYGON, 4, GL_UNSIGNED_BYTE, g_indices[4]); //左

		glNormal3f( 0.0f, 0.0f, -1.0f);
		glDrawElements (GL_POLYGON, 4, GL_UNSIGNED_BYTE, g_indices[5]);	//后

		glDisable(GL_TEXTURE_2D);
		/*
		//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

		glBindTexture( GL_TEXTURE_2D, g_uTexName );
		GLUquadricObj * sphere = gluNewQuadric();
		gluQuadricOrientation(sphere, GLU_OUTSIDE);
		gluQuadricNormals(sphere,GLU_SMOOTH);
		gluQuadricTexture(sphere,GL_TRUE);
		gluSphere(sphere,1.0,50,50);
		//glutSolidSphere(1.0,50,50);
		*/

		

		glEndList();
	}




}
Ejemplo n.º 19
0
void drawContext::drawScale()
{
  glPushMatrix();
  glLoadIdentity();

  double size = std::max(_right -_left, _top - _bottom);
  double width = size / 3.5;
  double height = size / 10.;
  double dh = height / 5;

	// Draw the scale bar
  int nPview = 0;
  for(int i=0; i<PView::list.size();i++){
    PView *p = PView::list[i];
    PViewOptions *opt = p->getOptions();
    if(!opt->visible) continue;
    PViewData *data = p->getData();

    double box = width / (opt->nbIso ? opt->nbIso : 1);
    double xmin = _left + (_right - _left - width)/2.;
    double ymin = _bottom + 0.7 * height + height * nPview;

    std::vector<GLfloat> vertex(opt->nbIso*3*4);
    std::vector<GLubyte> color(opt->nbIso*4*4);
    for(int i = 0; i < opt->nbIso; i++){
      if(opt->intervalsType == PViewOptions::Discrete ||
         opt->intervalsType == PViewOptions::Numeric){
        unsigned int col = opt->getColor(i, opt->nbIso);
        color[i*4*4+0] = color[i*4*4+4] = color[i*4*4+8] = color[i*4*4+12] =
          (GLubyte)CTX::instance()->unpackRed(col);
        color[i*4*4+1] = color[i*4*4+5] = color[i*4*4+9] = color[i*4*4+13] =
          (GLubyte)CTX::instance()->unpackGreen(col);
        color[i*4*4+2] = color[i*4*4+6] = color[i*4*4+10] = color[i*4*4+14] =
          (GLubyte)CTX::instance()->unpackBlue(col);
        color[i*4*4+3] = color[i*4*4+7] = color[i*4*4+11] = color[i*4*4+15] =
          (GLubyte)CTX::instance()->unpackAlpha(col);
        vertex[i*3*4+0] = xmin + i * box;
        vertex[i*3*4+1] = ymin;
        vertex[i*3*4+2] = 0.;
        vertex[i*3*4+3] = xmin + i * box;
        vertex[i*3*4+4] = ymin + dh;
        vertex[i*3*4+5] = 0.;
        vertex[i*3*4+6] = xmin + (i + 1) * box;
        vertex[i*3*4+7] = ymin;
        vertex[i*3*4+8] = 0.;
        vertex[i*3*4+9] = xmin + (i + 1) * box;
        vertex[i*3*4+10] = ymin + dh;
        vertex[i*3*4+11] = 0.;
      }
      else if(opt->intervalsType == PViewOptions::Continuous){
        double dv = (opt->tmpMax - opt->tmpMin) / (opt->nbIso ? opt->nbIso : 1);
        double v1 = opt->tmpMin + i * dv;
        unsigned int col1 = opt->getColor(v1, opt->tmpMin, opt->tmpMax, true);
        color[i*4*4+0] = color[i*4*4+4] = (GLubyte)CTX::instance()->unpackRed(col1);
        color[i*4*4+1] = color[i*4*4+5] = (GLubyte)CTX::instance()->unpackGreen(col1);
        color[i*4*4+2] = color[i*4*4+6] = (GLubyte)CTX::instance()->unpackBlue(col1);
        color[i*4*4+3] = color[i*4*4+7] = (GLubyte)CTX::instance()->unpackAlpha(col1);
        vertex[i*3*4+0] = xmin + i * box;
        vertex[i*3*4+1] = ymin;
        vertex[i*3*4+2] = 0.;
        vertex[i*3*4+3] = xmin + i * box;
        vertex[i*3*4+4] = ymin + dh;
        vertex[i*3*4+5] = 0.;
        double v2 = opt->tmpMin + (i + 1) * dv;
        unsigned int col2 = opt->getColor(v2, opt->tmpMin, opt->tmpMax, true);
        color[i*4*4+8] = color[i*4*4+12] = (GLubyte)CTX::instance()->unpackRed(col2);
        color[i*4*4+9] = color[i*4*4+13] = (GLubyte)CTX::instance()->unpackGreen(col2);
        color[i*4*4+10] = color[i*4*4+14] = (GLubyte)CTX::instance()->unpackBlue(col2);
        color[i*4*4+11] = color[i*4*4+15] = (GLubyte)CTX::instance()->unpackAlpha(col2);
        vertex[i*3*4+6] = xmin + (i + 1) * box;
        vertex[i*3*4+7] = ymin;
        vertex[i*3*4+8] = 0.;
        vertex[i*3*4+9] = xmin + (i + 1) * box;
        vertex[i*3*4+10] = ymin + dh;
        vertex[i*3*4+11] = 0.;
      }
      else{
        unsigned int col = opt->getColor(i, opt->nbIso);
        color[i*4*4+0] = color[i*4*4+4] = color[i*4*4+8] = color[i*4*4+12] =
          (GLubyte)CTX::instance()->unpackRed(col);
        color[i*4*4+1] = color[i*4*4+5] = color[i*4*4+9] = color[i*4*4+13] =
          (GLubyte)CTX::instance()->unpackGreen(col);
        color[i*4*4+2] = color[i*4*4+6] = color[i*4*4+10] = color[i*4*4+14] =
          (GLubyte)CTX::instance()->unpackBlue(col);
        color[i*4*4+3] = color[i*4*4+7] = color[i*4*4+11] = color[i*4*4+15] =
          (GLubyte)CTX::instance()->unpackAlpha(col);
        vertex[i*3*4+0] = xmin + i * box;
        vertex[i*3*4+1] = ymin;
        vertex[i*3*4+2] = 0.;
        vertex[i*3*4+3] = xmin + i * box;
        vertex[i*3*4+4] = ymin + dh;
        vertex[i*3*4+5] = 0.;
        vertex[i*3*4+6] = xmin + (i + 1) * box;
        vertex[i*3*4+7] = ymin;
        vertex[i*3*4+8] = 0.;
        vertex[i*3*4+9] = xmin + (i + 1) * box;
        vertex[i*3*4+10] = ymin + dh;
        vertex[i*3*4+11] = 0.;
      }
    }

    glVertexPointer(3, GL_FLOAT, 0, &vertex[0]);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, &color[0]);
    glEnableClientState(GL_COLOR_ARRAY);
    if(opt->intervalsType == PViewOptions::Discrete ||
       opt->intervalsType == PViewOptions::Numeric ||
       opt->intervalsType == PViewOptions::Continuous)
      glDrawArrays(GL_TRIANGLE_STRIP, 0, opt->nbIso*4);
    else
      glDrawArrays(GL_LINES, 0, opt->nbIso*4);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    char label[1024];
    int nt = data->getNumTimeSteps();
    if((opt->showTime == 1 && nt > 1) || opt->showTime == 2){
      char tmp[256];
      sprintf(tmp, opt->format.c_str(), data->getTime(opt->timeStep));
      sprintf(label, "%s (%s)", data->getName().c_str(), tmp);
    }
    else if((opt->showTime == 3 && nt > 1) || opt->showTime == 4){
      sprintf(label, "%s (%d/%d)", data->getName().c_str(), opt->timeStep,
              data->getNumTimeSteps() - 1);
    }
    else{
      sprintf(label, "%s", data->getName().c_str());
    }
    drawString lbl(label, 20 * _fontFactor);
    lbl.draw(xmin + width / 2, ymin + 2.8 * dh, 0.,
             _width/(_right-_left), _height/(_top-_bottom));

    drawString val(data->getName().c_str(), 15 * _fontFactor);
    for(int i = 0; i < 3; i++) {
      double v = opt->getScaleValue(i, 3, opt->tmpMin, opt->tmpMax);
      sprintf(label, opt->format.c_str(), v);
      val.setText(label);
      val.draw(xmin + i * width/ 2, ymin + 1.5 * dh, 0.,
               _width/(_right-_left), _height/(_top-_bottom));
    }
    nPview++;
  }
  glPopMatrix();
}
Ejemplo n.º 20
0
void OGLRender::Initialize(void)
{
    glMatrixMode(GL_MODELVIEW);
    OPENGL_CHECK_ERRORS;
    glLoadIdentity();
    OPENGL_CHECK_ERRORS;

    glViewportWrapper(0, windowSetting.statusBarHeightToUse, windowSetting.uDisplayWidth, windowSetting.uDisplayHeight);
    OPENGL_CHECK_ERRORS;

#if SDL_VIDEO_OPENGL
    COGLGraphicsContext *pcontext = (COGLGraphicsContext *)(CGraphicsContext::g_pGraphicsContext);
    if( pcontext->IsExtensionSupported("GL_IBM_texture_mirrored_repeat") )
    {
        OGLXUVFlagMaps[TEXTURE_UV_FLAG_MIRROR].realFlag = GL_MIRRORED_REPEAT_IBM;
    }
    else if( pcontext->IsExtensionSupported("ARB_texture_mirrored_repeat") )
    {
        OGLXUVFlagMaps[TEXTURE_UV_FLAG_MIRROR].realFlag = GL_MIRRORED_REPEAT_ARB;
    }
    else
    {
        OGLXUVFlagMaps[TEXTURE_UV_FLAG_MIRROR].realFlag = GL_REPEAT;
    }

    if( pcontext->IsExtensionSupported("GL_ARB_texture_border_clamp") || pcontext->IsExtensionSupported("GL_EXT_texture_edge_clamp") )
    {
        m_bSupportClampToEdge = true;
        OGLXUVFlagMaps[TEXTURE_UV_FLAG_CLAMP].realFlag = GL_CLAMP_TO_EDGE;
    }
    else
    {
        m_bSupportClampToEdge = false;
        OGLXUVFlagMaps[TEXTURE_UV_FLAG_CLAMP].realFlag = GL_CLAMP;
    }

    glVertexPointer( 4, GL_FLOAT, sizeof(float)*5, &(g_vtxProjected5[0][0]) );
    OPENGL_CHECK_ERRORS;
    glEnableClientState( GL_VERTEX_ARRAY );
    OPENGL_CHECK_ERRORS;

    if( m_bMultiTexture )
    {
        pglClientActiveTextureARB( GL_TEXTURE0_ARB );
        OPENGL_CHECK_ERRORS;
        glTexCoordPointer( 2, GL_FLOAT, sizeof( TLITVERTEX ), &(g_vtxBuffer[0].tcord[0].u) );
        OPENGL_CHECK_ERRORS;
        glEnableClientState( GL_TEXTURE_COORD_ARRAY );
        OPENGL_CHECK_ERRORS;

        pglClientActiveTextureARB( GL_TEXTURE1_ARB );
        OPENGL_CHECK_ERRORS;
        glTexCoordPointer( 2, GL_FLOAT, sizeof( TLITVERTEX ), &(g_vtxBuffer[0].tcord[1].u) );
        OPENGL_CHECK_ERRORS;
        glEnableClientState( GL_TEXTURE_COORD_ARRAY );
        OPENGL_CHECK_ERRORS;
    }
    else
    {
        glTexCoordPointer( 2, GL_FLOAT, sizeof( TLITVERTEX ), &(g_vtxBuffer[0].tcord[0].u) );
        OPENGL_CHECK_ERRORS;
        glEnableClientState( GL_TEXTURE_COORD_ARRAY );
        OPENGL_CHECK_ERRORS;
    }

    if (m_bSupportFogCoordExt)
    {
        pglFogCoordPointerEXT( GL_FLOAT, sizeof(float)*5, &(g_vtxProjected5[0][4]) );
        OPENGL_CHECK_ERRORS;
        glEnableClientState( GL_FOG_COORDINATE_ARRAY_EXT );
        OPENGL_CHECK_ERRORS;
        glFogi( GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT );
        OPENGL_CHECK_ERRORS;
        glFogi(GL_FOG_MODE, GL_LINEAR); // Fog Mode
        OPENGL_CHECK_ERRORS;
        glFogf(GL_FOG_DENSITY, 1.0f); // How Dense Will The Fog Be
        OPENGL_CHECK_ERRORS;
        glHint(GL_FOG_HINT, GL_FASTEST); // Fog Hint Value
        OPENGL_CHECK_ERRORS;
        glFogi( GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT );
        OPENGL_CHECK_ERRORS;
        glFogf( GL_FOG_START, 0.0f );
        OPENGL_CHECK_ERRORS;
        glFogf( GL_FOG_END, 1.0f );
        OPENGL_CHECK_ERRORS;
    }

    //glColorPointer( 1, GL_UNSIGNED_BYTE, sizeof(TLITVERTEX), &g_vtxBuffer[0].r);
    glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(uint8)*4, &(g_oglVtxColors[0][0]) );
    OPENGL_CHECK_ERRORS;
    glEnableClientState( GL_COLOR_ARRAY );
    OPENGL_CHECK_ERRORS;

    if( pcontext->IsExtensionSupported("GL_NV_depth_clamp") )
    {
        glEnable(GL_DEPTH_CLAMP_NV);
        OPENGL_CHECK_ERRORS;
    }

#elif SDL_VIDEO_OPENGL_ES2
    OGLXUVFlagMaps[TEXTURE_UV_FLAG_MIRROR].realFlag = GL_MIRRORED_REPEAT;
    m_bSupportClampToEdge = true;
    OGLXUVFlagMaps[TEXTURE_UV_FLAG_CLAMP].realFlag = GL_CLAMP_TO_EDGE;

    glVertexAttribPointer(VS_POSITION,4,GL_FLOAT,GL_FALSE,sizeof(float)*5,&(g_vtxProjected5[0][0]));
    OPENGL_CHECK_ERRORS;

    if( m_bMultiTexture )
    {
        glVertexAttribPointer(VS_TEXCOORD0,2,GL_FLOAT,GL_FALSE, sizeof( TLITVERTEX ), &(g_vtxBuffer[0].tcord[0].u));
        OPENGL_CHECK_ERRORS;
        glVertexAttribPointer(VS_TEXCOORD1,2,GL_FLOAT,GL_FALSE, sizeof( TLITVERTEX ), &(g_vtxBuffer[0].tcord[1].u));
        OPENGL_CHECK_ERRORS;
    }
    else
    {
        glVertexAttribPointer(VS_TEXCOORD0,2,GL_FLOAT,GL_FALSE, sizeof( TLITVERTEX ), &(g_vtxBuffer[0].tcord[0].u));
        OPENGL_CHECK_ERRORS;
    }
	
	if (m_bSupportFogCoordExt)
	{
	    glVertexAttribPointer(VS_FOG,1,GL_FLOAT,GL_FALSE,sizeof(float)*5,&(g_vtxProjected5[0][4]));
	    OPENGL_CHECK_ERRORS;
	}
	
    glVertexAttribPointer(VS_COLOR, 4, GL_UNSIGNED_BYTE,GL_TRUE, sizeof(uint8)*4, &(g_oglVtxColors[0][0]) );
    OPENGL_CHECK_ERRORS;
#endif

#ifdef PAULSCODE
//    hardwareType = Android_JNI_GetHardwareType();
#endif
}
Ejemplo n.º 21
0
  void output(vsx_module_param_abs* param)
  {
    VSX_UNUSED(param);
    //printf("mesh_out\n");
    glGetFloatv(GL_LINE_WIDTH,&prev_width);

    glLineWidth(line_width->get());
    #ifndef VSXU_OPENGL_ES
    glEnable(GL_LINE_SMOOTH);
    #endif
    mesh = mesh_in->get_addr();
    if (mesh) 
    {
        if (center->get()) {
          vsx_color l_center_color = vsx_color__(center_color->get(0)+center_color_add->get(0),center_color->get(1)+center_color_add->get(1),center_color->get(2)+center_color_add->get(2),center_color->get(3)+center_color_add->get(3));
					vsx_color main_color = vsx_color__(base_color->get(0)+base_color_add->get(0),base_color->get(1)+base_color_add->get(1),base_color->get(2)+base_color_add->get(2),base_color->get(3)+base_color_add->get(3));
					#ifdef VSXU_OPENGL_ES_1_0
					GLfloat fan_vertices[] = {
						0,0,0,
						0,0,0,
					};
					GLfloat fan_colors[] = {
						l_center_color.r,l_center_color.g,l_center_color.b,l_center_color.a,
						main_color.r,main_color.g,main_color.b,main_color.a,
					};
					glDisableClientState(GL_TEXTURE_COORD_ARRAY);
					glEnableClientState(GL_VERTEX_ARRAY);
					glEnableClientState(GL_COLOR_ARRAY);
					glVertexPointer(3, GL_FLOAT, 0, fan_vertices);
					glColorPointer(4, GL_FLOAT, 0, fan_colors);
					#endif
					#ifdef VSXU_OPENGL_ES_2_0
					//TODO
					#endif
					
					#ifndef VSXU_OPENGL_ES
					glBegin(GL_LINES);
					#endif
          if (override_base_color->get()) {
            
            for (unsigned long i = 0; i < (*mesh)->data->vertices.size(); ++i) {
              #ifdef VSXU_OPENGL_ES_1_0
                fan_vertices[3] = (*mesh)->data->vertices[i].x;
                fan_vertices[4] = (*mesh)->data->vertices[i].y;
                fan_vertices[5] = (*mesh)->data->vertices[i].z;
								glDrawArrays(GL_LINES, 0, 2);
							#endif
							#ifdef VSXU_OPENGL_ES_2_0
							//TODO
							#endif
							#ifndef VSXU_OPENGL_ES
								l_center_color.gl_color();
								glVertex3f(0.0f,0.0f,0.0f);
								main_color.gl_color();
								glVertex3f((*mesh)->data->vertices[i].x,(*mesh)->data->vertices[i].y,(*mesh)->data->vertices[i].z);
							#endif
            }
          } else {
            for (unsigned long i = 0; i < (*mesh)->data->vertices.size(); ++i) {
              #ifdef VSXU_OPENGL_ES_1_0
                fan_vertices[3] = (*mesh)->data->vertices[i].x;
                fan_vertices[4] = (*mesh)->data->vertices[i].y;
                fan_vertices[5] = (*mesh)->data->vertices[i].z;
                fan_colors[4] = (*mesh)->data->vertex_colors[i].r;
                fan_colors[5] = (*mesh)->data->vertex_colors[i].g;
                fan_colors[6] = (*mesh)->data->vertex_colors[i].b;
                fan_colors[7] = (*mesh)->data->vertex_colors[i].a;
								glDrawArrays(GL_LINES, 0, 2);
							#endif
							#ifdef VSXU_OPENGL_ES_2_0
							#endif
							
							#ifndef VSXU_OPENGL_ES
								l_center_color.gl_color();
								glVertex3f(0.0f,0.0f,0.0f);
								(*mesh)->data->vertex_colors[i].gl_color();
								glVertex3f((*mesh)->data->vertices[i].x,(*mesh)->data->vertices[i].y,(*mesh)->data->vertices[i].z);
							#endif
            }
          }
        } // center->get()
        else
        {
          #ifndef VSXU_OPENGL_ES
          glBegin(GL_LINE_STRIP);
          #endif
          #ifdef VSXU_OPENGL_ES_1_0
            glDisableClientState(GL_TEXTURE_COORD_ARRAY);
            if (override_base_color->get()) {
              glColor4f(base_color->get(0)+base_color_add->get(0),base_color->get(1)+base_color_add->get(1),base_color->get(2)+base_color_add->get(2),base_color->get(3)+base_color_add->get(3));
              glDisableClientState(GL_COLOR_ARRAY);
            } else {
              glEnableClientState(GL_COLOR_ARRAY);
              glColorPointer(4, GL_FLOAT, 0, mesh->data->vertex_colors.get_pointer());
            }
            glEnableClientState(GL_VERTEX_ARRAY);
            glVertexPointer(3, GL_FLOAT, 0, mesh->data->vertices.get_pointer());
            glDrawArrays(GL_LINE_STRIP,0,mesh->data->vertices.size());
          #endif
          #ifdef VSXU_OPENGL_ES_2_0
          //TODO
          #endif
					
          #ifndef VSXU_OPENGL_ES
          if (override_base_color->get()) {
            glColor4f(base_color->get(0)+base_color_add->get(0),base_color->get(1)+base_color_add->get(1),base_color->get(2)+base_color_add->get(2),base_color->get(3)+base_color_add->get(3));
            for (unsigned long i = 0; i < (*mesh)->data->vertices.size(); ++i) {
              glVertex3f((*mesh)->data->vertices[i].x,(*mesh)->data->vertices[i].y,(*mesh)->data->vertices[i].z);
            }
          } else
          {
            for (unsigned long i = 0; i < (*mesh)->data->vertices.size(); ++i) {
              if ((*mesh)->data->vertex_colors.size())
              (*mesh)->data->vertex_colors[i].gl_color();
              glVertex3f((*mesh)->data->vertices[i].x,(*mesh)->data->vertices[i].y,(*mesh)->data->vertices[i].z);
            }
          }
          #endif
        }
      #ifndef VSXU_OPENGL_ES_2_0
      glEnd();
      #endif
      render_out->set(1);
    } else
    render_out->set(0);
  }
Ejemplo n.º 22
0
void CGutModel_OpenGL::RenderMesh(bool bSubmitMaterial)
{
	glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT);

	for ( int i=0; i<m_iNumMeshes; i++ )
	{
		sModelMesh_OpenGL *pMesh = m_pMeshArray + i;

		for ( int j=0; j<pMesh->m_iNumVertexChunks; j++ )
		{
			sModelVertexChunk_OpenGL *pVertexChunk = pMesh->m_pVertexChunk + j;
			sVertexDecl *pVertexDecl = &pVertexChunk->m_VertexDecl;

			glBindBuffer(GL_ARRAY_BUFFER, pVertexChunk->m_VertexBufferID);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pVertexChunk->m_IndexBufferID);

			if ( pVertexDecl->m_iPositionOffset >= 0 )
			{
				glEnableClientState(GL_VERTEX_ARRAY);
				glVertexPointer(pVertexDecl->m_iNumPositionElements, GL_FLOAT, pVertexDecl->m_iVertexSize, (GLvoid *) pVertexDecl->m_iPositionOffset);
			}
			else
			{
				glDisableClientState(GL_VERTEX_ARRAY);
			}

			if ( pVertexDecl->m_iNormalOffset >= 0 )
			{
				glEnableClientState(GL_NORMAL_ARRAY);
				glNormalPointer(GL_FLOAT, pVertexDecl->m_iVertexSize, (GLvoid *) pVertexDecl->m_iNormalOffset);
			}
			else
			{
				glDisableClientState(GL_NORMAL_ARRAY);
			}

			if ( pVertexDecl->m_iColorOffset >= 0 )
			{
				glEnableClientState(GL_COLOR_ARRAY);
				glColorPointer(pVertexDecl->m_iNumColorElements, GL_UNSIGNED_BYTE, pVertexDecl->m_iVertexSize, (GLvoid *) pVertexDecl->m_iColorOffset);
			}
			else
			{
				glDisableClientState(GL_COLOR_ARRAY);
			}

			for (int l=0; l<pVertexChunk->m_iNumBatches; l++ )
			{
				sModelBatch *pBatch = pVertexChunk->m_pBatchArray + l;
				
				if ( bSubmitMaterial && pBatch->m_iMaterialID >= 0 )
				{
					m_pMaterialArray[pBatch->m_iMaterialID].Submit(pVertexChunk);
				}

				// OpenGL 1.1+
				//int *ip = (int *) (pBatch->m_iIndexArrayBegin * 2);
				//glDrawElements(GL_TRIANGLES, pBatch->m_iNumPrimitives * 3, GL_UNSIGNED_SHORT, ip);
				
				// OpenGL 1.2+
				glDrawRangeElements(GL_TRIANGLES, pBatch->m_iIndexArrayBegin, pBatch->m_iIndexArrayEnd, 
					pBatch->m_iNumIndices, GL_UNSIGNED_SHORT, 0);
			}

		}
	}

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	glPopClientAttrib();
}
Ejemplo n.º 23
0
//
// Bind data to GL
//
bool cgfxVaryingParameter::bind( const float* data, int stride) const
{
	bool result = false;
	switch( fGLType)
	{
		case glRegister::kPosition:
			glStateCache::instance().enablePosition();
			glVertexPointer( stride, GL_FLOAT, 0, data);
			result = true;
			break;

		case glRegister::kNormal:
			if( stride == 3)
			{
				glStateCache::instance().enableNormal();
				glNormalPointer( GL_FLOAT, 0, data);
				result = true;
			}
			break;

		case glRegister::kTexCoord:
			if( fGLIndex < glStateCache::sMaxTextureUnits)
			{
				glStateCache::instance().enableAndActivateTexCoord( fGLIndex);
				glTexCoordPointer( stride, GL_FLOAT, 0, data);
				result = true;
			}
			break;

		case glRegister::kColor:
			if( stride > 2)
			{
				glStateCache::instance().enableColor();
				glColorPointer( stride, GL_FLOAT, 0, data);
				result = true;
			}
			break;

		case glRegister::kSecondaryColor:
			if( stride > 2)
			{
				glStateCache::instance().enableSecondaryColor();
				if( glStateCache::glVertexAttribPointer) 
					glStateCache::glSecondaryColorPointer( stride, GL_FLOAT, 0, (GLvoid*)data);
				result = true;
			}
			break;

		case glRegister::kVertexAttrib:
			glStateCache::instance().enableVertexAttrib( fGLIndex);
			if( glStateCache::glVertexAttribPointer) 
				glStateCache::glVertexAttribPointer( fGLIndex, stride, GL_FLOAT, GL_FALSE, 0, data);
			result = true;
			break;

		/// TODO add secondaryColor, vertexWeight, vertexAttrib, fog
		default:
			break;
	}
	return result;
}
Ejemplo n.º 24
0
void RenderTarget::draw(const Vertex* vertices, unsigned int vertexCount,
                        PrimitiveType type, const RenderStates& states)
{
    // Nothing to draw?
    if (!vertices || (vertexCount == 0))
        return;

    if (activate(true))
    {
        // First set the persistent OpenGL states if it's the very first call
        if (!m_cache.glStatesSet)
            resetGLStates();

        // Check if the vertex count is low enough so that we can pre-transform them
        bool useVertexCache = (vertexCount <= StatesCache::VertexCacheSize);
        if (useVertexCache)
        {
            // Pre-transform the vertices and store them into the vertex cache
            for (unsigned int i = 0; i < vertexCount; ++i)
            {
                Vertex& vertex = m_cache.vertexCache[i];
                vertex.position = states.transform * vertices[i].position;
                vertex.color = vertices[i].color;
                vertex.texCoords = vertices[i].texCoords;
            }

            // Since vertices are transformed, we must use an identity transform to render them
            if (!m_cache.useVertexCache)
                applyTransform(Transform::Identity);
        }
        else
        {
            applyTransform(states.transform);
        }

        // Apply the view
        if (m_cache.viewChanged)
            applyCurrentView();

        // Apply the blend mode
        if (states.blendMode != m_cache.lastBlendMode)
            applyBlendMode(states.blendMode);

        // Apply the texture
        Uint64 textureId = states.texture ? states.texture->m_cacheId : 0;
        if (textureId != m_cache.lastTextureId)
            applyTexture(states.texture);

        // Apply the shader
        if (states.shader)
            applyShader(states.shader);

        // If we pre-transform the vertices, we must use our internal vertex cache
        if (useVertexCache)
        {
            // ... and if we already used it previously, we don't need to set the pointers again
            if (!m_cache.useVertexCache)
                vertices = m_cache.vertexCache;
            else
                vertices = NULL;
        }

        // Setup the pointers to the vertices' components
        if (vertices)
        {
            const char* data = reinterpret_cast<const char*>(vertices);
            glCheck(glVertexPointer(2, GL_FLOAT, sizeof(Vertex), data + 0));
            glCheck(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), data + 8));
            glCheck(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), data + 12));
        }

        // Find the OpenGL primitive type
        static const GLenum modes[] = {GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES,
                                       GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS
                                      };
        GLenum mode = modes[type];

        // Draw the primitives
        glCheck(glDrawArrays(mode, 0, vertexCount));

        // Unbind the shader, if any
        if (states.shader)
            applyShader(NULL);

        // Update the cache
        m_cache.useVertexCache = useVertexCache;
    }
}
Ejemplo n.º 25
0
int main()
{
    Parms_t input;
/*
    input.width = 10;
    input.height = 10;
    input.fullscreen = 0;//SDL_WINDOW_FULLSCREEN;
    input.windowH = 200;
    input.windowW = 200;
    input.animationDelay = 0;
    input.framesDrop = 1;
    input.startPoint.x = 1;
    input.startPoint.y = 1;
    input.exitPoint.x  = 7;
    input.exitPoint.y  = 7;
*/
    Parms_t      last;
    bool         quit = false;
    Data_t       d;
    RenderData_t rd;

    srand(clock());

    //инициализация SDL2
    SDL_Init(SDL_INIT_VIDEO);
    input = getInput(1, ALL, input);
    SDL_Window   *window   = SDL_CreateWindow("Labytinth", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, input.windowW, input.windowH, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | input.fullscreen | SDL_WINDOW_BORDERLESS);
    SDL_GL_CreateContext(window);
    SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    SDL_Event event;

    //OpenGL 4.1
    glMatrixMode(GL_PROJECTION|GL_MODELVIEW);
    glLoadIdentity();
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glOrtho(-input.windowW/2,input.windowW/2,input.windowH/2,-input.windowH/2,0,1);
    glClearColor( 1, 1, 1, 0 );
    SDL_GL_SetSwapInterval( 1 ); //vsync

    uint8_t *data;
    bool     flagChanged = 0;
    Action_t flagAction = NOTHING;
    bool     flagGenerated = 0;
    bool     flagGeneratorData   = 0;
    bool     flagSolverData   = 0;
    uint16_t i = 0;


    glClear(GL_COLOR_BUFFER_BIT);
    SDL_GL_SwapWindow(window);

    while(!quit){
        while(SDL_PollEvent(&event)){
            if(event.type == SDL_QUIT)
                quit = true;

            else if (event.type == SDL_KEYDOWN){
                    switch (event.key.keysym.sym){
                case  SDLK_g:      flagAction = GENERATE;      break;
                case  SDLK_s:      flagAction = SOLVE;         break;
                case  SDLK_TAB:    flagAction = STOP;          break;
                case  SDLK_ESCAPE: quit = 1;                   break;
                case  SDLK_UP:     input.framesDrop++;         break;
                case  SDLK_RIGHT:  input.animationDelay++;
                case  SDLK_DOWN:   input.framesDrop = (input.framesDrop - 1 > 0) ? input.framesDrop - 1 : 1;
                                   break;
                case  SDLK_LEFT:   input.animationDelay = (input.animationDelay - 1 >= 0) ? input.animationDelay - 1 : 0;
                                   break;
                }
            }
        }
        if(flagAction == GENERATE){
            if(!flagGeneratorData){
                d                 = initGeneratorData(input.width, input.height, input.startPoint);
                rd                = initRenderData(d, input.windowW, input.windowH);
                flagGeneratorData = true;
                flagGenerated     = false;
                flagSolverData    = false;

                glVertexPointer(2, GL_FLOAT, sizeof(Vertex_t), rd.vertices);
                glColorPointer(3, GL_UNSIGNED_BYTE, sizeof(VertexColor_t), rd.verticesColor);

            }
            for(i = 0; i < input.framesDrop; i++){
                if(d.unvisitedNum != 0){
                    generateStep(&d);
                }
                else{
                    flagGeneratorData = false;
                    flagGenerated     = true;
                    flagAction        = NOTHING;
                    break;
                }
            }
            d.maze[d.startPoint.y][d.startPoint.x] = CURRENT;
            renderMatrix(d.maze, rd, GENERATE);
            d.maze[d.startPoint.y][d.startPoint.x] = GENVISITED;
            flagChanged = true;
        }
        else if(flagAction == SOLVE && flagGenerated){
            if(!flagSolverData){
                d = initSeekerData(d, input.startPoint, input.exitPoint);
                rd = clearSeekerColorArray(d.maze, rd);
                flagSolverData = true;
            }
            for(i = 0; i < input.framesDrop; i++){
                if((d.startPoint.x != d.exitPoint.x || d.startPoint.y != d.exitPoint.y) && d.error != 1){
                    seekStep(&d);
                }
                else if(d.error){
                    printf("ERROR: Lanyrinth cannot be solved! :C\n");
                }
                else{
                    flagSolverData = false;
                    flagAction = NOTHING;
                    setMode(d.exitPoint, d.maze, WAY);
                    break;
                }
            }
            setMode(d.startPoint, d.maze, CURRENT);
            renderMatrix(d.maze, rd, SOLVE);
            setMode(d.startPoint, d.maze, WAY);
            flagChanged = true;
        }
        else if(flagAction == STOP){
            last = input;
            input = getInput(0, GENERATE, last);
            if((last.width != input.width) || (last.height != input.height)){
                flagGenerated     = false;
                flagGeneratorData = false;
                flagSolverData    = false;
            }
            flagAction  = NOTHING;
            flagChanged = true;
        }
        else if(flagAction == OUTPUT){
            data = malloc(input.windowW * input.windowH * 4 * sizeof(uint8_t));
            glReadBuffer(GL_FRONT);
            glReadPixels(0, 0, input.windowW , input.windowH,  GL_RGBA, GL_UNSIGNED_BYTE, data);
            flagAction = NOTHING;

        }
        if(flagAction != NOTHING || flagChanged){
            SDL_Delay(input.animationDelay);
            SDL_GL_SwapWindow(window);
            flagChanged = false;
        }
    }

    //cleanup
    wipe(d.stack);
    return 0;
}
Ejemplo n.º 26
0
/*
 *  OpenGL (GLUT) calls this routine to display the scene
 */
void display()
{
   const double len=2.5;  //  Length of axes
   double Ex = -2*dim*Sin(th)*Cos(ph);
   double Ey = +2*dim        *Sin(ph);
   double Ez = +2*dim*Cos(th)*Cos(ph);

   //  Erase the window and the depth buffer
   glClear(GL_COLOR_BUFFER_BIT);
   //  Undo previous transformations
   glLoadIdentity();
   //  Perspective - set eye position
   gluLookAt(Ex,Ey,Ez , 0,0,0 , 0,Cos(ph),0);

   //  Integrate
   Step();

   //  Set shader
   glUseProgram(shader);
   int id = glGetUniformLocation(shader,"star");
   if (id>=0) glUniform1i(id,0);
   id = glGetUniformLocation(shader,"size");
   if (id>=0) glUniform1f(id,0.1);
   glBlendFunc(GL_ONE,GL_ONE);
   glEnable(GL_BLEND);

   //  Draw stars using vertex arrays
   glEnableClientState(GL_VERTEX_ARRAY);
   glEnableClientState(GL_COLOR_ARRAY);
   glVertexPointer(3,GL_FLOAT,sizeof(float3),pos[src]);
   glColorPointer(3,GL_FLOAT,sizeof(Color),col);
   //  Draw all stars
   glDrawArrays(GL_POINTS,0,N);
   //  Disable vertex arrays
   glDisableClientState(GL_VERTEX_ARRAY);
   glDisableClientState(GL_COLOR_ARRAY);

   //  Unset shader
   glUseProgram(0);
   glDisable(GL_BLEND);

   //  Draw axes
   glDisable(GL_LIGHTING);
   glColor3f(1,1,1);
   if (axes)
   {
      glBegin(GL_LINES);
      glVertex3d(0.0,0.0,0.0);
      glVertex3d(len,0.0,0.0);
      glVertex3d(0.0,0.0,0.0);
      glVertex3d(0.0,len,0.0);
      glVertex3d(0.0,0.0,0.0);
      glVertex3d(0.0,0.0,len);
      glEnd();
      //  Label axes
      glRasterPos3d(len,0.0,0.0);
      Print("X");
      glRasterPos3d(0.0,len,0.0);
      Print("Y");
      glRasterPos3d(0.0,0.0,len);
      Print("Z");
   }
   //  Display parameters
   glWindowPos2i(5,5);
   Print("FPS=%d Angle=%d,%d Mode=%s",
      FramesPerSecond(),th,ph,text[mode]);
   //  Render the scene and make it visible
   ErrCheck("display");
   glFlush();
   glutSwapBuffers();
}
Ejemplo n.º 27
0
void
__glXDisp_DrawArrays(GLbyte * pc)
{
    __GLXdispatchDrawArraysHeader *hdr = (__GLXdispatchDrawArraysHeader *) pc;
    __GLXdispatchDrawArraysComponentHeader *compHeader;
    GLint numVertexes = hdr->numVertexes;
    GLint numComponents = hdr->numComponents;
    GLenum primType = hdr->primType;
    GLint stride = 0;
    int i;

    pc += sizeof(__GLXdispatchDrawArraysHeader);
    compHeader = (__GLXdispatchDrawArraysComponentHeader *) pc;

    /* compute stride (same for all component arrays) */
    for (i = 0; i < numComponents; i++) {
        GLenum datatype = compHeader[i].datatype;
        GLint numVals = compHeader[i].numVals;

        stride += __GLX_PAD(numVals * __glXTypeSize(datatype));
    }

    pc += numComponents * sizeof(__GLXdispatchDrawArraysComponentHeader);

    /* set up component arrays */
    for (i = 0; i < numComponents; i++) {
        GLenum datatype = compHeader[i].datatype;
        GLint numVals = compHeader[i].numVals;
        GLenum component = compHeader[i].component;

        switch (component) {
        case GL_VERTEX_ARRAY:
            glEnableClientState(GL_VERTEX_ARRAY);
            glVertexPointer(numVals, datatype, stride, pc);
            break;
        case GL_NORMAL_ARRAY:
            glEnableClientState(GL_NORMAL_ARRAY);
            glNormalPointer(datatype, stride, pc);
            break;
        case GL_COLOR_ARRAY:
            glEnableClientState(GL_COLOR_ARRAY);
            glColorPointer(numVals, datatype, stride, pc);
            break;
        case GL_INDEX_ARRAY:
            glEnableClientState(GL_INDEX_ARRAY);
            glIndexPointer(datatype, stride, pc);
            break;
        case GL_TEXTURE_COORD_ARRAY:
            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            glTexCoordPointer(numVals, datatype, stride, pc);
            break;
        case GL_EDGE_FLAG_ARRAY:
            glEnableClientState(GL_EDGE_FLAG_ARRAY);
            glEdgeFlagPointer(stride, (const GLboolean *) pc);
            break;
        case GL_SECONDARY_COLOR_ARRAY:
        {
            PFNGLSECONDARYCOLORPOINTERPROC SecondaryColorPointerEXT =
                __glGetProcAddress("glSecondaryColorPointerEXT");
            glEnableClientState(GL_SECONDARY_COLOR_ARRAY);
            SecondaryColorPointerEXT(numVals, datatype, stride, pc);
            break;
        }
        case GL_FOG_COORD_ARRAY:
        {
            PFNGLFOGCOORDPOINTERPROC FogCoordPointerEXT =
                __glGetProcAddress("glFogCoordPointerEXT");
            glEnableClientState(GL_FOG_COORD_ARRAY);
            FogCoordPointerEXT(datatype, stride, pc);
            break;
        }
        default:
            break;
        }

        pc += __GLX_PAD(numVals * __glXTypeSize(datatype));
    }

    glDrawArrays(primType, 0, numVertexes);

    /* turn off anything we might have turned on */
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_INDEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_EDGE_FLAG_ARRAY);
    glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
    glDisableClientState(GL_FOG_COORD_ARRAY);
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen;
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL );
    if ( !screen ) {
        printf("Unable to set video mode: %s\n", SDL_GetError());
        return 1;
    }
    
    glClearColor( 0, 0, 0, 0 );
    glClear( GL_COLOR_BUFFER_BIT );

    // Create a texture

    GLuint texture;
    glGenTextures( 1, &texture );
    glBindTexture( GL_TEXTURE_2D, texture );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte textureData[16*16*4];
    for (int x = 0; x < 16; x++) {
      for (int y = 0; y < 16; y++) {
        *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8);
      }
    }
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, 
                  GL_RGBA, GL_UNSIGNED_BYTE, textureData );

    // Create a second texture

    GLuint texture2;
    glGenTextures( 1, &texture2 );
    glBindTexture( GL_TEXTURE_2D, texture2 );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    GLubyte texture2Data[] = { 0xff,    0,    0, 0xff,
                                  0, 0xff,    0, 0xaa,
                                  0,    0, 0xff, 0x55,
                               0x80, 0x90, 0x70,    0 };
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0,
                  GL_RGBA, GL_UNSIGNED_BYTE, texture2Data );
    
    // BEGIN

#if USE_GLEW
    glewInit();
#endif

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048);
    glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048);
    glRotatef(-30, 1, 1, 1);
    //GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 };
    //glLoadMatrixf(pm);

    glMatrixMode(GL_MODELVIEW);
    GLfloat matrixData[] = { -1, 0, 0, 0,
                              0, 0,-1, 0,
                              0, 1, 0, 0,
                              0, 0, 0, 1 };
    glLoadMatrixf(matrixData);
    //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);

    glClear(GL_DEPTH_BUFFER_BIT);

    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glActiveTexture(GL_TEXTURE0);

    glEnableClientState(GL_VERTEX_ARRAY);

    GLuint arrayBuffer, elementBuffer;
    glGenBuffers(1, &arrayBuffer);
    glGenBuffers(1, &elementBuffer);

    GLubyte arrayData[] = {
/*
[0, 0,   0, 67] ==>  128 float
[0, 0, 128, 67] ==>  256 float
[0, 0,   0, 68] ==>  512 float
[0, 0, 128, 68] ==> 1024 float

[vertex x        ] [vertex y         ] [vertex z         ] [nr]                [texture u        ] [texture v        ] [lm u   ] [lm v   ] [color r,g,b,a    ] */
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,  11,   10,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  0
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,  23,   20,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  1
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  35,   30,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  2
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,  47,   40,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  3
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,  51,   50,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  4
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,  64,   60,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128, //  5
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,  70,   70,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  6
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  89,   80,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  7
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,  94,   90,   0,   0,   0,   0,   0,   0,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  8
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  20,   10,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, //  9
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,  31,   20,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 10
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,  42,   30,   0,   0,   0,   0,   0,   0,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 11
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,  53,   40,   0,   0,   0,   0,   0,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 12
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,  64,   50,   0,   0,   0,   0, 128,  67,   0,   0,   0,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 13
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,  75,   60,   0,   0,   0,   0, 128,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 14
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,  86,   70,   0,   0,   0,   0,   0,  67,   0,   0, 128,  67,   0,   0,   0,   0, 128, 128, 128, 128, // 15

  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,   0,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0,   0,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0, 128,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128,
  0,   0, 128,  68,   0,   0, 128,  68,   0,   0,   0,  68,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 128, 128, 128, 128
    };
    assert(sizeof(arrayData) == 1408);
    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 };
    assert(sizeof(elementData) == 48);

    glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer);

    // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B
    glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound
    glTexCoordPointer(2, GL_FLOAT, 32, (void*)16);
    glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build
    glTexCoordPointer(2, GL_SHORT, 32, (void*)24);
    glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup
    glNormalPointer(GL_BYTE, 32, (void*)12);
    glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28);

    glBindTexture(GL_TEXTURE_2D, texture); // diffuse?
    glActiveTexture(GL_TEXTURE0);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, texture2); // lightmap?
    glActiveTexture(GL_TEXTURE0);

    GLint ok;

    const char *vertexShader = "uniform vec4 texgenscroll;\n"
                               "void main(void)\n"
                               "{\n"
                               "    gl_Position = ftransform();\n"
                               "    gl_TexCoord[0].xy = gl_MultiTexCoord0.xy/10000.0 + (0.001*texgenscroll.xy) + gl_Normal.xy;\n" // added /100 here
                               "    gl_TexCoord[1].xy = gl_MultiTexCoord1.xy/100.0 * 3.051851e-05;\n"
                               "}\n";
    const char *fragmentShader = "uniform vec4 colorparams;\n"
                                 "uniform sampler2D diffusemap, lightmap;\n"
                                 "void main(void)\n"
                                 "{\n"
                                 "    vec4 diffuse = texture2D(diffusemap, gl_TexCoord[0].xy);\n"
                                 "    vec4 lm = texture2D(lightmap, gl_TexCoord[1].xy);\n"
                                 "    diffuse *= colorparams;\n"
                                 "    gl_FragColor = diffuse * lm;\n"
                                 "}\n";

    GLuint vs = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vs, 1, &vertexShader, NULL);
    glCompileShader(vs);
    glGetShaderiv(vs, GL_COMPILE_STATUS, &ok);
    assert(ok);

    GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fs, 1, &fragmentShader, NULL);
    glCompileShader(fs);
    glGetShaderiv(fs, GL_COMPILE_STATUS, &ok);
    assert(ok);

    GLuint program = glCreateProgram();

    glAttachShader(program, vs);
    glAttachShader(program, fs);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    assert(ok);

    glUseProgram(program);

    GLint lightmapLocation = glGetUniformLocation(program, "lightmap");
    assert(lightmapLocation >= 0);
    glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit?

    GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap");
    assert(diffusemapLocation >= 0);
    glUniform1i(diffusemapLocation, 0);

    GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll");
    assert(texgenscrollLocation >= 0);

    GLint colorparamsLocation = glGetUniformLocation(program, "colorparams");
    assert(colorparamsLocation >= 0);

    GLfloat texgenscrollData[] = { 0, 0, 0, 0 };
    glUniform4fv(texgenscrollLocation, 1, texgenscrollData);

    GLfloat colorparamsData[] = { 2, 2, 2, 1 };
    glUniform4fv(colorparamsLocation, 1, colorparamsData);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[12/sizeof(GLushort)]);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[ 0/sizeof(GLushort)]);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[24/sizeof(GLushort)]);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)&elementData[36/sizeof(GLushort)]);

    // END

    SDL_GL_SwapBuffers();

  
#ifndef __EMSCRIPTEN__
    SDL_Delay(1500);
#endif

    SDL_Quit();
    
    return 0;
}
Ejemplo n.º 29
0
// overriding draw method
void CCParticleSystemQuad::draw()
{	CCParticleSystem::draw();

	// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
	// Needed states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
	// Unneeded states: -
	glBindTexture(GL_TEXTURE_2D, m_pTexture->getName());

#define kQuadSize sizeof(m_pQuads[0].bl)

#if CC_USES_VBO
    ccglBindBuffer(GL_ARRAY_BUFFER, m_uQuadsID);

#if CC_ENABLE_CACHE_TEXTTURE_DATA
    ccglBufferData(GL_ARRAY_BUFFER, sizeof(m_pQuads[0])*m_uTotalParticles, m_pQuads, GL_DYNAMIC_DRAW);	
#endif

	glVertexPointer(2,GL_FLOAT, kQuadSize, 0);

	glColorPointer(4, GL_UNSIGNED_BYTE, kQuadSize, (GLvoid*) offsetof(ccV2F_C4B_T2F,colors) );

	glTexCoordPointer(2, GL_FLOAT, kQuadSize, (GLvoid*) offsetof(ccV2F_C4B_T2F,texCoords) );
#else   // vertex array list

    int offset = (int) m_pQuads;

    // vertex
    int diff = offsetof( ccV2F_C4B_T2F, vertices);
    glVertexPointer(2,GL_FLOAT, kQuadSize, (GLvoid*) (offset+diff) );

    // color
    diff = offsetof( ccV2F_C4B_T2F, colors);
    glColorPointer(4, GL_UNSIGNED_BYTE, kQuadSize, (GLvoid*)(offset + diff));

    // tex coords
    diff = offsetof( ccV2F_C4B_T2F, texCoords);
    glTexCoordPointer(2, GL_FLOAT, kQuadSize, (GLvoid*)(offset + diff));		

#endif // ! CC_USES_VBO

    bool newBlend = (m_tBlendFunc.src != CC_BLEND_SRC || m_tBlendFunc.dst != CC_BLEND_DST) ? true : false;
	if( newBlend ) 
	{
		glBlendFunc( m_tBlendFunc.src, m_tBlendFunc.dst );
	}

    CCAssert( m_uParticleIdx == m_uParticleCount, "Abnormal error in particle quad");

	glDrawElements(GL_TRIANGLES, (GLsizei)(m_uParticleIdx*6), GL_UNSIGNED_SHORT, m_pIndices);	

	// restore blend state
	if( newBlend )
		glBlendFunc( CC_BLEND_SRC, CC_BLEND_DST );

#if CC_USES_VBO
	ccglBindBuffer(GL_ARRAY_BUFFER, 0);
#endif

	// restore GL default state
	// -
}
Ejemplo n.º 30
0
void TriangleMeshViewerDisplay::paintGL()
{
  assert(isValid());

  const FloatRGBA bg=background_colour();
  glClearColor(bg.r,bg.g,bg.b,1.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  const float a=parameters->ambient;

  GLfloat global_ambient[]={a,a,a,1.0};
  glLightModelfv(GL_LIGHT_MODEL_AMBIENT,global_ambient);

  GLfloat light_diffuse[]={1.0f-a,1.0f-a,1.0f-a,1.0};
  glLightfv(GL_LIGHT0,GL_DIFFUSE,light_diffuse);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  gluLookAt(
	    camera_position.x,camera_position.y,camera_position.z,
	    camera_lookat.x  ,camera_lookat.y  ,camera_lookat.z,
	    camera_up.x      ,camera_up.y      ,camera_up.z
	    );

  const XYZ light_direction(parameters->illumination_direction());
  GLfloat light_position[]=
    {
      light_direction.x,
      light_direction.y,
      light_direction.z,
      0.0f     // w=0 implies directional light
    };

  glLightfv(GL_LIGHT0,GL_POSITION,light_position);

  glRotatef((180.0/M_PI)*object_tilt,1.0,0.0,0.0);
  glRotatef((180.0/M_PI)*object_rotation,0.0,0.0,1.0);

  glPolygonMode(GL_FRONT_AND_BACK,(parameters->wireframe ? GL_LINE : GL_FILL));

  glEnable(GL_CULL_FACE);
  glFrontFace(GL_CCW);
  
  if (parameters->display_list && gl_display_list_index!=0)
    {
      glCallList(gl_display_list_index);
    }
  else
    {
      bool building_display_list=(parameters->display_list && gl_display_list_index==0);

      if (building_display_list)
	{
	  gl_display_list_index=glGenLists(1);
	  assert(gl_display_list_index!=0);
	  glNewList(gl_display_list_index,GL_COMPILE_AND_EXECUTE);
	  if (_verbose) std::cerr << "Building display list...";
	}

      GLfloat default_material_white[3]={1.0f,1.0f,1.0f};
      GLfloat default_material_black[3]={0.0f,0.0f,0.0f};
      glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,default_material_white);
      glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,default_material_black);

      for (uint m=0;m<mesh.size();m++)
	{
	  const TriangleMesh*const it=mesh[m];
	  if (it==0) continue;

	  // Meshes after the first are rendered twice: first the backfacing polys then the front facing.
	  // This solves the problem of either clouds disappearing when we're under them (with backface culling)
	  // or weird stuff around the periphery when culling is on.
	  // It's quite an expensive solution!  
	  const uint passes=(m==0 ? 1 : 2);
	  for (uint pass=0;pass<passes;pass++)
	    {
	      if (passes==2 && pass==0)
		{
		  glCullFace(GL_FRONT);
		}
	      else
		{
		  glCullFace(GL_BACK);
		}

	      if (it->emissive()==0.0f)
		{
		  if (m) // Switch blending on for non-emissive meshes after the first
		    {
		      glEnable(GL_BLEND);
		      glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
		    }
		  else
		    {
		      glDisable(GL_BLEND);
		    }
		  
		  // Use "Color Material" mode 'cos everything is the same material.... just change the colour
		  glEnable(GL_COLOR_MATERIAL);
		  glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
		  
		  // Point GL at arrays of data
		  glVertexPointer(3,GL_FLOAT,sizeof(Vertex),&(it->vertex(0).position().x));
		  glNormalPointer(GL_FLOAT,sizeof(Vertex),&(it->vertex(0).normal().x));
		  
		  // For a second mesh, use alpha (actually could use it for the first mesh but maybe it's more efficient not to).
		  glColorPointer((m==0 ? 3 : 4),GL_UNSIGNED_BYTE,sizeof(Vertex),&(it->vertex(0).colour(0).r));

		  // Builds on some platforms (ie Ubuntu) seem to get in a mess if you render >1k primitives
		  // (3k vertices).  NB This is a problem in the client; not the xserver.
		  // Debian (Sarge or Etch) has no problems with unlimited batches.
		  // Note it's simply the batch size; there doesn't seem to be any problem with the 10Ks of vertices.
		  // Since the limited batch size doesn't seem to hurt working implementations we just use it everywhere.
		  const uint batch_size=1000;

		  // Draw the colour-zero triangles
		  for (uint t=0;t<it->triangles_of_colour0();t+=batch_size)
		    {
		      glDrawRangeElements
			(
			 GL_TRIANGLES,
			 0,
			 it->vertices()-1,
			 3*std::min(batch_size,static_cast<uint>(it->triangles_of_colour0()-t)),
			 GL_UNSIGNED_INT,
			 &(it->triangle(t).vertex(0))
			 );
		      if (_verbose && building_display_list)
			{
			  std::cerr << ".";
			}
		    }
		  
		  // Switch to alternate colour and draw the colour-one triangles
		  glColorPointer(3,GL_UNSIGNED_BYTE,sizeof(Vertex),&(it->vertex(0).colour(1).r));

		  for (uint t=it->triangles_of_colour0();t<it->triangles();t+=batch_size)
		    {
		      glDrawRangeElements
			(
			 GL_TRIANGLES,
			 0,
			 it->vertices()-1,
			 3*std::min(batch_size,static_cast<uint>(it->triangles()-t)),
			 GL_UNSIGNED_INT,
			 &(it->triangle(t).vertex(0))
			 );
		      if (_verbose && building_display_list)
			{
			  std::cerr << ".";
			}
		    }
		  
		  glDisable(GL_COLOR_MATERIAL);
		}
	      else // implies mesh[m]->emissive()>0.0
		{
		  // We abuse alpha for emission, so no blending
		  glDisable(GL_BLEND);
		  
		  // If there could be emissive vertices, we need to do things the hard way
		  // using immediate mode.  Maybe the display list capture will help.
		  
		  const float k=1.0f/255.0f;
		  const float em=k*(     it->emissive());
		  const float ad=k*(1.0f-it->emissive());
		  
		  glBegin(GL_TRIANGLES);
		  for (unsigned int t=0;t<it->triangles();t++)
		    {
		      if (_verbose && building_display_list && (t&0x3ff) == 0)
			{
			  std::cerr << ".";
			}

		      const uint c=(t<it->triangles_of_colour0() ? 0 : 1);		      
		      for (uint i=0;i<3;i++)
			{
			  const uint vn=it->triangle(t).vertex(i);
			  const Vertex& v=it->vertex(vn);
			  
			  GLfloat c_ad[3];
			  GLfloat c_em[3];
			  if (v.colour(c).a==0)  // Zero alpha used to imply emissive vertex colour
			    {
			      c_ad[0]=v.colour(c).r*ad;
			      c_ad[1]=v.colour(c).g*ad;
			      c_ad[2]=v.colour(c).b*ad;
			      c_em[0]=v.colour(c).r*em;
			      c_em[1]=v.colour(c).g*em;
			      c_em[2]=v.colour(c).b*em;
			    }
			  else
			    {
			      c_ad[0]=v.colour(c).r*k;
			      c_ad[1]=v.colour(c).g*k;
			      c_ad[2]=v.colour(c).b*k;
			      c_em[0]=0.0f;
			      c_em[1]=0.0f;
			      c_em[2]=0.0f;
			    }
			  
			  glNormal3fv(&(v.normal().x));
			  glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,c_ad);
			  glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,c_em);
			  glVertex3fv(&(v.position().x));
			}
		    }
		  glEnd();
		}
	    }
	}
      
      if (building_display_list)
	{
	  glEndList();
	  if (_verbose)
	    {
	      std::cerr << "\n...built display list\n";
	    }
	}
    }

  if (_verbose)
    check_for_gl_errors(__PRETTY_FUNCTION__);

  // Get time taken since last frame
  const uint dt=frame_time.restart();

  // Save it in the queue
  frame_times.push_back(dt);

  // Keep last 30 frame times
  while (frame_times.size()>30) frame_times.pop_front();

  // Only update frame time a couple of times a second to reduce flashing
  if (frame_time_reported.elapsed()>500)
    {    
      //! \todo Frame time calculation is wrong... need -1 correction to number of frames
      const float average_time=std::accumulate
	(
	 frame_times.begin(),
	 frame_times.end(),
	 0
	 )/static_cast<float>(frame_times.size());
      
      const float fps=1000.0/average_time;
      
      std::ostringstream report;
      report.setf(std::ios::fixed);
      report.precision(1);
      
      uint n_triangles=0;
      uint n_vertices=0;
      for (uint m=0;m<mesh.size();m++)
	{
	  if (mesh[m])
	    {
	      n_triangles+=mesh[m]->triangles();
	      n_vertices+=mesh[m]->vertices();
	    }
	}
      report 
	<< "Triangles: " 
	<< n_triangles
	<< ", "
	<< "Vertices: " 
	<< n_vertices 
	<< ", "
	<< "FPS: " 
	<< fps 
	<< "\n";
    
      _notify.notify(report.str());
      frame_time_reported.restart();
    }
}