void OBJWrapper::onDraw(Render& render, const glm::mat4& mvp)
{
	glm::mat4 localMatrix = getMatrix();
	glm::mat4 totalMatrix = mvp * localMatrix;
	for(std::map<std::string, OBJDatas*>::iterator itOBJ = m_objDatas.begin(); itOBJ != m_objDatas.end(); ++itOBJ)
	{
		OBJDatas* currentDatas = itOBJ->second;
		glBindBuffer(GL_ARRAY_BUFFER, currentDatas->vboID);
		{
			for(std::map<std::string, int>::iterator itSeries = currentDatas->materialSerie.begin(); itSeries != currentDatas->materialSerie.end(); itSeries++)
			{
				//Draw triangle for each materials series.
				int offset = 0;
				//Get the material and the shader, then init them.
				Material* currentMaterial = currentDatas->mtlWrapper->getMaterial(itSeries->first);
				const Shader* shader;
				if(!m_material)
				{
					currentMaterial->enableShader();
					currentMaterial->init(render, totalMatrix, localMatrix);
					shader = currentMaterial->getShader();
				}
				else
				{
					m_material->init(render, totalMatrix, localMatrix);
					shader = m_material->getShader();
				}

				//Send the vector attribute
				int stride = 12;
				glVertexAttribPointer(glGetAttribLocation(shader->getProgramID(), "vPosition"), 3, GL_FLOAT, false, stride, BUFFER_OFFSET(0));
				glVertexAttribPointer(glGetAttribLocation(shader->getProgramID(), "vNormal"), 3, GL_FLOAT, false, stride, BUFFER_OFFSET(currentDatas->vertexPositionLength*4));

				//Send the uniform attribute
				GLint mvpMatrixHandle = glGetUniformLocation(shader->getProgramID(), "uMVP");
				glUniformMatrix4fv(mvpMatrixHandle, 1, false, glm::value_ptr(totalMatrix));

				//Draw the triangles.
				glDrawArrays(GL_TRIANGLES, offset, itSeries->second);
				offset += itSeries->second;
			}
		}
		glBindBuffer(GL_ARRAY_BUFFER, 0);
	}
}
       Rotate(modelViewShadow, 1.0, 0.0, 0.0, rotateModelWithLeftMouse[0]);
       Rotate(modelViewShadow, 0.0, 1.0, 0.0, rotateModelWithLeftMouse[1]); 
       //----------------------------------------------------------------------------------------
       Translate(modelViewShadow, facing_VIEW_blocks_01_POSITION[0] * scaleMoveShadows[0], 
                                  facing_VIEW_blocks_01_POSITION[1] * scaleMoveShadows[1], 
                                  facing_VIEW_blocks_01_POSITION[2] * scaleMoveShadows[2]);
                                  //-------------------------------------------------------                                                                                                         
       Rotate(modelViewShadow,    facing_VIEW_blocks_01_ROTATE[0], 
                                  facing_VIEW_blocks_01_ROTATE[1], 
                                  facing_VIEW_blocks_01_ROTATE[2], 
                                  facing_VIEW_blocks_01_ROTATE[3]);          
                                  //-------------------------------------------------------
       Scale(modelViewShadow,     scaleShadowSize, 
                                  scaleShadowSize, 
                                  scaleShadowSize);        
       //------------------------------------------------------------------------------------------------                                                                                                              
                 MultiplyMatrix(mvpMatrix, ProjectionShadow, modelViewShadow);                    
                 //---------------------------------------------------------------------------------------------------------------------------------------------------|__DRAW              
                           glVertexAttribPointer(0,   3, GL_FLOAT, GL_FALSE, 44, BUFFER_OFFSET(0));
                           glEnableVertexAttribArray(0);	
                           glVertexAttribPointer(1,   3, GL_FLOAT, GL_FALSE, 44, BUFFER_OFFSET(12));
                           glEnableVertexAttribArray(1);  
                           glVertexAttribPointer(2,   3, GL_FLOAT, GL_FALSE, 44, BUFFER_OFFSET(24));
                           glEnableVertexAttribArray(2);                                                       
                           glVertexAttribPointer(3,   2, GL_FLOAT, GL_FALSE, 44, BUFFER_OFFSET(36));
                           glEnableVertexAttribArray(3);                              
                           //--------------------------------------------------------------------------------------------------
                           glUniformMatrix4fv(UNIFORM_MODELVIEWPROJ_shadow_44bit_Stride, 1, 0,  mvpMatrix);
    //--------------------------------------------------------------------------------------------------
    glDrawElements(GL_TRIANGLES, 60, GL_UNSIGNED_INT, 0);
Example #3
0
void Ex06_02::InitGL()
{
	if (! LoadGL() )
		return;

	ShaderInfo  base_shaders[] = {
		{ GL_VERTEX_SHADER, "Shaders/sh06_02.vert" },
		{ GL_FRAGMENT_SHADER, "Shaders/sh06_02.frag" },
		{ GL_NONE, NULL }
	};

	base_prog = LoadShaders( base_shaders );

	glGenBuffers(1, &quad_vbo);
	glBindBuffer(GL_ARRAY_BUFFER, quad_vbo);

	static const GLfloat quad_data[] =
	{
		0.75f, -0.75f,
		-0.75f, -0.75f,
		-0.75f, 0.75f,
		0.75f, 0.75f,

		0.0f, 0.0f,
		1.0f, 0.0f,
		1.0f, 1.0f,
		0.0f, 1.0f
	};

	glBufferData(GL_ARRAY_BUFFER, sizeof(quad_data), quad_data, GL_STATIC_DRAW);

	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(8 * sizeof(float)));

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);

	glLinkProgram(base_prog);

	glGenTextures(1, &tex_checkerboard);
	glBindTexture(GL_TEXTURE_2D, tex_checkerboard);
	glTexStorage2D(GL_TEXTURE_2D, 4, GL_RGBA8, 8, 8);

	// The following is an 8x8 checkerboard pattern using
	// GL_RED, GL_UNSIGNED_BYTE data.
	static const unsigned char tex_checkerboard_data[] =
	{
		0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
		0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF,
		0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
		0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF,
		0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
		0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF,
		0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
		0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF
	};

	glTexSubImage2D(GL_TEXTURE_2D,
		0,
		0, 0,
		8, 8,
		GL_RED, GL_UNSIGNED_BYTE,
		tex_checkerboard_data);

	static const GLint swizzles[] = { GL_RED, GL_RED, GL_RED, GL_ONE };
	glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzles);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

	glGenerateMipmap(GL_TEXTURE_2D);

	glGenTextures(1, &tex_color);
	glBindTexture(GL_TEXTURE_2D, tex_color);
	glTexStorage2D(GL_TEXTURE_2D, 2, GL_RGBA32F, 2, 2);

	// The following data represents a 2x2 texture with red,
	// green, blue, and yellow texels represented as GL_RGBA,
	// GL_FLOAT data.
	static const GLfloat tex_color_data[] =
	{
		// Red texel				Green texel
		1.0f, 0.0f, 0.0f, 1.0f,		0.0f, 1.0f, 0.0f, 1.0f,
		// Blue texel				Yellow texel
		0.0f, 0.0f, 1.0f, 1.0f,		1.0f, 1.0f, 0.0f, 1.0f
	};

	glTexSubImage2D(GL_TEXTURE_2D, // target
		0, // First mipmap level
		0, 0, // x and y offset
		2, 2, // width and height
		GL_RGBA, GL_FLOAT, // format and type
		tex_color_data); // data

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

	glGenerateMipmap(GL_TEXTURE_2D);
}
Example #4
0
// OpenGL initialization
void
init()
{
	
/**
***  Create and initialize buffer objects
**/

	
	glGenBuffers( 4, buffers );
	//Vertex buffer for the vertex coordinates
	glBindBuffer( GL_ARRAY_BUFFER, buffers[cube_vertices] ); 
	glBufferData( GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW );

	glBindBuffer( GL_ARRAY_BUFFER, buffers[cube_vertices_explicit] ); 
	glBufferData( GL_ARRAY_BUFFER, sizeof(cube_vertices_positions), cube_vertices_positions, GL_STATIC_DRAW );

	std::cout<< "sizeof(cube_vertices_positions)" << sizeof(cube_vertices_positions) << std::endl;




	
	//Elements buffer for the pointers
	 glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, buffers[cube_indeces] ); 
	 glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); 

	 
	 glGenVertexArrays(2, VAO);
	


// Load shaders and use the resulting shader programs
    program[0] = InitShader( "./shaders/vshader30_TwoCubes_FullPipe.glsl", "./shaders/fshader30_TwoCubes.glsl" ); 
	program[1] = InitShader( "./shaders/skyboxvertex.glsl", "./shaders/skyboxfragment.glsl" ); 
	
    
	//VAO[1] the skybox
	glUseProgram( program[1] );
	glBindVertexArray(VAO[1]);
	glBindBuffer( GL_ARRAY_BUFFER, buffers[cube_vertices_explicit] ); 
	vPosition = glGetAttribLocation( program[1], "vPosition" );
	glEnableVertexAttribArray( vPosition );
	glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );
   	//done with this packet
    glBindVertexArray(0); 
	glUseProgram(0);
	
   //VAO[0] the Cube 
	glUseProgram( program[0] );

	glBindVertexArray(VAO[0]);
	glBindBuffer( GL_ARRAY_BUFFER, buffers[cube_vertices] ); 
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[cube_indeces]);
	vPosition = glGetAttribLocation( program[0], "vPosition" );
	glEnableVertexAttribArray( vPosition );
	glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );
   	//done with this packet
    glBindVertexArray(0); 

	glUseProgram(0);


	
	//Skybox textures 
	


	
	//Load Skybox Images. 6 images to represent the 6 angles of view. Inside it's own structured Cubemap
    skybox.top = glmReadPPM("skybox\\sky-top.ppm", &skybox.topWidth, &skybox.topHeight);
	skybox.bottom = glmReadPPM("skybox\\sky-bottom.ppm", &skybox.bottomWidth, &skybox.bottomHeight);
    skybox.right = glmReadPPM("skybox\\sky-right.ppm", &skybox.rightWidth, &skybox.rightHeight);
    skybox.left = glmReadPPM("skybox\\sky-left.ppm", &skybox.leftWidth, &skybox.leftHeight);
    skybox.front = glmReadPPM("skybox\\sky-front.ppm", &skybox.frontWidth, &skybox.frontHeight);
    skybox.back = glmReadPPM("skybox\\sky-back.ppm", &skybox.backWidth, &skybox.backHeight);
    
   	glActiveTexture(GL_TEXTURE0);

	glGenTextures(1, &texture);

	int isEnabled=0; 
	
	if (glIsEnabled(GL_TEXTURE_CUBE_MAP) == GL_TRUE) {isEnabled = 1;} else {isEnabled = 0;};


	std::cout << isEnabled << std::endl;

	glEnable(GL_TEXTURE_CUBE_MAP);

    
	if (glIsEnabled(GL_TEXTURE_CUBE_MAP) == GL_TRUE) {isEnabled = 1;} else {isEnabled = 0;};

	std::cout << isEnabled << std::endl;


    glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
	glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGB, skybox.topWidth, skybox.topHeight, 0,
                 GL_RGB, GL_UNSIGNED_BYTE,skybox.top);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGB, skybox.bottomWidth, skybox.bottomHeight, 0,
                 GL_RGB, GL_UNSIGNED_BYTE,skybox.bottom);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGB, skybox.rightWidth, skybox.rightHeight, 0,
                 GL_RGB, GL_UNSIGNED_BYTE,skybox.right);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGB, skybox.leftWidth, skybox.rightWidth, 0,
                 GL_RGB, GL_UNSIGNED_BYTE,skybox.left);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGB, skybox.frontWidth, skybox.frontHeight, 0,
                 GL_RGB, GL_UNSIGNED_BYTE,skybox.front);
    glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGB, skybox.backWidth, skybox.backHeight, 0,
                 GL_RGB, GL_UNSIGNED_BYTE,skybox.back);
	glGenerateMipmap(GL_TEXTURE_CUBE_MAP);


	glClearColor( 1.0, 1.0, 1.0, 0.0 ); 
	glClearDepth( 1.0 ); 
	glEnable( GL_DEPTH_TEST );
	glDepthFunc(GL_LEQUAL);
}
	bool initVertexArray()
	{
		bool Validated(true);

		glGenVertexArrays(1, &VertexArrayName);
		glBindVertexArray(VertexArrayName);
			glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
			glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fv2f), BUFFER_OFFSET(0));
			glVertexAttribPointer(semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fv2f), BUFFER_OFFSET(sizeof(glm::vec2)));
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glEnableVertexAttribArray(semantic::attr::POSITION);
			glEnableVertexAttribArray(semantic::attr::TEXCOORD);

			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]);
		glBindVertexArray(0);

		return Validated;
	}
void CRenderingContext::SetBitangentsBuffer(size_t iOffset, size_t iStride)
{
	if (m_pShader->m_iBitangentAttribute == ~0)
		return;

	TAssert(iOffset%4 == 0);	// Should be multiples of four because it's offsets in bytes and we're always working with floats or doubles
	glEnableVertexAttribArray(m_pShader->m_iBitangentAttribute);
	glVertexAttribPointer(m_pShader->m_iBitangentAttribute, 3, GL_FLOAT, false, iStride, BUFFER_OFFSET(iOffset));
}
Example #7
0
Sphere::Sphere(Scenegraph *graph,string name)
    :Object(graph,name)
{
	float theta,phi;
    int STACKS=100;
	int i,j;
    int SLICES = 100;
    float PI = 3.14159f;
	float cosphi,sinphi,costheta,sintheta;
    VertexAttribs v;

    /*
     *A sphere is drawn using vertices in polar coordinates. Polar coordinates are in terms of the radiu
     *, latitude and longitude. STACKS controls how many latitudes, and SLICES controls how many longitudes
     * are being used to draw this sphere.
     */

    //prepare the vertex data
	for (i=0;i<=STACKS;i++)
	{
		phi = -PI/2 + i*PI/STACKS;
		cosphi = cos(phi);
		sinphi = sin(phi);
		for (j=0;j<=SLICES;j++)
		{
			theta = 2*j*PI/SLICES;
			costheta = cos(theta);
			sintheta = sin(theta);

            v.position[0] = cosphi*costheta;
            v.position[1] = sinphi;
            v.position[2] = -cosphi*sintheta;
            v.position[3] = 1;

            v.normal[0] = cosphi*costheta;
            v.normal[1] = sinphi;
            v.normal[2] = -cosphi*sintheta;
            v.normal[3] = 0;

            v.texcoords[0] = theta/(2*PI);
            v.texcoords[1] = (phi+0.5f*PI)/PI;

            vertexData.push_back(v);
		}
	}

    //now prepare the triangle index list
    //this is simple enough. Just imagine drawing each quad in the sphere as two triangles
    //triangle 1: (i,j), (i,j+1) and (i+1,j+1)
    //triangle 2: (i,j), (i+1,j+1) and (i+1,j)
    //It is a good habit to specify all triangles in counter-clockwise order as OpenGL uses by default the order
    //to determine front-facing vs. back-facing if culling is enabled


	for (i=0;i<STACKS;i++)
	{
		for (j=0;j<SLICES;j++)
		{
            triangleIndices.push_back(i*(SLICES+1)+j);
            triangleIndices.push_back(i*(SLICES+1)+j+1);
            triangleIndices.push_back((i+1)*(SLICES+1)+j+1);

            triangleIndices.push_back(i*(SLICES+1)+j);
            triangleIndices.push_back((i+1)*(SLICES+1)+j+1);
            triangleIndices.push_back((i+1)*(SLICES+1)+j);

		}
	}

    /*
     *Bind the VAO as the current VAO, so that all subsequent commands affect it
     */
    glBindVertexArray(VAO);

    /*
     *Allocate the VBO for vertex data and send it to the GPU
     */
    glBindBuffer(GL_ARRAY_BUFFER,buffers[VertexBuffer]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(VertexAttribs)*vertexData.size(),&vertexData[0],GL_STATIC_DRAW);

    /*
     *Allocate the VBO for triangle indices and send it to GPU
     */
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[IndexBuffer]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*triangleIndices.size(), &triangleIndices[0], GL_STATIC_DRAW);


    /*
     *Specify all the vertex attribute pointers, i.e. tell OpenGL how to organize data according to attributes rather than vertices
     */

    //first enable the correct VBO, since the "current" is the VBO for triangle indices
    glBindBuffer(GL_ARRAY_BUFFER,buffers[VertexBuffer]);

    //VertexData starts with position, so starting byte is 0
    glVertexAttribPointer(vPosition,4,GL_FLOAT,GL_FALSE,sizeof(VertexAttribs),BUFFER_OFFSET(0));
    //In VertexData, normal follows the position (4 floats), so start reading normals from 4*sizeof(float)
    glVertexAttribPointer(vNormal,4,GL_FLOAT,GL_FALSE,sizeof(VertexAttribs),BUFFER_OFFSET(4*sizeof(float)));
    //In VertexData, texture coordinates follow the position and normal (8 floats), so start reading texture coordinates from 8*sizeof(float)
    glVertexAttribPointer(vTexCoord,2,GL_FLOAT,GL_FALSE,sizeof(VertexAttribs),BUFFER_OFFSET(8*sizeof(float)));

    //enable the vertex attribute arrays
    glEnableVertexAttribArray(vPosition);
    glEnableVertexAttribArray(vNormal);
  glEnableVertexAttribArray(vTexCoord);

    /*
     *Unbind the VAO to prevent accidental change to all the settings
     *so at this point, this VAO has two VBOs and two enabled VertexAttribPointers.
     * It is going to remember all of that!
     */
    glBindVertexArray(0);

    numIndices = triangleIndices.size();
    triangleIndices.clear();
    vertexData.clear();
}
Example #8
0
bool ProxyTexture::Init(__in const char* vCmdLine[], __in const int iCmdCount,
                        __in const int iWidth, __in const int iHeight){
    if(!NX::Application::Init(vCmdLine, iCmdCount, iWidth, iHeight)){
        return false;
    }
    
    
    GLuint ProxyId;
    glGenTextures(1, &ProxyId);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_PROXY_TEXTURE_2D, ProxyId);
    glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
    
    GLint maxTexWidth;
    glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &maxTexWidth);
    if(maxTexWidth){
        NX::glb_GetLog().logToConsole("create succeed");
    }else{
        NX::glb_GetLog().logToConsole("create failed");
    }
    return true;
}
Example #9
0
// OpenGL initialization
void
init()
{
    // Subdivide a tetrahedron into a sphere
    tetrahedron( NumTimesToSubdivide );

    // Create a vertex array object
    GLuint vao;
    glGenVertexArrays( 1, &vao );
    glBindVertexArray( vao );

    // Create and initialize a buffer object
    GLuint buffer;
    glGenBuffers( 1, &buffer );
    glBindBuffer( GL_ARRAY_BUFFER, buffer );
    glBufferData( GL_ARRAY_BUFFER, sizeof(points) + sizeof(normals),
		  NULL, GL_STATIC_DRAW );
    glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(points), points );
    glBufferSubData( GL_ARRAY_BUFFER, sizeof(points),
		     sizeof(normals), normals );

    // Load shaders and use the resulting shader program
    GLuint program = InitShader( "vshader_a7.glsl", "fshader_a7.glsl" );
    glUseProgram( program );
	
    // set up vertex arrays
    GLuint vPosition = glGetAttribLocation( program, "vPosition" );
    glEnableVertexAttribArray( vPosition );
    glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,
			   BUFFER_OFFSET(0) );

    GLuint vNormal = glGetAttribLocation( program, "vNormal" ); 
    glEnableVertexAttribArray( vNormal );
    glVertexAttribPointer( vNormal, 3, GL_FLOAT, GL_FALSE, 0,
			   BUFFER_OFFSET(sizeof(points)) );

    // Initialize shader lighting parameters
    point4 light_position( 0.0, 0.0, 2.0, 0.0 );
    color4 light_ambient( 0.2, 0.2, 0.2, 1.0 );
    color4 light_diffuse( 1.0, 1.0, 1.0, 1.0 );
    color4 light_specular( 1.0, 1.0, 1.0, 1.0 );

    color4 material_ambient( 1.0, 0.0, 1.0, 1.0 );
    color4 material_diffuse( 1.0, 0.8, 0.0, 1.0 );
    color4 material_specular( 1.0, 0.0, 1.0, 1.0 );
    float  material_shininess = 5.0;

    color4 ambient_product = light_ambient * material_ambient;
    color4 diffuse_product = light_diffuse * material_diffuse;
    color4 specular_product = light_specular * material_specular;

    glUniform4fv( glGetUniformLocation(program, "AmbientProduct"),
		  1, ambient_product );
    glUniform4fv( glGetUniformLocation(program, "DiffuseProduct"),
		  1, diffuse_product );
    glUniform4fv( glGetUniformLocation(program, "SpecularProduct"),
		  1, specular_product );
	
    glUniform4fv( glGetUniformLocation(program, "LightPosition"),
		  1, light_position );

    glUniform1f( glGetUniformLocation(program, "Shininess"),
		 material_shininess );
		 
    // Retrieve transformation uniform variable locations
    ModelView = glGetUniformLocation( program, "ModelView" );
    Projection = glGetUniformLocation( program, "Projection" );
    
    glEnable( GL_DEPTH_TEST );
    
    glClearColor( 1.0, 1.0, 1.0, 1.0 ); /* white background */
}
Example #10
0
VertexFormatToAttrOffsetsMap Mesh::createVertexFormatToAttrOffsetsMap() {
    VertexFormatToAttrOffsetsMap formatToOffsetMap;
    byte* start;

    VertexPos vtPos;
    start = (byte*)&vtPos;
    AttrToOffsetMap mapPos;
    mapPos[kPosIndex] = BUFFER_OFFSET((byte*)&(vtPos.position) - start);
    formatToOffsetMap[VT_Pos] = mapPos;

    VertexPosUV vtPosUV;
    start = (byte*)&vtPosUV;
    AttrToOffsetMap mapPosUV;
    mapPosUV[kPosIndex] = BUFFER_OFFSET((byte*)&(vtPosUV.position) - start);
    mapPosUV[kTexCoordIndex] = BUFFER_OFFSET((byte*)&(vtPosUV.texcoord) - start);
    formatToOffsetMap[VT_PosUV] = mapPosUV;

    VertexPosColor vtPosColor;
    start = (byte*)&vtPosColor;
    AttrToOffsetMap mapPosColor;
    mapPosColor[kPosIndex] = BUFFER_OFFSET((byte*)&(vtPosColor.position) - start);
    mapPosColor[kColorIndex] = BUFFER_OFFSET((byte*)&(vtPosColor.color) - start);
    formatToOffsetMap[VT_PosColor] = mapPosColor;

    VertexPosUVColor vtPosUVColor;
    start = (byte*)&vtPosUVColor;
    AttrToOffsetMap mapPosUVColor;
    mapPosUVColor[kPosIndex] = BUFFER_OFFSET((byte*)&(vtPosUVColor.position) - start);
    mapPosUVColor[kTexCoordIndex] = BUFFER_OFFSET((byte*)&(vtPosUVColor.texcoord) - start);
    mapPosUVColor[kColorIndex] = BUFFER_OFFSET((byte*)&(vtPosUVColor.color) - start);
    formatToOffsetMap[VT_PosUVColor] = mapPosUVColor;

    VertexSkinned vtSkinned;
    start = (byte*)&vtSkinned;
    AttrToOffsetMap mapSkinned;
    mapSkinned[kPosIndex] = BUFFER_OFFSET((byte*)&(vtSkinned.position) - start);
    mapSkinned[kTexCoordIndex] = BUFFER_OFFSET((byte*)&(vtSkinned.texcoord) - start);
    mapSkinned[kColorIndex] = BUFFER_OFFSET((byte*)&(vtSkinned.color) - start);
    mapSkinned[kBlendIndicesIndex] = BUFFER_OFFSET((byte*)&(vtSkinned.blendindices) - start);
    mapSkinned[kBlendWeightsIndex] = BUFFER_OFFSET((byte*)&(vtSkinned.blendweights) - start);
    formatToOffsetMap[VT_Skinned] = mapSkinned;

    return formatToOffsetMap;
}
Example #11
0
void Grid::uploadGeometry()
{
	const int ColorOffset = 0;
	const int PositionOffset = sizeof( Color4 );
	const int TexCoordOffset = sizeof( Color4 ) + sizeof( Point );
	const unsigned int POSITION_INDEX = 0;	
	const unsigned int COLOR0_INDEX = 3;
	const unsigned int TEXCOORD_INDEX = 8;
	/// Generate and bind vertex array object for the grid
	glGenVertexArrays(1, g_vao);
	(Logger::Instance()).checkAndReportGLError("Failed to generate Vertex Arrays",'e',4,__LINE__,__FILE__);
	glBindVertexArray( g_vao[0] );
	(Logger::Instance()).checkAndReportGLError("Failed to bind Vertex Arrays",'e',4,__LINE__,__FILE__);
	/// Generate buffer objects for vertices and indices
	
	glGenTextures(1, texName);
	(Logger::Instance()).checkAndReportGLError(" failed to gen textures",'e',4,__LINE__,__FILE__);
	glBindTexture(GL_TEXTURE_2D, texName[0]);
	(Logger::Instance()).checkAndReportGLError(" fail 2d ",'e',4,__LINE__,__FILE__);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	(Logger::Instance()).checkAndReportGLError(" fail wrap s",'e',4,__LINE__,__FILE__);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	(Logger::Instance()).checkAndReportGLError(" fail wrap t",'e',4,__LINE__,__FILE__);
	
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	
	if(tgaObj.pixelSizeInBytes == 3)
	{
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tgaObj.width,
		tgaObj.height, 0, GL_BGR, GL_UNSIGNED_BYTE,
		tgaObj.data);
		(Logger::Instance()).checkAndReportGLError(" fail image 2d ",'e',4,__LINE__,__FILE__);
	}
	else
	{
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tgaObj.width,
		tgaObj.height, 0, GL_BGRA, GL_UNSIGNED_BYTE,
		tgaObj.data);
		(Logger::Instance()).checkAndReportGLError(" fail image 2d ",'e',4,__LINE__,__FILE__);
	}
	glGenBuffers( NUM_BUFFERS, vbo );
	(Logger::Instance()).checkAndReportGLError("Failed to generate Buffer objects",'e',4,__LINE__,__FILE__);
	/// Bind vertex buffer object
	glBindBuffer( GL_ARRAY_BUFFER, vbo[VBO] );
	(Logger::Instance()).checkAndReportGLError("Failed to bind Vertex Buffer object",'e',4,__LINE__,__FILE__);
	glBufferData(
		GL_ARRAY_BUFFER,
		sizeof(Vertex) * totVertices,
		reinterpret_cast<const GLvoid*>( g_VertexArray ),
		GL_STATIC_DRAW );
	(Logger::Instance()).checkAndReportGLError("Failed to provide Vertex Buffer data",'e',4,__LINE__,__FILE__);
	glVertexAttribPointer(
		POSITION_INDEX,
		3,
		GL_FLOAT,
		GL_FALSE,
		sizeof( Vertex ),
		BUFFER_OFFSET( PositionOffset ) );
	(Logger::Instance()).checkAndReportGLError("Failed to run glVertexAttribPointer for vertex position",'e',4,__LINE__,__FILE__);
	glEnableVertexAttribArray( POSITION_INDEX );
	(Logger::Instance()).checkAndReportGLError("Failed to enable VertexAttribArray for vertex position",'e',4,__LINE__,__FILE__);
	glVertexAttribPointer(
		COLOR0_INDEX,
		4,
		GL_UNSIGNED_BYTE,
		GL_TRUE,
		sizeof( Vertex ),
		BUFFER_OFFSET( ColorOffset ) );
	(Logger::Instance()).checkAndReportGLError("Failed to run glVertexAttribPointer for color",'e',4,__LINE__,__FILE__);
	glEnableVertexAttribArray( COLOR0_INDEX );
	(Logger::Instance()).checkAndReportGLError("Failed to enable VertexAttribArray for color",'e',4,__LINE__,__FILE__);
	glVertexAttribPointer(
		TEXCOORD_INDEX,
		2,
		GL_FLOAT,
		GL_FALSE,
		sizeof( Vertex ),
		BUFFER_OFFSET( TexCoordOffset ) );
	(Logger::Instance()).checkAndReportGLError("Failed to run glVertexAttribPointer for TexCoord",'e',4,__LINE__,__FILE__);
	glEnableVertexAttribArray( TEXCOORD_INDEX );
	(Logger::Instance()).checkAndReportGLError("Failed to enable VertexAttribArray for TexCoord",'e',4,__LINE__,__FILE__);
	/// Bind Index buffer object
	glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vbo[IBO] );
	(Logger::Instance()).checkAndReportGLError("Failed to bind Index Buffer object",'e',4,__LINE__,__FILE__);
	glBufferData(
		GL_ELEMENT_ARRAY_BUFFER,
		sizeof(GLushort) * NUMBER_OF_INDICES,
		reinterpret_cast<const GLvoid*>( g_indices ),
		GL_STATIC_DRAW );
	(Logger::Instance()).checkAndReportGLError("Failed to provide buffer data for indices",'e',4,__LINE__,__FILE__);
}
	KIL_UINT32 RendererPrimitive::Create( const KIL_BYTE *p_pVertices,
		const KIL_UINT16 *p_pIndices, const KIL_MEMSIZE p_VertexCount,
		const KIL_MEMSIZE p_IndexCount,
		const VertexAttributes &p_VertexAttributes,
		const PRIMITIVE_TYPE p_Type )
	{
		if( p_pVertices == KIL_NULL )
		{
			return KIL_FAIL;
		}

		if( p_pIndices == KIL_NULL )
		{
			return KIL_FAIL;
		}

		switch( p_Type )
		{
			case PRIMITIVE_TYPE_TRIANGLE_LIST:
			{
				m_PolygonCount = p_IndexCount / 3;
				m_GLType = GL_TRIANGLES;
				break;
			}
			case PRIMITIVE_TYPE_TRIANGLE_STRIP:
			{
				m_PolygonCount = p_IndexCount - 2;
				m_GLType = GL_TRIANGLE_STRIP;
				break;
			}
			case PRIMITIVE_TYPE_TRIANGLE_FAN:
			{
				m_PolygonCount = p_IndexCount - 2;
				m_GLType = GL_TRIANGLE_FAN;
				break;
			}
			case PRIMITIVE_TYPE_LINE_LIST:
			{
				m_PolygonCount = p_IndexCount / 2;
				m_GLType = GL_LINES;
				break;
			}
			case PRIMITIVE_TYPE_LINE_STRIP:
			{
				m_PolygonCount = p_IndexCount - 1;
				m_GLType = GL_LINE_STRIP;
				break;
			}
			case PRIMITIVE_TYPE_LINE_LOOP:
			{
				m_PolygonCount = p_IndexCount;
				m_GLType = GL_LINE_LOOP;
				break;
			}
			case PRIMITIVE_TYPE_UNKNOWN:
			{
				return KIL_FAIL;
			}
		}

		if( m_PolygonCount == 0 )
		{
			return KIL_FAIL;
		}

		m_Stride = p_VertexAttributes.GetStride( );

		glGenBuffers( 1, &m_VertexBufferObject );
		glGenBuffers( 1, &m_IndexBufferObject );
		glGenVertexArrays( 1, &m_VertexArrayObject );

		glBindVertexArray( m_VertexArrayObject );
		glBindBuffer( GL_ARRAY_BUFFER, m_VertexBufferObject );
		glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_IndexBufferObject );

		KIL_MEMSIZE Offset = 0;
		KIL_SINT32 PositionOffset = -1;
		KIL_SINT32 NormalsOffset = -1;

		for( KIL_MEMSIZE Index = 0;
			Index < p_VertexAttributes.GetVertexAttributeCount( ); ++Index )
		{
			KIL_MEMSIZE Dimension = 0;
			KIL_MEMSIZE TypeSize = 0;
			GLenum Type = GL_INVALID_ENUM;
			struct VERTEXATTRIBUTE Attribute =
				p_VertexAttributes.GetAttributeAt( Index );

			Type = ConvertVertexAttributeToGLenum( Attribute );
			TypeSize = ConvertVertexAttributeToSize( Attribute );
			Dimension = ConvertVertexAttributeToElementCount( Attribute );
	
			if( Attribute.Intent == VERTEXATTRIBUTE_INTENT_POSITION )
			{
				PositionOffset = Offset;
			}

			if( Attribute.Intent == VERTEXATTRIBUTE_INTENT_NORMAL )
			{
				NormalsOffset = Offset;
			}

			glVertexAttribPointer( Index, Dimension, Type, GL_FALSE,
				m_Stride, BUFFER_OFFSET( Offset ) );

			Offset += TypeSize;

			glEnableVertexAttribArray( Index );
		}

		glBufferData( GL_ARRAY_BUFFER, p_VertexCount * m_Stride,
			p_pVertices, GL_STATIC_DRAW );

		GLenum Error = glGetError( );

		if( Error == GL_OUT_OF_MEMORY )
		{
			this->Destroy( );

			return KIL_FAIL;
		}

		glBufferData( GL_ELEMENT_ARRAY_BUFFER,
			p_IndexCount * sizeof( KIL_UINT16 ), p_pIndices, GL_STATIC_DRAW );

		Error = glGetError( );
		
		if( Error == GL_OUT_OF_MEMORY )
		{
			this->Destroy( );

			return KIL_FAIL;
		}

		m_VertexCount = p_VertexCount;
		m_IndexCount = p_IndexCount;

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

		if( ( NormalsOffset != -1 ) && ( PositionOffset != -1 ) )
		{
			glGenBuffers( 1, &m_NormalsVertexBufferObject );
			glGenBuffers( 1, &m_NormalsIndexBufferObject );
			glGenVertexArrays( 1, &m_NormalsVertexArrayObject );

			glBindVertexArray( m_NormalsVertexArrayObject );
			glBindBuffer( GL_ARRAY_BUFFER, m_NormalsVertexBufferObject );
			glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,
				m_NormalsIndexBufferObject );

			glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0,
				BUFFER_OFFSET( 0 ) );

			glEnableVertexAttribArray( 0 );

			struct NORMALPOSITION
			{
				KIL_FLOAT32 Start[ 3 ];
				KIL_FLOAT32 End[ 3 ];
			};

			struct NORMALPOSITION *pNormalPosition =
				new NORMALPOSITION[ m_VertexCount ];

			for( KIL_MEMSIZE Vertex = 0; Vertex < m_VertexCount; ++Vertex )
			{
				memcpy( pNormalPosition[ Vertex ].Start,
					p_pVertices + ( Vertex * m_Stride ) + PositionOffset, 12 );
				memcpy( pNormalPosition[ Vertex ].End,
					p_pVertices + ( Vertex * m_Stride ) + NormalsOffset, 12 );

				Vector3 Normal( pNormalPosition[ Vertex ].End[ 0 ],
					pNormalPosition[ Vertex ].End[ 1 ],
					pNormalPosition[ Vertex ].End[ 2 ] );

				Vector3 Position( pNormalPosition[ Vertex ].Start[ 0 ],
					pNormalPosition[ Vertex ].Start[ 1 ],
					pNormalPosition[ Vertex ].Start[ 2 ] );

				Normal += Position;

				memcpy( pNormalPosition[ Vertex ].End, &Normal, 12 );
			}

			KIL_UINT16 *pNormalsIndices = new KIL_UINT16[ m_VertexCount * 2 ];

			for( KIL_MEMSIZE Index = 0; Index < m_VertexCount * 2; ++Index )
			{
				pNormalsIndices[ Index ] = Index;
			}

			glBufferData( GL_ARRAY_BUFFER,
				m_VertexCount * sizeof( struct NORMALPOSITION ),
				pNormalPosition, GL_STATIC_DRAW );
			glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( KIL_UINT16 ) *
				m_VertexCount * 2, pNormalsIndices, GL_STATIC_DRAW );

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

			SafeDeleteArray< KIL_UINT16 >( pNormalsIndices );
			SafeDeleteArray< NORMALPOSITION >( pNormalPosition );
		}

		if( PositionOffset != -1 )
		{
			glGenBuffers( 1, &m_WireframeVertexBufferObject );
			glGenBuffers( 1, &m_WireframeIndexBufferObject );
			glGenVertexArrays( 1, &m_WireframeVertexArrayObject );

			glBindVertexArray( m_WireframeVertexArrayObject );

			glBindBuffer( GL_ARRAY_BUFFER, m_WireframeVertexBufferObject );
			glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,
				m_WireframeIndexBufferObject );

			glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0,
				BUFFER_OFFSET( 0 ) );

			glEnableVertexAttribArray( 0 );

			struct POSITION
			{
				KIL_FLOAT32 Position[ 3 ];
			};

			struct POSITION *pPosition = new POSITION[ m_VertexCount ];

			for( KIL_MEMSIZE Vertex = 0; Vertex < m_VertexCount; ++Vertex )
			{
				memcpy( pPosition[ Vertex ].Position,
					p_pVertices + ( Vertex * m_Stride ) + PositionOffset, 12 );
			}

			glBufferData( GL_ARRAY_BUFFER,
				m_VertexCount * sizeof( struct POSITION ), pPosition,
				GL_STATIC_DRAW );
			glBufferData( GL_ELEMENT_ARRAY_BUFFER,
				sizeof( KIL_UINT16 ) * p_IndexCount, p_pIndices,
				GL_STATIC_DRAW );

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

			SafeDeleteArray< POSITION >( pPosition );
		}

		return KIL_OK;
	}
//////////////////////////////////////////////////////////////////////
//  readback 
//
//   Code to handle reading back of the FBO data (but with a specified FBO pointer)
//
//////////////////////////////////////////////////////////////////////
bool CheckBackBuffer::readback( GLuint width, GLuint height, GLuint bufObject )
{
    bool ret = false;

    if (m_bUseFBO) {
        if (m_bUsePBO) 
        {
            printf("CheckBackBuffer::readback() FBO->PBO->m_pImageData\n");
            // binds the PBO for readback
            bindReadback();

            // bind FBO buffer (we want to transfer FBO -> PBO)
            glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, bufObject );

            // Now initiate the readback to PBO
	        glReadPixels(0, 0, width, height, getPixelFormat(),      GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
            ret = checkStatus(__FILE__, __LINE__, true);
            if (!ret) printf("CheckBackBuffer::readback() FBO->PBO checkStatus = %d\n", ret);

	        // map - unmap simulates readback without the copy
	        void *ioMem = glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);
            memcpy(m_pImageData,    ioMem, width*height*m_Bpp);

		    glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);

            // release the FBO
		    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); 

            // release the PBO
            unbindReadback();
        } else {
            printf("CheckBackBuffer::readback() FBO->m_pImageData\n");
            // Reading direct to FBO using glReadPixels
            glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, bufObject );
            ret = checkStatus(__FILE__, __LINE__, true);
            if (!ret) printf("CheckBackBuffer::readback::glBindFramebufferEXT() fbo=%d checkStatus = %d\n", bufObject, ret);

            glReadBuffer(static_cast<GLenum>(GL_COLOR_ATTACHMENT0_EXT));
            ret &= checkStatus(__FILE__, __LINE__, true);
            if (!ret) printf("CheckBackBuffer::readback::glReadBuffer() fbo=%d checkStatus = %d\n", bufObject, ret);

            glReadPixels(0, 0, width, height, getPixelFormat(), GL_UNSIGNED_BYTE, m_pImageData);

            glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
        }
    } else {
        
        printf("CheckBackBuffer::readback() PBO->m_pImageData\n");
        // read from bufObject (PBO) to system memorys image
		glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, bufObject);	// Bind the PBO

        // map - unmap simulates readback without the copy
        void *ioMem = glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);

        // allocate a buffer so we can flip the image
        unsigned char * temp_buf = (unsigned char *)malloc(width*height*m_Bpp);
        memcpy( temp_buf, ioMem, width*height*m_Bpp );

        // let's flip the image as we copy
        for (unsigned int y = 0; y < height; y++) {
            memcpy( (void *)&(m_pImageData[(height-y)*width*m_Bpp]), (void *)&(temp_buf[y*width*m_Bpp]), width*m_Bpp);
        }
        free(temp_buf);

	    glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);

        // read from bufObject (PBO) to system memory image
		glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);	// unBind the PBO
    }
	return CHECK_FBO;
}
static int get_image( mlt_frame a_frame, uint8_t **image, mlt_image_format *format, int *width, int *height, int writable )
{
	int error = 0;

	// Get the b frame from the stack
	mlt_frame b_frame = (mlt_frame) mlt_frame_pop_frame( a_frame );

	// Get the transition object
	mlt_transition transition = (mlt_transition) mlt_frame_pop_service( a_frame );

	// Get the properties of the transition
	mlt_properties properties = MLT_TRANSITION_PROPERTIES( transition );

	// Get the properties of the a frame
	mlt_properties a_props = MLT_FRAME_PROPERTIES( a_frame );

	// Get the movit objects
	mlt_service service = MLT_TRANSITION_SERVICE( transition );
	mlt_service_lock( service );
	EffectChain* chain = GlslManager::get_chain( service );
	MltInput* a_input = GlslManager::get_input( service );
	MltInput* b_input = (MltInput*) mlt_properties_get_data( properties, "movit input B", NULL );
	mlt_image_format output_format = *format;

	if ( !chain || !a_input ) {
		mlt_service_unlock( service );
		return 2;
	}

	// Get the frames' textures
	GLuint* texture_id[2] = {0, 0};
	*format = mlt_image_glsl_texture;
	mlt_frame_get_image( a_frame, (uint8_t**) &texture_id[0], format, width, height, 0 );
	a_input->useFBOInput( chain, *texture_id[0] );
	*format = mlt_image_glsl_texture;
	mlt_frame_get_image( b_frame, (uint8_t**) &texture_id[1], format, width, height, 0 );
	b_input->useFBOInput( chain, *texture_id[1] );

	// Set resolution to that of the a_frame
	*width = mlt_properties_get_int( a_props, "width" );
	*height = mlt_properties_get_int( a_props, "height" );

	// Setup rendering to an FBO
	GlslManager* glsl = GlslManager::get_instance();
	glsl_fbo fbo = glsl->get_fbo( *width, *height );
	if ( output_format == mlt_image_glsl_texture ) {
		glsl_texture texture = glsl->get_texture( *width, *height, GL_RGBA );

		glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo );
		check_error();
		glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 );
		check_error();
		glBindFramebuffer( GL_FRAMEBUFFER, 0 );
		check_error();

		GlslManager::render( service, chain, fbo->fbo, *width, *height );

		glFinish();
		check_error();
		glBindFramebuffer( GL_FRAMEBUFFER, 0 );
		check_error();

		*image = (uint8_t*) &texture->texture;
		mlt_frame_set_image( a_frame, *image, 0, NULL );
		mlt_properties_set_data( properties, "movit.convert", texture, 0,
			(mlt_destructor) GlslManager::release_texture, NULL );
		*format = output_format;
	}
	else {
		// Use a PBO to hold the data we read back with glReadPixels()
		// (Intel/DRI goes into a slow path if we don't read to PBO)
		GLenum gl_format = ( output_format == mlt_image_rgb24a || output_format == mlt_image_opengl )?
			GL_RGBA : GL_RGB;
		int img_size = *width * *height * ( gl_format == GL_RGB? 3 : 4 );
		glsl_pbo pbo = glsl->get_pbo( img_size );
		glsl_texture texture = glsl->get_texture( *width, *height, gl_format );

		if ( fbo && pbo && texture ) {
			// Set the FBO
			glBindFramebuffer( GL_FRAMEBUFFER, fbo->fbo );
			check_error();
			glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->texture, 0 );
			check_error();
			glBindFramebuffer( GL_FRAMEBUFFER, 0 );
			check_error();

			GlslManager::render( service, chain, fbo->fbo, *width, *height );

			// Read FBO into PBO
			glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, pbo->pbo );
			check_error();
			glBufferData( GL_PIXEL_PACK_BUFFER_ARB, img_size, NULL, GL_STREAM_READ );
			check_error();
			glReadPixels( 0, 0, *width, *height, gl_format, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0) );
			check_error();

			// Copy from PBO
			uint8_t* buf = (uint8_t*) glMapBuffer( GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY );
			check_error();

			*format = gl_format == GL_RGBA ? mlt_image_rgb24a : mlt_image_rgb24;
			*image = (uint8_t*) mlt_pool_alloc( img_size );
			mlt_frame_set_image( a_frame, *image, img_size, mlt_pool_release );
			memcpy( *image, buf, img_size );

			// Release PBO and FBO
			glUnmapBuffer( GL_PIXEL_PACK_BUFFER_ARB );
			check_error();
			glBindBuffer( GL_PIXEL_PACK_BUFFER_ARB, 0 );
			check_error();
			glBindFramebuffer( GL_FRAMEBUFFER, 0 );
			check_error();
			glBindTexture( GL_TEXTURE_2D, 0 );
			check_error();
			GlslManager::release_texture( texture );
		}
		else {
			error = 1;
		}
	}
	if ( fbo ) GlslManager::release_fbo( fbo );
	mlt_service_lock( service );

	return error;
}
Example #15
0
//.......................................................................................
void Font::RenderString_ss(float _x, float _y, char *_str, ...)
{
	// extract arguments
	char buffer[1024];
	memset(buffer, 0, 1024);

	va_list arglist;

	if (!_str)
		return;

	va_start(arglist, _str);
	vsprintf(buffer, _str, arglist);
	va_end(arglist);
	
	const uint8_t *p;

	float x = -1 + _x * m_sx;
	float y = 1 - _y * m_sy;

	// Bind texture
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, m_atlasTextureID);
	glUniform1i(m_uniformTex, 0);

	// Select the font VBO
	glBindVertexArray(m_fontVAO);
	glEnableVertexAttribArray(m_attributeCoord);
	glBindBuffer(GL_ARRAY_BUFFER, m_fontVBO);
	glVertexAttribPointer(m_attributeCoord, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));

	int c = 0;
	//memset(m_sTexCoords, 0, sizeof(font_point) * 256); 
	m_sTexCoords = new font_point[6 * strlen(buffer)];

	// Loop through all characters
	for (p = (const uint8_t *)buffer; *p; p++)
	{
		// calculate vertex and texture coordinates
		float x2 = x + m_sChars[*p].bl * m_sx;
		float y2 = -y - m_sChars[*p].bt * m_sy;
		float w = m_sChars[*p].bw * m_sx;
		float h = m_sChars[*p].bh * m_sy;

		// advance cursor
		x += m_sChars[*p].ax * m_sx;
		y += m_sChars[*p].ay * m_sy;

		// skip empty chars
		if (!w || !h)
			continue;
		
		m_sTexCoords[c+0].x = x2 + w;
		m_sTexCoords[c+0].y = -y2;
		m_sTexCoords[c+0].s =  m_sChars[*p].tx + m_sChars[*p].bw / m_iTextureWidth;
		m_sTexCoords[c+0].t = m_sChars[*p].ty;

		m_sTexCoords[c+1].x = x2;
		m_sTexCoords[c+1].y = -y2;
		m_sTexCoords[c+1].s = m_sChars[*p].tx;
		m_sTexCoords[c+1].t = m_sChars[*p].ty;

		m_sTexCoords[c+2].x = x2;
		m_sTexCoords[c+2].y = -y2 - h;
		m_sTexCoords[c+2].s = m_sChars[*p].tx;
		m_sTexCoords[c+2].t = m_sChars[*p].ty + m_sChars[*p].bh / m_iTextureHeight;

		m_sTexCoords[c+3].x = x2 + w; 
		m_sTexCoords[c+3].y = -y2;
		m_sTexCoords[c+3].s = m_sChars[*p].tx + m_sChars[*p].bw / m_iTextureWidth;
		m_sTexCoords[c+3].t = m_sChars[*p].ty;

		m_sTexCoords[c+4].x = x2; 
		m_sTexCoords[c+4].y = -y2 - h;
		m_sTexCoords[c+4].s = m_sChars[*p].tx;
		m_sTexCoords[c+4].t = m_sChars[*p].ty + m_sChars[*p].bh / m_iTextureHeight;

		m_sTexCoords[c+5].x = x2 + w;
		m_sTexCoords[c+5].y = -y2 - h;
		m_sTexCoords[c+5].s = m_sChars[*p].tx + m_sChars[*p].bw / m_iTextureWidth;
		m_sTexCoords[c+5].t = m_sChars[*p].ty + m_sChars[*p].bh / m_iTextureHeight;

		c += 6;

	}
	
	glBufferData(GL_ARRAY_BUFFER, sizeof(font_point) * c, m_sTexCoords, GL_DYNAMIC_DRAW);
	glDrawArrays(GL_TRIANGLES, 0, c);

	glDisableVertexAttribArray(m_attributeCoord);
	glBindVertexArray(0);

	// free memory
	delete [] m_sTexCoords;

} // Font::RenderString_ss()
	bool render()
	{
		glm::vec2 WindowSize(this->getWindowSize());

		{
			glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::TRANSFORM]);
			glm::mat4* Pointer = (glm::mat4*)glMapBufferRange(GL_UNIFORM_BUFFER, 0,	sizeof(glm::mat4),
				GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

			glm::mat4 Projection = glm::perspectiveFov(glm::pi<float>() * 0.25f, WindowSize.x, WindowSize.y, 0.1f, 100.0f);
			glm::mat4 Model = glm::mat4(1.0f);
			*Pointer = Projection * this->view() * Model;

			// Make sure the uniform buffer is uploaded
			glUnmapBuffer(GL_UNIFORM_BUFFER);
		}

		glBindProgramPipeline(PipelineName[program::COMPUTE]);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, semantics::INPUT, BufferName[buffer::INPUT]);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, semantics::OUTPUT, BufferName[buffer::OUTPUT]);
		glBindBufferBase(GL_UNIFORM_BUFFER, semantic::uniform::TRANSFORM0, BufferName[buffer::TRANSFORM]);
		glDispatchCompute(GLuint(VertexCount), 1, 1);

		glViewportIndexedf(0, 0, 0, WindowSize.x, WindowSize.y);
		glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f)[0]);

		glBindProgramPipeline(PipelineName[program::GRAPHICS]);
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, TextureName);
		glBindVertexArray(VertexArrayName);
		glBindBufferBase(GL_UNIFORM_BUFFER, semantic::uniform::TRANSFORM0, BufferName[buffer::TRANSFORM]);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, semantics::INPUT, BufferName[buffer::OUTPUT]);

		glDrawElementsInstancedBaseVertexBaseInstance(GL_TRIANGLES, ElementCount, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0), 1, 0, 0);

		return true;
	}
Example #17
0
bool DrawInstance::Init(const char* vCmdLine[], const int iCmdCount, const int iWidth, const int iHeight){
    if(!NX::Application::Init(vCmdLine, iCmdCount, iWidth, iHeight)){
        return false;
    }
    
    {//shader
        m_pg = new NX::Program();
        m_pg->AddShader("./RedBook/Chap3/DrawInstanceVS.glsl", GL_VERTEX_SHADER);
        m_pg->AddShader("./RedBook/Chap3/DrawInstanceFS.glsl", GL_FRAGMENT_SHADER);
        m_pg->LinkProgram();
        m_pg->UseProgram();
    }
    
    {//vao
        glGenVertexArrays(1, &vao);
        glBindVertexArray(vao);
        
        glGenBuffers(1, &vbo);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        NX::float3 v = NX::float3(0.0f, 0.0f, 0.0f);
        glBufferData(GL_ARRAY_BUFFER, sizeof(v), &v, GL_STATIC_DRAW);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
        glEnableVertexAttribArray(0);
    }
    
    {//color instance
        GLuint  cI;
        NX::float3 Color[INSTANCE_COUNT];
        for(int i = 0; i < INSTANCE_COUNT; ++i){
            Color[i].r = NX::RandUnitFloat();
            Color[i].g = NX::RandUnitFloat();
            Color[i].b = NX::RandUnitFloat();
        }
        glGenBuffers(1, &cI);
        glBindBuffer(GL_ARRAY_BUFFER, cI);
        glBufferData(GL_ARRAY_BUFFER, sizeof(Color), Color, GL_STATIC_DRAW);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Color[0]), BUFFER_OFFSET(0));
        glEnableVertexAttribArray(1);
        glVertexAttribDivisor(1, 1);
    }
    
    {//dif
        GLuint dI;
        glGenBuffers(1, &dI);
        glBindBuffer(GL_ARRAY_BUFFER, dI);
        NX::float2 Dif[INSTANCE_COUNT];
        for(int i = 0; i < INSTANCE_COUNT; ++i){
            Dif[i].x = 2 * NX::RandUnitFloat() - 1;
            Dif[i].y = 2 * NX::RandUnitFloat() - 1;
        }
        glBufferData(GL_ARRAY_BUFFER, sizeof(Dif), Dif, GL_STATIC_DRAW);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Dif[0]), BUFFER_OFFSET(0));
        glEnableVertexAttribArray(2);
        glVertexAttribDivisor(2, 1);
    }
    
    {//ibo
        glGenBuffers(1, &ibo);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
        GLbyte idx[] = {0};
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(idx), idx, GL_STATIC_DRAW);
    }
    
    {//clear
        glBindVertexArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        glUseProgram(0);
    }
    GLint xx;
    glGetIntegerv(GL_SAMPLES, &xx);
    std::cout << "you know " << xx << std::endl;
    return true;
}
	bool initVertexArray()
	{
		// Build a vertex array object
		glGenVertexArrays(1, &VertexArrayName);
		glBindVertexArray(VertexArrayName);
			glBindBuffer(GL_ARRAY_BUFFER, ArrayBufferName);
			glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fc4f), BUFFER_OFFSET(0));
			glVertexAttribPointer(semantic::attr::COLOR, 4, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fc4f), BUFFER_OFFSET(sizeof(glm::vec2)));
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glEnableVertexAttribArray(semantic::attr::POSITION);
			glEnableVertexAttribArray(semantic::attr::COLOR);
		glBindVertexArray(0);

		return this->checkError("initVertexArray");
	}
void CRenderingContext::SetTexCoordBuffer(size_t iOffset, size_t iStride, size_t iChannel)
{
	TAssert(iChannel >= 0 && iChannel < MAX_TEXTURE_CHANNELS);

	if (m_pShader->m_aiTexCoordAttributes[iChannel] == ~0)
		return;

	TAssert(iOffset%4 == 0);	// Should be multiples of four because it's offsets in bytes and we're always working with floats or doubles
	glEnableVertexAttribArray(m_pShader->m_aiTexCoordAttributes[iChannel]);
	glVertexAttribPointer(m_pShader->m_aiTexCoordAttributes[iChannel], 2, GL_FLOAT, false, iStride, BUFFER_OFFSET(iOffset));
}
Example #20
0
	bool initVertexArray()
	{
		glGenVertexArrays(vertex_format::MAX, &VertexArrayName[0]);
		glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);

		std::size_t CurrentOffset(0);
		glBindVertexArray(VertexArrayName[vertex_format::F32]);
		glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), BUFFER_OFFSET(CurrentOffset));
		glEnableVertexAttribArray(semantic::attr::POSITION);
		
		CurrentOffset += PositionSizeF32;
		glBindVertexArray(VertexArrayName[vertex_format::I8]);
		glVertexAttribPointer(semantic::attr::POSITION, 2, GL_BYTE, GL_FALSE, sizeof(glm::u8vec2), BUFFER_OFFSET(CurrentOffset));
		glEnableVertexAttribArray(semantic::attr::POSITION);

		CurrentOffset += PositionSizeI8;
		glBindVertexArray(VertexArrayName[vertex_format::I32]);
		glVertexAttribPointer(semantic::attr::POSITION, 2, GL_INT, GL_FALSE, sizeof(glm::i32vec2), BUFFER_OFFSET(CurrentOffset));
		glEnableVertexAttribArray(semantic::attr::POSITION);

		CurrentOffset += PositionSizeI32;
		glBindVertexArray(VertexArrayName[vertex_format::RGB10A2]);
		glVertexAttribPointer(semantic::attr::POSITION, 4, GL_INT_2_10_10_10_REV, GL_TRUE, sizeof(glm::uint), BUFFER_OFFSET(CurrentOffset));
		glEnableVertexAttribArray(semantic::attr::POSITION);

		CurrentOffset += PositionSizeRGB10A2;
		glBindVertexArray(VertexArrayName[vertex_format::F16]);
		glVertexAttribPointer(semantic::attr::POSITION, 2, GL_HALF_FLOAT, GL_FALSE, sizeof(glm::uint16) * 2, BUFFER_OFFSET(CurrentOffset));
		glEnableVertexAttribArray(semantic::attr::POSITION);

		CurrentOffset += PositionSizeRG11FB10F;
		glBindVertexArray(VertexArrayName[vertex_format::RG11B10F]);
		glVertexAttribPointer(semantic::attr::POSITION, 3, GL_UNSIGNED_INT_10F_11F_11F_REV, GL_FALSE, sizeof(glm::uint), BUFFER_OFFSET(CurrentOffset));
		glEnableVertexAttribArray(semantic::attr::POSITION);
		
		glBindVertexArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		return this->checkError("initVertexArray");
	}
	bool initVertexArray()
	{
		glGenVertexArrays(1, &VertexArrayName);
		glBindVertexArray(VertexArrayName);
			glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
			glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fc4ub), BUFFER_OFFSET(0));
			glVertexAttribPointer(semantic::attr::COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(glf::vertex_v2fc4ub), BUFFER_OFFSET(sizeof(glm::vec2)));
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glEnableVertexAttribArray(semantic::attr::POSITION);
			glEnableVertexAttribArray(semantic::attr::COLOR);
		glBindVertexArray(0);

		return this->checkError("initVertexArray");
	}
Example #22
0
void myDisplay()
{
    test++;

    printf("myDisplay\n");
    glClearColor(1.0, 0.0, 0.0, 0.0);
//    glClearDepth(1.0);
    glClear(GL_COLOR_BUFFER_BIT);
    
//    glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
//    glRotatef(spin, 0.0, 0.0, 1.0);
    
    glColor3f(1.0, 1.0, 1.0);
//    glPolygonMode(GL_BACK, GL_FILL);
//    glEnable(GL_CULL_FACE);
//    glCullFace(GL_BACK);
    GLubyte fly[] = {
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x03, 0x80, 0x01, 0xC0, 0x06, 0xC0, 0x03, 0x60,
        0x04, 0x60, 0x06, 0x20, 0x04, 0x30, 0x0C, 0x20,
        0x04, 0x18, 0x18, 0x20, 0x04, 0x0C, 0x30, 0x20,
        0x04, 0x06, 0x60, 0x20, 0x44, 0x03, 0xC0, 0x22,
        0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
        0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
        0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22,
        0x66, 0x01, 0x80, 0x66, 0x33, 0x01, 0x80, 0xCC,
        0x19, 0x81, 0x81, 0x98, 0x0C, 0xC1, 0x83, 0x30,
        0x07, 0xe1, 0x87, 0xe0, 0x03, 0x3f, 0xfc, 0xc0,
        0x03, 0x31, 0x8c, 0xc0, 0x03, 0x33, 0xcc, 0xc0,
        0x06, 0x64, 0x26, 0x60, 0x0c, 0xcc, 0x33, 0x30,
        0x18, 0xcc, 0x33, 0x18, 0x10, 0xc4, 0x23, 0x08,
        0x10, 0x63, 0xC6, 0x08, 0x10, 0x30, 0x0c, 0x08,
        0x10, 0x18, 0x18, 0x08, 0x10, 0x00, 0x00, 0x08};
//    glEnable(GL_POLYGON_STIPPLE);
//    glPolygonStipple(fly);
//    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//    glBegin(GL_POLYGON);
//    glEdgeFlag(true);
//    glVertex3f(0.25*windows_width, 0.25*windows_height, 0.0);
//    glVertex3f(0.75*windows_width, 0.25*windows_height, 0.0);
//    glVertex3f(0.75*windows_width, 0.75*windows_height, 0.0);
//    glVertex3f(0.25*windows_width, 0.75*windows_height, 0.0);
//    glEnd();
//
//    glColor3f(1.0, 1.0, 0.0);
//    glRectf(-0.5f*windows_width, -0.5f*windows_height,
//            0.5*windows_width, 0.5*windows_height);
    
//    glColor3f(1.0, 1.0, 1.0);
//    glLineStipple(2, 0x3F07);//0011111100000111
//    glEnable(GL_LINE_STIPPLE);
//    glLineWidth(5);
//    glBegin(GL_LINES);
//    glVertex2f(0.25*windows_width, 0.25*windows_height);
//    glVertex2f(0.75*windows_width, 0.75*windows_height);
//    glEnd();
    
//    static GLint vertices[] = {25, 25,
//        100, 325,
//        175, 25,
//        175, 325,
//        250, 25,
//        325, 325};
//    static GLint vertices[] = {100, 100,
//        150, 150,
//        150, 350,
//        100, 300,
//        300, 100,
//        350, 150,
//        350, 350,
//        300, 300
//    };
//    static GLfloat colors[] = {1.0, 0.2, 0.2,
//        0.2, 0.2, 1.0,
//        0.8, 1.0, 0.2,
//        0.75, 0.75, 0.75,
//        0.35, 0.35, 0.35,
//        0.5, 0.5, 0.5};
    
//    glEnableClientState(GL_VERTEX_ARRAY);
//    glEnableClientState(GL_COLOR_ARRAY);
//    
//    glColorPointer(3, GL_FLOAT, 0, colors);
//    glVertexPointer(2, GL_INT, 0, vertices);
    
//    glBegin(GL_TRIANGLES);
//    glArrayElement(0);
//    glArrayElement(1);
//    glArrayElement(2);
//    glArrayElement(3);
//    glArrayElement(4);
//    glArrayElement(5);
//    glEnd();
    
//    static GLubyte allIndices[] = {0,1,2,3,4,5};
//    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, allIndices);
//    glDrawArrays(GL_TRIANGLES, 0, 6);
    
//    static GLubyte frontIndices[] = {4, 5, 6, 7};
//    static GLubyte rightIndices[] = {1, 2, 6, 5};
//    static GLubyte bottomIndices[] = {0, 1, 5, 4};
//    static GLubyte backIndices[] = {0, 3, 2, 1};
//    static GLubyte leftIndices[] = {0, 4, 7, 3};
//    static GLubyte topIndices[] = {2, 3, 7, 6};
//    glLineStipple(5, 0x3F07);
//    glEnable(GL_LINE_STIPPLE);
//    
//    glDrawElements(GL_LINE_STRIP, 4, GL_UNSIGNED_BYTE, frontIndices);
//    glDrawElements(GL_LINE_STRIP, 4, GL_UNSIGNED_BYTE, rightIndices);
//    glDrawElements(GL_LINE_STRIP, 4, GL_UNSIGNED_BYTE, bottomIndices);
//    glDrawElements(GL_LINE_STRIP, 4, GL_UNSIGNED_BYTE, backIndices);
//    glDrawElements(GL_LINE_STRIP, 4, GL_UNSIGNED_BYTE, leftIndices);
//    glDrawElements(GL_LINE_STRIP, 4, GL_UNSIGNED_BYTE, topIndices);
    
//    static GLubyte allIndices[] = {4, 5, 6, 7, 1, 2, 6, 5,
//        0, 1, 5, 4, 0, 3, 2, 1,
//        0, 4, 7, 3, 2, 3, 7, 6};
//    
//    glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, allIndices);
    
    GLuint  buffers[NUM_BUFFERS];
    GLfloat vertices[][3] = {
        { -1.0, -1.0, -1.0 },
        {  1.0, -1.0, -1.0 },
        {  1.0,  1.0, -1.0 },
        { -1.0,  1.0, -1.0 },
        { -1.0, -1.0,  1.0 },
        {  1.0, -1.0,  1.0 },
        {  1.0,  1.0,  1.0 },
        { -1.0,  1.0,  1.0 }
    };
    GLubyte indices[][4] = {
        { 0, 1, 2, 3 },
        { 4, 7, 6, 5 },
        { 0, 4, 5, 1 },
        { 3, 2, 6, 7 },
        { 0, 3, 7, 4 },
        { 1, 5, 6, 2 }
    };
    
    glGenBuffers(NUM_BUFFERS, buffers);
    glBindBuffer(GL_ARRAY_BUFFER, buffers[VERTICES]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                 GL_STATIC_DRAW);
    glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));
    glEnableClientState(GL_VERTEX_ARRAY);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[INDICES]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices,GL_STATIC_DRAW);
    glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE,
                   BUFFER_OFFSET(0));

    glFlush();
    
    printf("myDisplay\n");
}
Example #23
0
void
display( void )
{
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
 
	

//Make sure you start with the Default Coordinate Systems
	projmat=mat4(1.0);
	model_view = mat4(1.0);
	
//Set up the camera optics
	projmat = projmat*Perspective(90,1.0,0.1,20.0); 

//Sky Box @  infinity
	vec4 skyboxEye = vec4(0.0, 0.0, 0.0, 1.0);
	model_view = LookAt(skyboxEye, skyboxEye-n, v);

	glUseProgram(program[1]);
	proj_loc       = glGetUniformLocation(program[1], "Projection");
	model_view_loc = glGetUniformLocation(program[1], "ModelView");
	glUniformMatrix4fv(proj_loc, 1, GL_TRUE, projmat);
	glUniformMatrix4fv(model_view_loc, 1, GL_TRUE, model_view);
	glUniform1i(glGetUniformLocation(program[1], "CubeMap"), 0);
	


	glBindVertexArray(VAO[1]);

	glCullFace(GL_BACK);
	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);
	glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
	glDrawArrays(GL_QUADS, 0, 24);
	
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);


	glUseProgram(0);


	model_view = Angel::mat4(1.0);

//Render the  rest of the scene

	//Position and orient the camera
	model_view = LookAt(eye, eye-n, v)*model_view;
	//Render surface mesh

    glUseProgram(program[0]);
	color_loc = glGetUniformLocation(program[0], "color");
	proj_loc       = glGetUniformLocation(program[0], "projection");
	model_view_loc = glGetUniformLocation(program[0], "modelview");
	glUniformMatrix4fv(proj_loc, 1, GL_TRUE, projmat);
	glUniformMatrix4fv(model_view_loc, 1, GL_TRUE, model_view);
    glUniform4fv(color_loc, 1, green_transparent);
	
	glPolygonOffset(1.0, 1.0);
	glBindVertexArray(VAO[0]);
	glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
	

	model_view = Angel::mat4(1.0);



	glutSwapBuffers();

}
    void StaticGeometryBuffer::bind() const
    {
        glBindBuffer( GL_ARRAY_BUFFER,          _vertexBufferHandle );
        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  _indexBufferHandle  );

        glEnableVertexAttribArray( VertexTags::Position );
        glVertexAttribPointer(VertexTags::Position, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), BUFFER_OFFSET( 0 ) );
			
        int vertexProperties = getVertexProperties();

        if( vertexProperties & GG::TEXCOORDS )
        {
            glEnableVertexAttribArray(VertexTags::Uv0);
            glVertexAttribPointer(VertexTags::Uv0, 2, GL_FLOAT, GL_FALSE, sizeof( Vertex ), BUFFER_OFFSET( 3 * sizeof( float ) ) );
        }
        else
        {
            glDisableVertexAttribArray(VertexTags::Uv0 );
        }

        if( vertexProperties & GG::NORMALS )
        {
            glEnableVertexAttribArray(VertexTags::Normal );
            glVertexAttribPointer(VertexTags::Normal, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), BUFFER_OFFSET( 5 * sizeof( float ) ) );
        }
        else
        {
            glDisableVertexAttribArray(VertexTags::Normal );
        }

        if( vertexProperties & GG::TANGENTS )
        {
            glEnableVertexAttribArray(VertexTags::Tangent );
            glVertexAttribPointer(VertexTags::Tangent, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), BUFFER_OFFSET( 8 * sizeof( float ) ) );
        }
        else
        {
            glDisableVertexAttribArray(VertexTags::Tangent );
        }

        if( vertexProperties & GG::BITANGENTS )
        {
            glEnableVertexAttribArray(VertexTags::Bitangent );
            glVertexAttribPointer(VertexTags::Bitangent, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), BUFFER_OFFSET( 11 * sizeof( float ) ) );
        }
        else
        {
            glDisableVertexAttribArray(VertexTags::Bitangent );
        }

        if( vertexProperties & GG::COLORS )
        {
            glEnableVertexAttribArray(VertexTags::Color );
            glVertexAttribPointer(VertexTags::Color, 4, GL_FLOAT, GL_FALSE, sizeof( Vertex ), BUFFER_OFFSET( 14 * sizeof( float ) ) );
        }
        else
        {
            glDisableVertexAttribArray(VertexTags::Color );
        }
    }
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, gaussianBlurVerticalPass_fboId);//----
        //-------------------------------------------------------------------------------------                                         
        glClearColor( 1.0f, 0.0f, 0.0f, 0.5f );
        glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); 
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 
        
        glViewport(0, 0, (GLsizei)viewWidth / resize_LIGHTS_FBO, (GLsizei)viewHeight / resize_LIGHTS_FBO);
        //----------------------------------------------------------------------------------
        glUseProgram(frameBufferPlane_GaussianVertical_SHADER);                                                                                                                                              
        glBindBuffer(GL_ARRAY_BUFFER, frameBufferPlane_VBO);                                                                                                                                
        //------------------------------------------------------------------------------------------------------------------------------------           
        glVertexAttribPointer(0,   3, GL_FLOAT, GL_FALSE, 20, BUFFER_OFFSET(0));                                                                                                  
        glEnableVertexAttribArray(0);	                                                                                                                                          
        glVertexAttribPointer(1,   2, GL_FLOAT, GL_FALSE, 20, BUFFER_OFFSET(12));                                                                                                 
        glEnableVertexAttribArray(1);                                                                                                                                             
        //---------------------------------------------------------------------------------------------------------------------------------------------------|__UNIFORMS          
        glUniform1f (UNIFORM_blurRadius_frameBufferPlane_GaussianVertical, frameBufferPlane_GaussianVertical_blurRadius);                                                                                                                           
        glUniform1f (UNIFORM_screenRatio_frameBufferPlane_GaussianVertical, screenRatio);            
        glUniform1i (UNIFORM_TEXTURE_frameBufferPlane_GaussianVertical, 0 );                                                                                                                                 
        
        //---------------------------------------------------------------------------------------------------------------------------------------------------|__DRAW              
        glDrawArrays(GL_TRIANGLES, 0, 6);                                                                                                     
        //---------------------------------------------------------------------------------------------------------------------
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);    //--------------------------------
        
        
        
                 
  
Example #26
0
int main (int argc, char** argv) {
	// Standard stuff...
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutCreateWindow("Diffuse Lighting");
	glutReshapeFunc(changeViewport);
	glutDisplayFunc(render);
	glewInit();

	initMatrices(); 

	// Make a shader
	char* vertexShaderSourceCode = readFile("vertexShader.vsh");
	char* fragmentShaderSourceCode = readFile("fragmentShader.fsh");
	GLuint vertShaderID = makeVertexShader(vertexShaderSourceCode);
	GLuint fragShaderID = makeFragmentShader(fragmentShaderSourceCode);
	shaderProgramID = makeShaderProgram(vertShaderID, fragShaderID);

	// Create the "remember all"
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	// Create the buffer, but don't load anything yet
	//glBufferData(GL_ARRAY_BUFFER, 7*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
	glBufferData(GL_ARRAY_BUFFER, 6*NUM_VERTICES*sizeof(GLfloat), NULL, GL_STATIC_DRAW);		// NEW!! - We're only loading vertices and normals (6 elements, not 7)
	
	// Load the vertex points
	glBufferSubData(GL_ARRAY_BUFFER, 0, 3*NUM_VERTICES*sizeof(GLfloat), vertices);
	// Load the colors right after that
	//glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),4*NUM_VERTICES*sizeof(GLfloat), colors);
	glBufferSubData(GL_ARRAY_BUFFER, 3*NUM_VERTICES*sizeof(GLfloat),3*NUM_VERTICES*sizeof(GLfloat), normals);
	
	
#ifdef USING_INDEX_BUFFER
	glGenBuffers(1, &indexBufferID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, NUM_INDICES*sizeof(GLuint), indices, GL_STATIC_DRAW);
#endif
	
	// Find the position of the variables in the shader
	positionID = glGetAttribLocation(shaderProgramID, "s_vPosition");
	normalID = glGetAttribLocation(shaderProgramID, "s_vNormal");
	lightID = glGetUniformLocation(shaderProgramID, "vLight");	// NEW
	
	// ============ glUniformLocation is how you pull IDs for uniform variables===============
	perspectiveMatrixID = glGetUniformLocation(shaderProgramID, "mP");
	viewMatrixID = glGetUniformLocation(shaderProgramID, "mV");
	modelMatrixID = glGetUniformLocation(shaderProgramID, "mM");
	allRotsMatrixID = glGetUniformLocation(shaderProgramID, "mRotations");	// NEW
	//=============================================================================================

	glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, 0, 0);
	//glVertexAttribPointer(colorID, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(vertices)));
	
	glUseProgram(shaderProgramID);
	glEnableVertexAttribArray(positionID);
	glEnableVertexAttribArray(normalID);
	
	
	glEnable(GL_CULL_FACE);  // NEW! - we're doing real 3D now...  Cull (don't render) the backsides of triangles
	glCullFace(GL_BACK);	// Other options?  GL_FRONT and GL_FRONT_AND_BACK
	glEnable(GL_DEPTH_TEST);// Make sure the depth buffer is on.  As you draw a pixel, update the screen only if it's closer than previous ones
	
	glutMainLoop();
	
	return 0;
}
	bool initVertexArray()
	{
		glGenVertexArrays(program::MAX, &VertexArrayName[0]);
		glBindVertexArray(VertexArrayName[program::TEXTURE]);
			glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
			glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fv2f), BUFFER_OFFSET(0));
			glVertexAttribPointer(semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fv2f), BUFFER_OFFSET(sizeof(glm::vec2)));
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glEnableVertexAttribArray(semantic::attr::POSITION);
			glEnableVertexAttribArray(semantic::attr::TEXCOORD);

			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]);
		glBindVertexArray(0);

		glBindVertexArray(VertexArrayName[program::SPLASH]);
		glBindVertexArray(0);

		return true;
	}
Example #28
0
void RB_SurfaceVaoMdvMesh(srfVaoMdvMesh_t * surface)
{
	//mdvModel_t     *mdvModel;
	//mdvSurface_t   *mdvSurface;
	refEntity_t    *refEnt;

	GLimp_LogComment("--- RB_SurfaceVaoMdvMesh ---\n");

	if (ShaderRequiresCPUDeforms(tess.shader))
	{
		RB_SurfaceMesh(surface->mdvSurface);
		return;
	}

	if(!surface->vao)
		return;

	//RB_CheckVao(surface->vao);
	RB_EndSurface();
	RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex);

	R_BindVao(surface->vao);

	tess.useInternalVao = qfalse;

	tess.numIndexes = surface->numIndexes;
	tess.numVertexes = surface->numVerts;

	//mdvModel = surface->mdvModel;
	//mdvSurface = surface->mdvSurface;

	refEnt = &backEnd.currentEntity->e;

	glState.vertexAttribsInterpolation = (refEnt->oldframe == refEnt->frame) ? 0.0f : refEnt->backlerp;

	if (surface->mdvModel->numFrames > 1)
	{
		int frameOffset, attribIndex;
		vaoAttrib_t *vAtb;

		glState.vertexAnimation = qtrue;

		if (glRefConfig.vertexArrayObject)
		{
			qglBindBuffer(GL_ARRAY_BUFFER, surface->vao->vertexesVBO);
		}

		frameOffset    = refEnt->frame * surface->vao->frameSize;

		attribIndex = ATTR_INDEX_POSITION;
		vAtb = &surface->vao->attribs[attribIndex];
		qglVertexAttribPointer(attribIndex, vAtb->count, vAtb->type, vAtb->normalized, vAtb->stride, BUFFER_OFFSET(vAtb->offset + frameOffset));

		attribIndex = ATTR_INDEX_NORMAL;
		vAtb = &surface->vao->attribs[attribIndex];
		qglVertexAttribPointer(attribIndex, vAtb->count, vAtb->type, vAtb->normalized, vAtb->stride, BUFFER_OFFSET(vAtb->offset + frameOffset));

		attribIndex = ATTR_INDEX_TANGENT;
		vAtb = &surface->vao->attribs[attribIndex];
		qglVertexAttribPointer(attribIndex, vAtb->count, vAtb->type, vAtb->normalized, vAtb->stride, BUFFER_OFFSET(vAtb->offset + frameOffset));

		frameOffset = refEnt->oldframe * surface->vao->frameSize;

		attribIndex = ATTR_INDEX_POSITION2;
		vAtb = &surface->vao->attribs[attribIndex];
		qglVertexAttribPointer(attribIndex, vAtb->count, vAtb->type, vAtb->normalized, vAtb->stride, BUFFER_OFFSET(vAtb->offset + frameOffset));

		attribIndex = ATTR_INDEX_NORMAL2;
		vAtb = &surface->vao->attribs[attribIndex];
		qglVertexAttribPointer(attribIndex, vAtb->count, vAtb->type, vAtb->normalized, vAtb->stride, BUFFER_OFFSET(vAtb->offset + frameOffset));

		attribIndex = ATTR_INDEX_TANGENT2;
		vAtb = &surface->vao->attribs[attribIndex];
		qglVertexAttribPointer(attribIndex, vAtb->count, vAtb->type, vAtb->normalized, vAtb->stride, BUFFER_OFFSET(vAtb->offset + frameOffset));


		if (!glRefConfig.vertexArrayObject)
		{
			attribIndex = ATTR_INDEX_TEXCOORD;
			vAtb = &surface->vao->attribs[attribIndex];
			qglVertexAttribPointer(attribIndex, vAtb->count, vAtb->type, vAtb->normalized, vAtb->stride, BUFFER_OFFSET(vAtb->offset));
		}
	}

	RB_EndSurface();

	// So we don't lerp surfaces that shouldn't be lerped
	glState.vertexAnimation = qfalse;
}
	bool initVertexArray()
	{
		glGenVertexArrays(1, &VertexArrayName);
		glBindVertexArray(VertexArrayName);
			glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
			glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), BUFFER_OFFSET(0));
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glEnableVertexAttribArray(semantic::attr::POSITION);
		glBindVertexArray(0);

		return true;
	}
	bool initVertexArray()
	{
		glGenVertexArrays(1, &VertexArrayName);
		glBindVertexArray(VertexArrayName);
			glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
			glVertexAttribPointer(semantic::attr::POSITION + 0, 2, GL_FLOAT, GL_FALSE,(GLint) sizeof(glf::vertex_v2fc4d), BUFFER_OFFSET(0));
			glVertexAttribPointer(semantic::attr::POSITION + 1, 2, GL_FLOAT, GL_FALSE,(GLint) sizeof(glf::vertex_v2fc4d), BUFFER_OFFSET(0));
			glVertexAttribLPointer(semantic::attr::COLOR, 4, GL_DOUBLE, (GLint)sizeof(glf::vertex_v2fc4d), BUFFER_OFFSET(sizeof(glm::vec2)));
			//glVertexAttribLPointer(semantic::attr::COLOR, 4, GL_DOUBLE, (GLint)sizeof(glf::vertex_v2fc4d), BUFFER_OFFSET(sizeof(glm::vec2)));
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glEnableVertexAttribArray(semantic::attr::POSITION + 0);
			glEnableVertexAttribArray(semantic::attr::POSITION + 1);
			glEnableVertexAttribArray(semantic::attr::COLOR);
		glBindVertexArray(0);

		std::vector<vertexattrib> Valid(16); 
		Valid[semantic::attr::POSITION + 0] = vertexattrib(GL_TRUE, 2, (GLint)sizeof(glf::vertex_v2fc4d), GL_FLOAT, GL_FALSE, GL_FALSE, GL_FALSE, 0, 0, NULL);
		Valid[semantic::attr::POSITION + 1] = vertexattrib(GL_TRUE, 2, (GLint)sizeof(glf::vertex_v2fc4d), GL_FLOAT, GL_FALSE, GL_FALSE, GL_FALSE, 0, 0, NULL);
		Valid[semantic::attr::COLOR]        = vertexattrib(GL_TRUE, 4, (GLint)sizeof(glf::vertex_v2fc4d), GL_FLOAT, GL_FALSE, GL_FALSE, GL_FALSE, 0, 0, NULL);
		//Valid[semantic::attr::COLOR]        = vertexattrib(GL_TRUE, 4, (GLint)sizeof(glf::vertex_v2fc4d), GL_DOUBLE, GL_FALSE, GL_FALSE, GL_FALSE, 0, BUFFER_OFFSET(sizeof(glm::vec2)),NULL);

		// TODO
		//glf::validateVAO(VertexArrayName, Valid);

		return true;
	}