Пример #1
0
int APIENTRY WinMain(HINSTANCE hCurrentInst, HINSTANCE hPreviousInst,LPSTR lpszCmdLine, int nCmdShow) // int main(int argc, char *argv[])
{
	std::cout << "Test Physics\n";

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

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



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

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

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

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


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

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

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

		wmdraw(world_slab);  // world_geometry

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

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

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

	std::cout << "\n";
	return 0;
}
Пример #2
0
void RenderScene(void) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    glFrontFace(GL_CW);
    glUseProgram(shader);
    M3DVector3f at={1.5f, 0.0f, 0.0f};
    M3DVector3f up={-1.0f, 0.0f, 1.0f};
    M3DVector3f eye;
    float angle = timer.GetElapsedSeconds()*3.14159f/8;
    eye[0]= 6.8f * cos(angle);
    eye[1]= 6.0f * sin(angle);
    eye[2]= 30.0f;
    LookAt(cameraFrame,eye,at,up);

    M3DVector3f ambientLight = {1.0f, 1.0f, 1.0f};
    M3DVector3f position = {10.0f, 10.0f, 5.0f};
    M3DVector3f color = {1.0f, 1.0f, 1.0f};
    float l_angle = 90.0f;
    float attenuation0 = 0.01f;
    float attenuation1 = 0.01f;
    float attenuation2 = 0.01f;
    M3DVector3f ambientColor = {0.0f, 1.0, 0.0};
    M3DVector3f diffuseColor = {0.0f, 1.0f, 1.0f};
    M3DVector3f specularColor = {1.0f, 1.0f, 1.0f};
    float specularExponent = 8;

    projection.LoadMatrix(viewFrustum.GetProjectionMatrix());
    modelView.PushMatrix();
    M3DMatrix44f mCamera;
    cameraFrame.GetCameraMatrix(mCamera);
    modelView.LoadMatrix(mCamera);
    modelView.PushMatrix();

glUniform3fv(shaderPositionLocation, 1, position);
glUniform3fv(shaderColorLocation, 1, color);
glUniform1f(shaderAngleLocation, angle);
glUniform1f(shaderAttenuation0Location, attenuation0);
glUniform1f(shaderAttenuation1Location, attenuation1);
glUniform1f(shaderAttenuation2Location, attenuation2);

    glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
    glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
    glUniformMatrix3fv(normalMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
    glUniform3fv(ambientLightLocation, 1, ambientLight);

    glUniform3fv(shaderAmbientColorLocation, 1, ambientColor);
    glUniform3fv(shaderDiffuseColorLocation, 1, diffuseColor);
    glUniform3fv(shaderSpecularColorLocation, 1, specularColor);
    glUniform1f(shaderSpecularExponentLocation, specularExponent);

    glPolygonOffset(1.0f, 1.0f);
	grid();
    glEnable(GL_POLYGON_OFFSET_FILL);
	grid();
    glDisable(GL_POLYGON_OFFSET_FILL);
   

	modelView.PopMatrix();
    modelView.PushMatrix();
    modelView.Translate(-7.75f, -7.75f, 0.0f);
	modelView.Scale(0.25f, 0.25f, 0.25f);
    glUniform3fv(shaderPositionLocation, 1, position);
    glUniform3fv(shaderColorLocation, 1, color);
    glUniform1f(shaderAngleLocation, l_angle);
    glUniform1f(shaderAttenuation0Location, attenuation0);
    glUniform1f(shaderAttenuation1Location, attenuation1);
    glUniform1f(shaderAttenuation2Location, attenuation2);
    glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
    glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
    glUniformMatrix3fv(normalMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
	glUniform3fv(ambientLightLocation, 1, ambientLight);
    glUniform3fv(shaderAmbientColorLocation, 1, ambientColor);
    glUniform3fv(shaderDiffuseColorLocation, 1, diffuseColor);
    glUniform3fv(shaderSpecularColorLocation, 1, specularColor);
    glUniform1f(shaderSpecularExponentLocation, specularExponent);
	
	piramida();

	modelView.PopMatrix();
    modelView.PushMatrix();
    modelView.Translate(-6.0f, -6.0f, 0.0f);
	modelView.Scale(0.5f, 0.5f, 0.5f);
	modelView.Rotate(angle*512, 0.0f, 0.0f, 2.0f);
    glUniform3fv(shaderPositionLocation, 1, position);
    glUniform3fv(shaderColorLocation, 1, color);
    glUniform1f(shaderAngleLocation, l_angle);
    glUniform1f(shaderAttenuation0Location, attenuation0);
    glUniform1f(shaderAttenuation1Location, attenuation1);
    glUniform1f(shaderAttenuation2Location, attenuation2);
    glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
    glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
    glUniformMatrix3fv(normalMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
    glUniform3fv(ambientLightLocation, 1, ambientLight);
    glUniform3fv(shaderAmbientColorLocation, 1, ambientColor);
    glUniform3fv(shaderDiffuseColorLocation, 1, diffuseColor);
    glUniform3fv(shaderSpecularColorLocation, 1, specularColor);
    glUniform1f(shaderSpecularExponentLocation, specularExponent);
	
	glDrawElements(GL_TRIANGLES,3*n_faces,GL_UNSIGNED_INT,0);

	modelView.PopMatrix();
    modelView.PushMatrix();
    modelView.Translate(-4.0f, -4.0f, 0.0f);
	modelView.Scale(0.75f, 0.75f, 0.75f);
	modelView.Rotate(angle*512, 0.0f, 2.0f, 0.0f);
	glUniform3fv(shaderPositionLocation, 1, position);
    glUniform3fv(shaderColorLocation, 1, color);
    glUniform1f(shaderAngleLocation, l_angle);
    glUniform1f(shaderAttenuation0Location, attenuation0);
    glUniform1f(shaderAttenuation1Location, attenuation1);
    glUniform1f(shaderAttenuation2Location, attenuation2);
    glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
    glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
    glUniformMatrix3fv(normalMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
    glUniform3fv(ambientLightLocation, 1, ambientLight);
    glUniform3fv(shaderAmbientColorLocation, 1, ambientColor);
    glUniform3fv(shaderDiffuseColorLocation, 1, diffuseColor);
    glUniform3fv(shaderSpecularColorLocation, 1, specularColor);
    glUniform1f(shaderSpecularExponentLocation, specularExponent);
    
	piramida();

	modelView.PopMatrix();`
    modelView.PushMatrix();
    modelView.Translate(2.0f, 2.0f, 0.0f);
    modelView.Scale(1.5f, 1.5f, 1.5f);
	modelView.Rotate(angle*512, 2.0f, 2.0f, 0.0f);
	glUniform3fv(shaderPositionLocation, 1, position);
    glUniform3fv(shaderColorLocation, 1, color);
    glUniform1f(shaderAngleLocation, l_angle);
    glUniform1f(shaderAttenuation0Location, attenuation0);
    glUniform1f(shaderAttenuation1Location, attenuation1);
    glUniform1f(shaderAttenuation2Location, attenuation2);
    glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
    glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
    glUniformMatrix3fv(normalMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
    glUniform3fv(ambientLightLocation, 1, ambientLight);
    glUniform3fv(shaderAmbientColorLocation, 1, ambientColor);
    glUniform3fv(shaderDiffuseColorLocation, 1, diffuseColor);
    glUniform3fv(shaderSpecularColorLocation, 1, specularColor);
    glUniform1f(shaderSpecularExponentLocation, specularExponent);
    
	piramida();

	modelView.PopMatrix();
    modelView.PushMatrix();
	modelView.Translate(-1.5f, -1.5f, 0.0f);
	modelView.Rotate(angle*512, 2.0f, 0.0f, 0.0f);
	glUniform3fv(shaderPositionLocation, 1, position);
    glUniform3fv(shaderColorLocation, 1, color);
    glUniform1f(shaderAngleLocation, l_angle);
    glUniform1f(shaderAttenuation0Location, attenuation0);
    glUniform1f(shaderAttenuation1Location, attenuation1);
    glUniform1f(shaderAttenuation2Location, attenuation2);
    glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
    glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
    glUniformMatrix3fv(normalMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
    glUniform3fv(ambientLightLocation, 1, ambientLight);
    glUniform3fv(shaderAmbientColorLocation, 1, ambientColor);
    glUniform3fv(shaderDiffuseColorLocation, 1, diffuseColor);
    glUniform3fv(shaderSpecularColorLocation, 1, specularColor);
    glUniform1f(shaderSpecularExponentLocation, specularExponent);

	DrawTriangles(20, vertices_tab, faces_tab);
	
	modelView.PopMatrix();
	modelView.PushMatrix();
    modelView.Translate(6.5f, 6.5f, 0.0f);
    modelView.Scale(2.5f, 2.5f, 2.5f);
	modelView.Rotate(angle*512, 2.0f, 2.0f, 2.0f);
	glUniform3fv(shaderPositionLocation, 1, position);
    glUniform3fv(shaderColorLocation, 1, color);
    glUniform1f(shaderAngleLocation, l_angle);
    glUniform1f(shaderAttenuation0Location, attenuation0);
    glUniform1f(shaderAttenuation1Location, attenuation1);
    glUniform1f(shaderAttenuation2Location, attenuation2);
    glUniformMatrix4fv(MVMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
    glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewMatrix());
    glUniformMatrix3fv(normalMatrixLocation,1,GL_FALSE,geometryPipeline.GetNormalMatrix());
    glUniform3fv(ambientLightLocation, 1, ambientLight);
    glUniform3fv(shaderAmbientColorLocation, 1, ambientColor);
    glUniform3fv(shaderDiffuseColorLocation, 1, diffuseColor);
    glUniform3fv(shaderSpecularColorLocation, 1, specularColor);
    glUniform1f(shaderSpecularExponentLocation, specularExponent);
	
	DrawSmoothTriangles(20, vertices_tab, faces_tab);

	modelView.PopMatrix();
    modelView.PopMatrix();
    glutSwapBuffers();
    glutPostRedisplay();
}
Пример #3
0
GLUSboolean init(GLUSvoid)
{
    GLUSshape background;

    GLUSshape torus;

    GLUStextfile vertexSource;
    GLUStextfile fragmentSource;

    GLfloat viewMatrix[16];

    GLfloat lightDirection[3];

    GLenum none[] = {GL_NONE};

    lightDirection[0] = g_lightPosition[0];
    lightDirection[1] = g_lightPosition[1];
    lightDirection[2] = g_lightPosition[2];

    glusVector3Normalizef(lightDirection);

    //

    glusLoadTextFile("../Example12_ES/shader/rendershadow.vert.glsl", &vertexSource);
    glusLoadTextFile("../Example12_ES/shader/rendershadow.frag.glsl", &fragmentSource);

    glusBuildProgramFromSource(&g_programShadow, (const GLUSchar**) &vertexSource.text, (const GLUSchar**) &fragmentSource.text);

    glusDestroyTextFile(&vertexSource);
    glusDestroyTextFile(&fragmentSource);

    //

    glusLoadTextFile("../Example12_ES/shader/useshadow.vert.glsl", &vertexSource);
    glusLoadTextFile("../Example12_ES/shader/useshadow.frag.glsl", &fragmentSource);

    glusBuildProgramFromSource(&g_program, (const GLUSchar**) &vertexSource.text, (const GLUSchar**) &fragmentSource.text);

    glusDestroyTextFile(&vertexSource);
    glusDestroyTextFile(&fragmentSource);

    //

    g_projectionMatrixShadowLocation = glGetUniformLocation(g_programShadow.program, "u_projectionMatrix");
    g_modelViewMatrixShadowLocation = glGetUniformLocation(g_programShadow.program, "u_modelViewMatrix");
    g_vertexShadowLocation = glGetAttribLocation(g_programShadow.program, "a_vertex");

    //

    g_projectionMatrixLocation = glGetUniformLocation(g_program.program, "u_projectionMatrix");
    g_viewMatrixLocation = glGetUniformLocation(g_program.program, "u_viewMatrix");
    g_modelMatrixLocation = glGetUniformLocation(g_program.program, "u_modelMatrix");
    g_normalMatrixLocation = glGetUniformLocation(g_program.program, "u_normalMatrix");
    g_shadowMatrixLocation = glGetUniformLocation(g_program.program, "u_shadowMatrix");
    g_shadowTextureLocation = glGetUniformLocation(g_program.program, "u_shadowTexture");
    g_colorLocation = glGetUniformLocation(g_program.program, "u_shapeColor");
    g_lightDirectionLocation = glGetUniformLocation(g_program.program, "u_lightDirection");

    g_vertexLocation = glGetAttribLocation(g_program.program, "a_vertex");
    g_normalLocation = glGetAttribLocation(g_program.program, "a_normal");

    //

    glGenTextures(1, &g_shadowTexture);
    glBindTexture(GL_TEXTURE_2D, g_shadowTexture);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, g_shadowTextureSize, g_shadowTextureSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);

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

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);

    glBindTexture(GL_TEXTURE_2D, 0);

    //

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

    glDrawBuffers(1, none);
    glReadBuffer(GL_NONE);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, g_shadowTexture, 0);

    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    {
        printf("GL_FRAMEBUFFER_COMPLETE error 0x%x", glCheckFramebufferStatus(GL_FRAMEBUFFER));

        return GLUS_FALSE;
    }

    glClearDepthf(1.0f);

    glEnable(GL_DEPTH_TEST);

    glEnable(GL_CULL_FACE);

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    //

    glusCreateTorusf(&torus, 0.5f, 1.0f, 32, 32);
    g_numberIndicesSphere = torus.numberIndices;

    glGenBuffers(1, &g_verticesVBO);
    glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO);
    glBufferData(GL_ARRAY_BUFFER, torus.numberVertices * 4 * sizeof(GLfloat), (GLfloat*) torus.vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &g_normalsVBO);
    glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO);
    glBufferData(GL_ARRAY_BUFFER, torus.numberVertices * 3 * sizeof(GLfloat), (GLfloat*) torus.normals, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &g_indicesVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, torus.numberIndices * sizeof(GLuint), (GLuint*) torus.indices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glusDestroyShapef(&torus);

    //

    glusCreatePlanef(&background, 10.0f);
    g_numberIndicesBackground = background.numberIndices;

    glGenBuffers(1, &g_verticesBackgroundVBO);
    glBindBuffer(GL_ARRAY_BUFFER, g_verticesBackgroundVBO);
    glBufferData(GL_ARRAY_BUFFER, background.numberVertices * 4 * sizeof(GLfloat), (GLfloat*) background.vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &g_normalsBackgroundVBO);
    glBindBuffer(GL_ARRAY_BUFFER, g_normalsBackgroundVBO);
    glBufferData(GL_ARRAY_BUFFER, background.numberVertices * 3 * sizeof(GLfloat), (GLfloat*) background.normals, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glGenBuffers(1, &g_indicesBackgroundVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesBackgroundVBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, background.numberIndices * sizeof(GLuint), (GLuint*) background.indices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glusDestroyShapef(&background);

    //

    glUseProgram(g_program.program);

    glusLookAtf(viewMatrix, g_cameraPosition[0], g_cameraPosition[1], g_cameraPosition[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

    glusMatrix4x4MultiplyVector3f(lightDirection, viewMatrix, lightDirection);

    glUniform3fv(g_lightDirectionLocation, 1, lightDirection);

    glUniform1i(g_shadowTextureLocation, 0);

    // Torus

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

    glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO);
    glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(g_vertexLocation);

    glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO);
    glVertexAttribPointer(g_normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(g_normalLocation);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO);

    // Plane

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

    glBindBuffer(GL_ARRAY_BUFFER, g_verticesBackgroundVBO);
    glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(g_vertexLocation);

    glBindBuffer(GL_ARRAY_BUFFER, g_normalsBackgroundVBO);
    glVertexAttribPointer(g_normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(g_normalLocation);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesBackgroundVBO);

    //

    glUseProgram(g_programShadow.program);

    // Torus

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

    glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO);
    glVertexAttribPointer(g_vertexShadowLocation, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(g_vertexShadowLocation);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO);

    // Plane

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

    glBindBuffer(GL_ARRAY_BUFFER, g_verticesBackgroundVBO);
    glVertexAttribPointer(g_vertexShadowLocation, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(g_vertexShadowLocation);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesBackgroundVBO);

    //

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glClearDepthf(1.0f);

    glEnable(GL_DEPTH_TEST);

    glEnable(GL_CULL_FACE);

    // Needed when rendering the shadow map. This will avoid artifacts.
    glPolygonOffset(1.0f, 0.0f);

    return GLUS_TRUE;
}
Пример #4
0
void GLUTRedraw(void)
{
  // Set projection transformation
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  double mesh_radius = mesh->Radius(); 
  gluPerspective(180.0*camera_yfov/M_PI, (GLdouble) GLUTwindow_width /(GLdouble) GLUTwindow_height, 
    0.01 * mesh_radius, 100 * mesh_radius);

  // Set camera transformation
  R3Vector& t = camera_towards;
  R3Vector& u = camera_up;
  R3Vector r = camera_up % camera_towards;
  GLdouble camera_matrix[16] = { r[0], u[0], t[0], 0, r[1], u[1], t[1], 0, r[2], u[2], t[2], 0, 0, 0, 0, 1 };
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glMultMatrixd(camera_matrix);
  glTranslated(-camera_eye[0], -camera_eye[1], -camera_eye[2]);

  // Clear window 
  glClearColor(1.0, 1.0, 1.0, 1.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  // Set lights
  static GLfloat light0_position[] = { 3.0, 4.0, 5.0, 0.0 };
  glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
  static GLfloat light1_position[] = { -3.0, -2.0, -3.0, 0.0 };
  glLightfv(GL_LIGHT1, GL_POSITION, light1_position);

  // Draw faces
  if (show_faces) {
    glEnable(GL_LIGHTING);
    // glEnable(GL_TEXTURE_2D); //ABIUSX
    // glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); //ABIUSX


    static GLfloat diffuse[] = { 0.8, 0.8, 0.8, 1.0 };
    static GLfloat specular[] = { 0.2, 0.2, 0.2, 1.0 };
    static GLfloat shininess[] = { 64 };
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, diffuse); 
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); 
    glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess); 
    for (int i = 0; i < mesh->NFaces(); i++) {
      R3MeshFace *face = mesh->Face(i);
      if (face->isLeaf) //ABIUSX
        glBindTexture(GL_TEXTURE_2D, leaf); //ABIUSX
      else //ABIUSX
        glBindTexture(GL_TEXTURE_2D, tree); //ABIUSX
      glBegin(GL_POLYGON);

      const R3Vector& normal = face->plane.Normal();
      glNormal3d(normal[0], normal[1], normal[2]);
      for (unsigned int j = 0; j < face->vertices.size(); j++) {
        R3MeshVertex *vertex = face->vertices[j];
        const R3Point& p = vertex->position;
        // printf("%f %f\n",vertex->texcoords.X(),vertex->texcoords.Y());
        glTexCoord2f(vertex->texcoords.X(),vertex->texcoords.Y()); //ABIUSX
        // glTexCoord2f(p[0],p[1]); //ABIUSX
        glVertex3f(p[0], p[1], p[2]);
      }
      glEnd();
    }
  }

  // Draw edges
  if (show_edges) {
    glDisable(GL_LIGHTING);
    glColor3d(0.3, 0.3, 0.3);
    glLineWidth(3);
    for (int i = 0; i < mesh->NFaces(); i++) {
      glBegin(GL_LINE_LOOP);
      R3MeshFace *face = mesh->Face(i);
      for (unsigned int j = 0; j < face->vertices.size(); j++) {
        R3MeshVertex *vertex = face->vertices[j];
        const R3Point& p = vertex->position;
        glVertex3f(p[0], p[1], p[2]);
      }
      glEnd();
    }
  }

  // Draw vertices
  if (show_vertices) {
    glDisable(GL_LIGHTING);
    glColor3d(0, 0, 0);
    glPointSize(5);
    glBegin(GL_POINTS);
    for (int i = 0; i < mesh->NVertices(); i++) {
      R3MeshVertex *vertex = mesh->Vertex(i);
      const R3Point& p = vertex->position;
      glVertex3f(p[0], p[1], p[2]);
    }
    glEnd();
  }

  // Draw vertex IDs
  if (show_ids) {
    char buffer[256];
    glDisable(GL_LIGHTING);
    glColor3d(0, 0, 0);
    for (int i = 0; i < mesh->NVertices(); i++) {
      R3MeshVertex *vertex = mesh->Vertex(i);
      sprintf(buffer, "%d", vertex->id);
      GLUTDrawText(vertex->position, buffer);
    }
  }

  // Draw normals
  if (show_normals) {
    glDisable(GL_LIGHTING);
    glColor3d(0, 0, 0);
    glLineWidth(3);
    glBegin(GL_LINES);
    for (int i = 0; i < mesh->NVertices(); i++) {
      R3MeshVertex *vertex = mesh->Vertex(i);
      double length = vertex->AverageEdgeLength();
      const R3Point& p = vertex->position;
      R3Vector v = length * vertex->normal;
      glVertex3f(p[0], p[1], p[2]);
      glVertex3f(p[0] + v[0], p[1] + v[1], p[2] + v[2]);
    }
    glEnd();
  }

  // Draw curvatures
  if (show_curvatures) {
    glDisable(GL_LIGHTING);
    glPointSize(10);
    glBegin(GL_POINTS);
    for (int i = 0; i < mesh->NVertices(); i++) {
      R3MeshVertex *vertex = mesh->Vertex(i);
      const R3Point& p = vertex->position;
      double curvature = vertex->curvature;
      double magnitude = curvature * mesh->Radius();
      if (curvature < 0) glColor3d(-magnitude, 0, 0);
      else glColor3d(0, 0, magnitude);
      glVertex3f(p[0], p[1], p[2]);
    }
    glEnd();
  }

  // Draw bounding box
  if (show_bbox) {
    const R3Box& bbox = mesh->bbox;
    glDisable(GL_LIGHTING);
    glColor3d(1, 0, 0);
    glLineWidth(3);
    glBegin(GL_LINE_LOOP);
    glVertex3d(bbox[0][0], bbox[0][1], bbox[0][2]);
    glVertex3d(bbox[0][0], bbox[0][1], bbox[1][2]);
    glVertex3d(bbox[0][0], bbox[1][1], bbox[1][2]);
    glVertex3d(bbox[0][0], bbox[1][1], bbox[0][2]);
    glVertex3d(bbox[0][0], bbox[0][1], bbox[0][2]);
    glVertex3d(bbox[1][0], bbox[0][1], bbox[0][2]);
    glVertex3d(bbox[1][0], bbox[0][1], bbox[1][2]);
    glVertex3d(bbox[1][0], bbox[1][1], bbox[1][2]);
    glVertex3d(bbox[1][0], bbox[1][1], bbox[0][2]);
    glVertex3d(bbox[1][0], bbox[0][1], bbox[0][2]);
    glVertex3d(bbox[1][0], bbox[0][1], bbox[1][2]);
    glVertex3d(bbox[0][0], bbox[0][1], bbox[1][2]);
    glVertex3d(bbox[0][0], bbox[1][1], bbox[1][2]);
    glVertex3d(bbox[1][0], bbox[1][1], bbox[1][2]);
    glVertex3d(bbox[1][0], bbox[1][1], bbox[0][2]);
    glVertex3d(bbox[0][0], bbox[1][1], bbox[0][2]);
    glEnd();
  }

  // Draw pick position
  if (show_pick && pick_active) {
    // Draw pick position
    glEnable(GL_LIGHTING);
    static GLfloat diffuse[] = { 1, 0, 0, 1.0 };
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, diffuse); 
    double radius = 0.01 * mesh->Radius();
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glTranslated(pick_position[0], pick_position[1], pick_position[2]);
    static GLUquadricObj *sphere = gluNewQuadric();
    gluQuadricNormals(sphere, (GLenum) GLU_SMOOTH);
    gluQuadricDrawStyle(sphere, (GLenum) GLU_FILL);
    gluSphere(sphere, radius, 8, 8);
    glPopMatrix();

    // Draw pick face
    if (pick_face) {
      glDisable(GL_LIGHTING);
      glColor3f(1, 1, 0);
      glEnable(GL_POLYGON_OFFSET_FILL);
      glPolygonOffset(-2, -2);
      glBegin(GL_POLYGON);
      for (unsigned int j = 0; j < pick_face->vertices.size(); j++) {
        R3MeshVertex *vertex = pick_face->vertices[j];
        const R3Point& p = vertex->position;
        glVertex3f(p[0], p[1], p[2]);
      }
      glEnd();
      glDisable(GL_POLYGON_OFFSET_FILL);
    }
  }

  // Write image
  if (save_image) {
    char image_name[256];
    static int image_number = 1;
    for (;;) {
      sprintf(image_name, "image%d.jpg", image_number++);
      FILE *fp = fopen(image_name, "r");
      if (!fp) break; 
      else fclose(fp);
    }
    GLUTSaveImage(image_name);
    printf("Saved %s\n", image_name);
    save_image = 0;
  }

  // Quit here so that can save image before exit
  if (quit) {
    if (output_image_name) GLUTSaveImage(output_image_name);
    if (output_mesh_name) mesh->Write(output_mesh_name);
    GLUTStop();
  }

  // Swap buffers 
  glutSwapBuffers();
}    
Пример #5
0
void GLGSRender::begin()
{
	rsx::thread::begin();

	init_buffers();

	std::chrono::time_point<std::chrono::system_clock> then = std::chrono::system_clock::now();

	bool color_mask_b = rsx::method_registers.color_mask_b();
	bool color_mask_g = rsx::method_registers.color_mask_g();
	bool color_mask_r = rsx::method_registers.color_mask_r();
	bool color_mask_a = rsx::method_registers.color_mask_a();

	__glcheck glColorMask(color_mask_r, color_mask_g, color_mask_b, color_mask_a);
	__glcheck glDepthMask(rsx::method_registers.depth_write_enabled());
	__glcheck glStencilMask(rsx::method_registers.stencil_mask());

	if (__glcheck enable(rsx::method_registers.depth_test_enabled(), GL_DEPTH_TEST))
	{
		__glcheck glDepthFunc(comparison_op(rsx::method_registers.depth_func()));
		__glcheck glDepthMask(rsx::method_registers.depth_write_enabled());
	}

	if (glDepthBoundsEXT && (__glcheck enable(rsx::method_registers.depth_bounds_test_enabled(), GL_DEPTH_BOUNDS_TEST_EXT)))
	{
		__glcheck glDepthBoundsEXT(rsx::method_registers.depth_bounds_min(), rsx::method_registers.depth_bounds_max());
	}

	__glcheck glDepthRange(rsx::method_registers.clip_min(), rsx::method_registers.clip_max());
	__glcheck enable(rsx::method_registers.dither_enabled(), GL_DITHER);

	if (__glcheck enable(rsx::method_registers.blend_enabled(), GL_BLEND))
	{
		__glcheck glBlendFuncSeparate(blend_factor(rsx::method_registers.blend_func_sfactor_rgb()),
			blend_factor(rsx::method_registers.blend_func_dfactor_rgb()),
			blend_factor(rsx::method_registers.blend_func_sfactor_a()),
			blend_factor(rsx::method_registers.blend_func_dfactor_a()));

		if (rsx::method_registers.surface_color() == rsx::surface_color_format::w16z16y16x16) //TODO: check another color formats
		{
			u16 blend_color_r = rsx::method_registers.blend_color_16b_r();
			u16 blend_color_g = rsx::method_registers.blend_color_16b_g();
			u16 blend_color_b = rsx::method_registers.blend_color_16b_b();
			u16 blend_color_a = rsx::method_registers.blend_color_16b_a();

			__glcheck glBlendColor(blend_color_r / 65535.f, blend_color_g / 65535.f, blend_color_b / 65535.f, blend_color_a / 65535.f);
		}
		else
		{
			u8 blend_color_r = rsx::method_registers.blend_color_8b_r();
			u8 blend_color_g = rsx::method_registers.blend_color_8b_g();
			u8 blend_color_b = rsx::method_registers.blend_color_8b_b();
			u8 blend_color_a = rsx::method_registers.blend_color_8b_a();

			__glcheck glBlendColor(blend_color_r / 255.f, blend_color_g / 255.f, blend_color_b / 255.f, blend_color_a / 255.f);
		}

		__glcheck glBlendEquationSeparate(blend_equation(rsx::method_registers.blend_equation_rgb()),
			blend_equation(rsx::method_registers.blend_equation_a()));
	}

	if (__glcheck enable(rsx::method_registers.stencil_test_enabled(), GL_STENCIL_TEST))
	{
		__glcheck glStencilFunc(comparison_op(rsx::method_registers.stencil_func()), rsx::method_registers.stencil_func_ref(),
			rsx::method_registers.stencil_func_mask());
		__glcheck glStencilOp(stencil_op(rsx::method_registers.stencil_op_fail()), stencil_op(rsx::method_registers.stencil_op_zfail()),
			stencil_op(rsx::method_registers.stencil_op_zpass()));

		if (rsx::method_registers.two_sided_stencil_test_enabled()) {
			__glcheck glStencilMaskSeparate(GL_BACK, rsx::method_registers.back_stencil_mask());
			__glcheck glStencilFuncSeparate(GL_BACK, comparison_op(rsx::method_registers.back_stencil_func()),
				rsx::method_registers.back_stencil_func_ref(), rsx::method_registers.back_stencil_func_mask());
			__glcheck glStencilOpSeparate(GL_BACK, stencil_op(rsx::method_registers.back_stencil_op_fail()),
				stencil_op(rsx::method_registers.back_stencil_op_zfail()), stencil_op(rsx::method_registers.back_stencil_op_zpass()));
		}
	}

	__glcheck enable(rsx::method_registers.blend_enabled_surface_1(), GL_BLEND, 1);
	__glcheck enable(rsx::method_registers.blend_enabled_surface_2(), GL_BLEND, 2);
	__glcheck enable(rsx::method_registers.blend_enabled_surface_3(), GL_BLEND, 3);

	if (__glcheck enable(rsx::method_registers.logic_op_enabled(), GL_COLOR_LOGIC_OP))
	{
		__glcheck glLogicOp(logic_op(rsx::method_registers.logic_operation()));
	}

	__glcheck glLineWidth(rsx::method_registers.line_width());
	__glcheck enable(rsx::method_registers.line_smooth_enabled(), GL_LINE_SMOOTH);

	//TODO
	//NV4097_SET_ANISO_SPREAD

	__glcheck enable(rsx::method_registers.poly_offset_point_enabled(), GL_POLYGON_OFFSET_POINT);
	__glcheck enable(rsx::method_registers.poly_offset_line_enabled(), GL_POLYGON_OFFSET_LINE);
	__glcheck enable(rsx::method_registers.poly_offset_fill_enabled(), GL_POLYGON_OFFSET_FILL);

	__glcheck glPolygonOffset(rsx::method_registers.poly_offset_scale(),
		rsx::method_registers.poly_offset_bias());

	//NV4097_SET_SPECULAR_ENABLE
	//NV4097_SET_TWO_SIDE_LIGHT_EN
	//NV4097_SET_FLAT_SHADE_OP
	//NV4097_SET_EDGE_FLAG

	auto set_clip_plane_control = [&](int index, rsx::user_clip_plane_op control)
	{
		int value = 0;
		int location;

		if (m_program->uniforms.has_location("uc_m" + std::to_string(index), &location))
		{
			switch (control)
			{
			default:
				LOG_ERROR(RSX, "bad clip plane control (0x%x)", (u8)control);

			case rsx::user_clip_plane_op::disable:
				value = 0;
				break;

			case rsx::user_clip_plane_op::greater_or_equal:
				value = 1;
				break;

			case rsx::user_clip_plane_op::less_than:
				value = -1;
				break;
			}

			__glcheck m_program->uniforms[location] = value;
		}

		__glcheck enable(value, GL_CLIP_DISTANCE0 + index);
	};

	load_program();
	set_clip_plane_control(0, rsx::method_registers.clip_plane_0_enabled());
	set_clip_plane_control(1, rsx::method_registers.clip_plane_1_enabled());
	set_clip_plane_control(2, rsx::method_registers.clip_plane_2_enabled());
	set_clip_plane_control(3, rsx::method_registers.clip_plane_3_enabled());
	set_clip_plane_control(4, rsx::method_registers.clip_plane_4_enabled());
	set_clip_plane_control(5, rsx::method_registers.clip_plane_5_enabled());

	if (__glcheck enable(rsx::method_registers.cull_face_enabled(), GL_CULL_FACE))
	{
		__glcheck glCullFace(cull_face(rsx::method_registers.cull_face_mode()));
	}

	__glcheck glFrontFace(front_face(rsx::method_registers.front_face_mode()));

	__glcheck enable(rsx::method_registers.poly_smooth_enabled(), GL_POLYGON_SMOOTH);

	//NV4097_SET_COLOR_KEY_COLOR
	//NV4097_SET_SHADER_CONTROL
	//NV4097_SET_ZMIN_MAX_CONTROL
	//NV4097_SET_ANTI_ALIASING_CONTROL
	//NV4097_SET_CLIP_ID_TEST_ENABLE

	std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
	m_begin_time += (u32)std::chrono::duration_cast<std::chrono::microseconds>(now - then).count();
	m_draw_calls++;
}
Пример #6
0
void GLGraphicsContext::updateRasterizerState(const RasterizerState& rasterizerState)
{
	const RasterizerState& newState = rasterizerState;
	const RasterizerState& currentState = getRasterizerState();
	
	if (newState.getCullMode() != currentState.getCullMode())
	{
		switch (newState.getCullMode())
		{
			case CullMode::NONE:
				glDisable(GL_CULL_FACE);
				break;
			
			case CullMode::CLOCKWISE:
				if (currentState.getCullMode() == CullMode::NONE)
				{
					glEnable(GL_CULL_FACE);
				}
				glCullFace(GL_BACK);
				break;
			
			case CullMode::COUNTERCLOCKWISE:
				if (currentState.getCullMode() == CullMode::NONE)
				{
					glEnable(GL_CULL_FACE);
				}
				glCullFace(GL_FRONT);
				break;
		}
	}
	
	if (newState.getFillMode() != currentState.getFillMode())
	{
		if (newState.getFillMode() == FillMode::SOLID)
		{
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
		}
		else
		{
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		}
	}
	
	if (newState.getDepthBias() != currentState.getDepthBias() || newState.getSlopeScaleDepthBias() != currentState.getSlopeScaleDepthBias())
	{
		glPolygonOffset(newState.getSlopeScaleDepthBias(), newState.getDepthBias());
	}
	
	if (newState.isScissorTestEnabled() != currentState.isScissorTestEnabled())
	{
		if (newState.isScissorTestEnabled())
		{
			glEnable(GL_SCISSOR_TEST);
		}
		else
		{
			glDisable(GL_SCISSOR_TEST);
		}
	}
	
	if (newState.isMSAAEnabled() != currentState.isMSAAEnabled())
	{
		if (newState.isMSAAEnabled())
		{
			glEnable(GL_MULTISAMPLE);
		}
		else
		{
			glDisable(GL_MULTISAMPLE);
		}
	}
}
Пример #7
0
void LLDrawPoolAvatar::renderAvatars(LLVOAvatar* single_avatar, S32 pass)
{
	if (pass == -1)
	{
		for (S32 i = 1; i < getNumPasses(); i++)
		{ //skip foot shadows
			prerender();
			beginRenderPass(i);
			renderAvatars(single_avatar, i);
			endRenderPass(i);
		}

		return;
	}

	if (mDrawFace.empty() && !single_avatar)
	{
		return;
	}

	LLVOAvatar *avatarp;

	if (single_avatar)
	{
		avatarp = single_avatar;
	}
	else
	{
		const LLFace *facep = mDrawFace[0];
		if (!facep->getDrawable())
		{
			return;
		}
		avatarp = (LLVOAvatar *)facep->getDrawable()->getVObj().get();
	}

    if (avatarp->isDead() || avatarp->mDrawable.isNull())
	{
		return;
	}

	if (!single_avatar && !avatarp->isFullyLoaded() )
	{
		if (pass==0 && (!gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_PARTICLES) || LLViewerPartSim::getMaxPartCount() <= 0))
		{
			// debug code to draw a sphere in place of avatar
			gGL.getTexUnit(0)->bind(LLViewerFetchedTexture::sWhiteImagep);
			gGL.setColorMask(true, true);
			LLVector3 pos = avatarp->getPositionAgent();
			gGL.color4f(1.0f, 1.0f, 1.0f, 0.7f);
			
			gGL.pushMatrix();	 
			gGL.translatef((F32)(pos.mV[VX]),	 
						   (F32)(pos.mV[VY]),	 
							(F32)(pos.mV[VZ]));	 
			 gGL.scalef(0.15f, 0.15f, 0.3f);

			 gSphere.renderGGL();
				 
			 gGL.popMatrix();
			 gGL.setColorMask(true, false);
		}
		// don't render please
		return;
	}

	BOOL impostor = avatarp->isImpostor() && !single_avatar;

	if (impostor && pass != 0)
	{ //don't draw anything but the impostor for impostored avatars
		return;
	}
	
	if (pass == 0 && !impostor && LLPipeline::sUnderWaterRender)
	{ //don't draw foot shadows under water
		return;
	}

	if (pass == 0)
	{
		if (!LLPipeline::sReflectionRender)
		{
			LLVOAvatar::sNumVisibleAvatars++;
		}

		if (impostor)
		{
			if (LLPipeline::sRenderDeferred && !LLPipeline::sReflectionRender && avatarp->mImpostor.isComplete()) 
			{
				if (normal_channel > -1)
				{
					avatarp->mImpostor.bindTexture(2, normal_channel);
				}
				if (specular_channel > -1)
				{
					avatarp->mImpostor.bindTexture(1, specular_channel);
				}
			}
			avatarp->renderImpostor(LLColor4U(255,255,255,255), sDiffuseChannel);
		}
		return;
	}

	/*if (single_avatar && avatarp->mSpecialRenderMode >= 1) // 1=anim preview, 2=image preview,  3=morph view
	{
		gPipeline.enableLightsAvatarEdit(LLColor4(.5f, .5f, .5f, 1.f));
	}*/
	
	if (pass == 1)
	{
		// render rigid meshes (eyeballs) first
		avatarp->renderRigid();
		return;
	}

	if (pass == 3)
	{
		if (is_deferred_render)
		{
			renderDeferredRiggedSimple(avatarp);
		}
		else
		{
			renderRiggedSimple(avatarp);
		}
		return;
	}

	if (pass == 4)
	{
		if (is_deferred_render)
		{
			renderDeferredRiggedBump(avatarp);
		}
		else
		{
			renderRiggedFullbright(avatarp);
		}

		return;
	}

	if (pass == 5)
	{
		renderRiggedShinySimple(avatarp);
		return;
	}

	if (pass == 6)
	{
		renderRiggedFullbrightShiny(avatarp);
		return;
	}

	if (pass >= 7 && pass < 9)
	{
		LLGLEnable blend(GL_BLEND);

		gGL.setColorMask(true, true);
		gGL.blendFunc(LLRender::BF_SOURCE_ALPHA,
					  LLRender::BF_ONE_MINUS_SOURCE_ALPHA,
					  LLRender::BF_ZERO,
					  LLRender::BF_ONE_MINUS_SOURCE_ALPHA);

		
		if (pass == 7)
		{
			renderRiggedAlpha(avatarp);
			return;
		}

		if (pass == 8)
		{
			renderRiggedFullbrightAlpha(avatarp);
			return;
		}
	}

	if (pass == 9)
	{
		LLGLEnable blend(GL_BLEND);
		LLGLDisable test(GL_ALPHA_TEST);
		gGL.flush();

		LLGLEnable polyOffset(GL_POLYGON_OFFSET_FILL);
		glPolygonOffset(-1.0f, -1.0f);
		gGL.setSceneBlendType(LLRender::BT_ADD);

		LLGLDepthTest depth(GL_TRUE, GL_FALSE);
		gGL.setColorMask(false, true);

		renderRiggedGlow(avatarp);
		gGL.setColorMask(true, false);
		gGL.setSceneBlendType(LLRender::BT_ALPHA);
		return;
	}
	
	if ((sShaderLevel >= SHADER_LEVEL_CLOTH))
	{
		LLMatrix4 rot_mat;
		LLViewerCamera::getInstance()->getMatrixToLocal(rot_mat);
		LLMatrix4 cfr(OGL_TO_CFR_ROTATION);
		rot_mat *= cfr;
		
		LLVector4 wind;
		wind.setVec(avatarp->mWindVec);
		wind.mV[VW] = 0;
		wind = wind * rot_mat;
		wind.mV[VW] = avatarp->mWindVec.mV[VW];

		sVertexProgram->uniform4fv(LLViewerShaderMgr::AVATAR_WIND, 1, wind.mV);
		F32 phase = -1.f * (avatarp->mRipplePhase);

		F32 freq = 7.f + (noise1(avatarp->mRipplePhase) * 2.f);
		LLVector4 sin_params(freq, freq, freq, phase);
		sVertexProgram->uniform4fv(LLViewerShaderMgr::AVATAR_SINWAVE, 1, sin_params.mV);

		LLVector4 gravity(0.f, 0.f, -CLOTHING_GRAVITY_EFFECT, 0.f);
		gravity = gravity * rot_mat;
		sVertexProgram->uniform4fv(LLViewerShaderMgr::AVATAR_GRAVITY, 1, gravity.mV);
	}

	if( !single_avatar || (avatarp == single_avatar) )
	{
		avatarp->renderSkinned(AVATAR_RENDER_PASS_SINGLE);
	}
}
Пример #8
0
void DominancyClassifier::generateWeightsAndShadowMap( OOCRaster &rr )
{
    // Backup the previous OpenGL states.
    glPushAttrib( GL_VIEWPORT_BIT     |
                  GL_COLOR_BUFFER_BIT |
                  GL_TRANSFORM_BIT    |
                  GL_ENABLE_BIT       |
                  GL_POLYGON_BIT      );


    // Set the OpenGL matrices so as to place the viewpoint on the given raster.
    glMatrixMode( GL_PROJECTION );
    glPushMatrix();
    glLoadMatrixf( m_Proj.V() );

    glMatrixMode( GL_MODELVIEW );
    glPushMatrix();
    glLoadMatrixf( m_Pose.V() );


    // Create the off-screen rendering context, using the shadow map texture as depth buffer.
    //m_WeightMap.Create( GL_LUMINANCE32F_ARB, m_ShadowMap.Width(), m_ShadowMap.Height() );
m_WeightMap.Create( GL_LUMINANCE, m_ShadowMap.Width(), m_ShadowMap.Height() );
    m_WeightMap.SetFiltering( GL_NEAREST );

    GPU::FrameBuffer fbuffer( m_ShadowMap.Width(), m_ShadowMap.Height() );
    fbuffer.Attach( GL_COLOR_ATTACHMENT0, m_WeightMap );
    fbuffer.Attach( GL_DEPTH_ATTACHMENT, m_ShadowMap );
    fbuffer.Bind();


    // Perform the rendering pass that computes the the shadow map used afterward for visibility checks
    // as well as the first weight map containing the orientation mask, the image border mask and
    // the distance masks (the silhouette mask is computed hereafter, using the depth gather in the shadow map).
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_POLYGON_OFFSET_FILL );
    glPolygonOffset( 2.0f, 2.0f );

    glClearColor( 0.0f, 1.0f, 0.0f, 1.0f );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    m_WeightShader.Bind();
    m_MeshVBO.TexCoord.Disable();
    m_MeshVBO.Bind();
    m_MeshVBO.DrawElements( GL_TRIANGLES, 0, 3*m_Mesh.fn );
    m_MeshVBO.Unbind();
    m_MeshVBO.TexCoord.Enable();
    m_WeightShader.Unbind();

    fbuffer.Unbind();


    // Restore the previous OpenGL states.
    glMatrixMode( GL_PROJECTION );
    glPopMatrix();
    glMatrixMode( GL_MODELVIEW );
    glPopMatrix();

    glPopAttrib();
#if 0
unsigned char *b = new unsigned char [ fbuffer.Width()*fbuffer.Height() ];
fbuffer.DumpTo( GL_COLOR_ATTACHMENT0, b, GL_LUMINANCE, GL_UNSIGNED_BYTE );
QImage img( b, fbuffer.Width(), fbuffer.Height(), QImage::Format_Indexed8 );
img = img.convertToFormat( QImage::Format_RGB888 );
img.save( "test1.png" );
delete [] b;
#endif


    // Recover the depth of the scene and create the texture containing the step discontinuity mask, if required.
    if( m_WeightMask & W_SILHOUETTE )
    {
        glPushAttrib( GL_TEXTURE_BIT );

        // Read the depth normalized between 0 and 1 from the framebuffer.
        floatbuffer buffer1, buffer2;
        buffer1.init( fbuffer.Width(), fbuffer.Height() );
        buffer2.init( fbuffer.Width(), fbuffer.Height() );
        fbuffer.DumpTo( GL_DEPTH_ATTACHMENT, buffer1.data, GL_DEPTH_COMPONENT, GL_FLOAT );  // WARNING: leads to a GL error.


        float zNear, zFar;
        GlShot< vcg::Shot<float> >::GetNearFarPlanes( rr.shot, m_Mesh.bbox, zNear, zFar );
        if( zNear < 0.0001f )
            zNear = 0.1f;
        if( zFar < zNear )
            zFar = zNear + 1000.0f;

        float range = zFar - zNear;
        for( unsigned int i=0; i<fbuffer.Width()*fbuffer.Height(); ++i )
            if( buffer1.data[i] < 1.0f )
    	        buffer1.data[i] = zNear*zFar / ((zFar - buffer1.data[i]*range)*range);


        // Detect step discontinuities and compute the distance of each pixel to the closest one.
        buffer2.applysobel( &buffer1 );
        buffer2.initborder( &buffer1 );
        buffer2.distancefield();

        // Create the OpenGL texture containing the weight values.
        //m_WeightMapSilh.Create( GL_LUMINANCE32F_ARB, fbuffer.Width(), fbuffer.Height(), GL_LUMINANCE, GL_FLOAT, buffer2.data );
m_WeightMapSilh.Create( GL_LUMINANCE, fbuffer.Width(), fbuffer.Height(), GL_LUMINANCE, GL_FLOAT, buffer2.data );
        m_WeightMapSilh.SetFiltering( GL_NEAREST );

        glPopAttrib();
#if 0
unsigned char *b = new unsigned char [ fbuffer.Width()*fbuffer.Height() ];
for( unsigned int i=0; i<fbuffer.Width()*fbuffer.Height(); ++i )
    b[i] = (unsigned char)(255.0f*buffer2.data[i]);
QImage img( b, fbuffer.Width(), fbuffer.Height(), QImage::Format_Indexed8 );
img = img.convertToFormat( QImage::Format_RGB888 );
img.save( "test2.png" );
delete [] b;
#endif
    }
}
Пример #9
0
void RenderScene(void) {
  


    // Clear the window with current clearing color
      
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    // Obracanie widoku
 float angle =timer.GetElapsedSeconds()*PI/4;
	posVector[0] = -8.0f * cos(angle / 2.0f);
    posVector[1] = -8.0f * sin(angle / 2.0f);
    posVector[2] = 5.0f;
  

	 swiatlo0.position[0] = 8.0f * cos(-angle);
   swiatlo0.position[1] = 15.0f * sin(-angle);
   swiatlo0.position[2] = 5.0f;

 LookAt(viewFrame, posVector, atVector, upVector);
     
  
  
geometryPipeline.SetMatrixStacks(modelView,projection);

      
    projection.LoadMatrix(viewFrustum.GetProjectionMatrix());
modelView.PushMatrix();
M3DMatrix44f mCamera;
viewFrame.GetCameraMatrix(mCamera);
modelView.LoadMatrix(mCamera);
modelView.PushMatrix();
//glUseProgram(shader);

modelView.Translate(swiatlo0.position[0], swiatlo0.position[1], swiatlo0.position[2]);
glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
modelView.PopMatrix();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glUseProgram(shader);
   modelView.PushMatrix();
  modelView.Translate(swiatlo0.position[0], swiatlo0.position[1], swiatlo0.position[2]);
   modelView.Scale(0.25f, 0.25f, 0.25f);
   glUniformMatrix4fv(MVPMatrixLocationshader, 1, GL_FALSE, geometryPipeline.GetModelViewProjectionMatrix());
modelView.PopMatrix();
    glUseProgram(Pshader);//wywo³anie shadera

    //mno¿enie macierzy
    //modelView.MultMatrix(mCamera);
   // modelView.PushMatrix();
    //m3dMatrixMultiply44(mModelViewProjection, viewFrustum.GetProjectionMatrix(), mCamera);
  // wrzucanie do shadera
   
glUniformMatrix3fv(NMatrixLocation, 1, GL_FALSE, geometryPipeline.GetNormalMatrix());
   glUniformMatrix4fv(VMmatrixLocation, 1, GL_FALSE, mCamera);
   glUniform3fv(iambient_component_location, 1, iambient_component);
   glUniform3fv(swiatlo0_location, 1, swiatlo0.position);
   glUniform3fv(swiatlo0_idiffuse_location, 1, swiatlo0.idiffuse);
   glUniform3fv(swiatlo0_ispecular_location, 1, swiatlo0.ispecular);
   glUniform3fv(swiatlo0_attenuation_location, 1, swiatlo0.attenuation);
   glUniform1f(material0_ka_location, material0.ka);
   glUniform1f(material0_kd_location, material0.kd);
   glUniform1f(material0_ks_location, material0.ks);
   glUniform1f(material0_alpha_location, material0.alpha);
   //--
   glUniformMatrix4fv(MVPMatrixLocation, 1, GL_FALSE, geometryPipeline.GetModelViewProjectionMatrix());
   glUniformMatrix4fv(MVMatrixLocation, 1, GL_FALSE, geometryPipeline.GetModelViewMatrix());


    DrawPramid(0.5,0.0,1.0);    
 // drawTriangles(20,ico_vertices,ico_faces);
// rysowanie siatki --------------------------------------------------------------------------
    glEnable(GL_CULL_FACE);
    glPolygonOffset(1.0f, 1.0f);
    glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 1.0, 1.0, 1.0);
    glEnable(GL_POLYGON_OFFSET_FILL);
glBegin(GL_QUADS);
glVertex3f(10,    -10.0f,   0.0f);
  
  
glVertex3f(-10,    -10.0f,  0.0f);
glVertex3f(-10,    10.0f,   0.0f);
glVertex3f(10,    10.0f,   0.0f);
  
  
glEnd();
glDisable(GL_POLYGON_OFFSET_FILL);
   glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 1.0, 1.0, 1.0);
    for(int i=-10;i<=10;i++){
    glBegin(GL_LINES);
            glVertex3f((float)i,    -10.0f,  0.0f);
            glVertex3f((float)i,    10.0f,   0.0f);
            glEnd();
    }
for(int i=-10;i<=10;i++){
    glBegin(GL_LINES);
            glVertex3f(-10.0f,  (float)i,    0.0f);
            glVertex3f(10.0f,   (float)i,    0.0f);
    glEnd();
    }
     glDisable(GL_CULL_FACE); 
	 //sphereBatch.Draw();

	 glUniformMatrix4fv(MVPMatrixLocation, 1, GL_FALSE, geometryPipeline.GetModelViewProjectionMatrix());
   glUniformMatrix4fv(MVMatrixLocation, 1, GL_FALSE, geometryPipeline.GetModelViewMatrix());
modelView.PopMatrix();
    // rysowanie siatki - koniec -------------------------------------------------------------------
//matrixStack.Translate(10.0f,1.0f,0.0f);
 
// macierz translacji i macierz rotacji
//M3DMatrix44f mT,mR;
 // m3dTranslationMatrix44(mT,0.0f,3.0f,0.0f);
  //m3dRotationMatrix44(mR, angle, 0.0f, 0.0f, 1.0f);
  
  //mno¿enie  macierzy translacji i macierzy rotacji
//m3dMatrixMultiply44(mM,mT,mR);
  
//mno¿enie macierzy przekszta³ceñ i macierzy projekcji modelwidok
// m3dMatrixMultiply44(mModelViewProjection,mModelViewProjection, mM);
  
 //wysy³anie macierzy projekcji modelwidok do shadera
 //glUniformMatrix4fv(MVPMatrixLocation, 1, GL_FALSE, mModelViewProjection);
  //TriangleFace(position,color,atVector);
 //DrawPramid(0.5,0.0,1.0);
   
     //drawTriangles(20, ico_vertices, ico_faces);
//matrixStack.PopMatrix();
//matrixStack.Rotate(45.0,0,0,1);
//matrixStack.Translate(0.0,0.0,1.0);
//glUniformMatrix4fv(MVPMatrixLocation,1,GL_FALSE,geometryPipeline.GetModelViewProjectionMatrix());
//DrawPramid(0.5,0.0,1.0);



	glUniformMatrix4fv(MVPMatrixLocation, 1, GL_FALSE, geometryPipeline.GetModelViewProjectionMatrix());
   glUniformMatrix4fv(MVMatrixLocation, 1, GL_FALSE, geometryPipeline.GetModelViewMatrix());
modelView.PopMatrix();

 
   
      glUseProgram(0);
    // Perform the buffer swap to display back buffer
    glutSwapBuffers();
    glutPostRedisplay();
}
Пример #10
0
static void
draw_edges(void)
{
    /*
     * render the offset depth image
     */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
#ifdef GL_POLYGON_OFFSET_FILL
    glPolygonOffset(4.0, 1.0);
#else
    /* XXX should change to use glPolygonOffset in OpenGL 1.1 */
    glPolygonOffsetEXT(4.0, (1.0 / (1 << 22)));
#endif
    glEnable(GL_POLYGON_OFFSET_FILL);
    /* glColorMask(0,0,0,0); */
    glCallList(1);
    /* glColorMask(1,1,1,1); */
    glDisable(GL_POLYGON_OFFSET_FILL);

    /*
     *  make no further changes to the depth image
     */
    glDepthMask(0);
    glDisable(GL_DEPTH_TEST);	/* XXX */
    glEnable(GL_DEPTH_TEST);	/* XXX */

    /*
     * cull all facets of one (arbitrary) orientation.  render the
     * remaining facets in outline mode, toggling the stencil bit
     * at each pixel.
     */
    glDisable(GL_LIGHTING);
    glColor3f(0.f, 0.f, 0.f);
    glLineWidth(2.0);
    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_ALWAYS, 0, 1);
    glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT);
    glEnable(GL_CULL_FACE);
    glColorMask(0, 0, 0, 0);
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    glCallList(1);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    glColorMask(1, 1, 1, 1);
    glDisable(GL_CULL_FACE);

    /*
     * color all pixels in the framebuffer with stencil value 1
     */
    glStencilFunc(GL_EQUAL, 1, 1);
    glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
    glColor3f(0, 0, 0);
    fill_window();
    glDisable(GL_STENCIL_TEST);

    /*
     * draw all true edges, testing against the depth image
     */
    glColor3f(0, 0, 0);
    glCallList(2);

    /*
     * return state to default values
     */
    glDepthMask(1);
    glDisable(GL_DEPTH_TEST);	/* XXX */
    glEnable(GL_DEPTH_TEST);	/* XXX */
    if (lighting)
	glEnable(GL_LIGHTING);
    glLineWidth(1.0);
    glColor3f(1.f, 1.f, 1.f);
}
Пример #11
0
void
redraw(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (show_texture) {
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(-2., 2., -2., 2., -1., 1);
	glBegin(GL_QUADS);
	glTexCoord2f(0.f, 0.f);
	glVertex2f(-1.f, -1.f);
	glTexCoord2f(1.f, 0.f);
	glVertex2f(1.f, -1.f);
	glTexCoord2f(1.f, 1.f);
	glVertex2f(1.f, 1.f);
	glTexCoord2f(0.f, 1.f);
	glVertex2f(-1.f, 1.f);
	glEnd();
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
	CHECK_ERROR("OpenGL Error in redraw()");
	glutSwapBuffers();
	return;
    }
    glPushMatrix();				/* assuming modelview */
    glTranslatef(objpos[X], objpos[Y], 0.f);	/* translate object */
    glRotatef(objangle[X], 0.f, 1.f, 0.f);	/* rotate object */
    glRotatef(objangle[Y], 1.f, 0.f, 0.f);

    /*
     * The object 
     */
    glEnable(GL_POLYGON_OFFSET_FILL);
    glPolygonOffset(1.0, 1.0);
    glCallList(1);
    glDisable(GL_POLYGON_OFFSET_FILL);

    /*
     * The edges 
     */
    if (edgelines) {
#if 0
	glDisable(GL_LIGHTING);
	glColor3f(0.0, 0.0, 0.0);
	glLineWidth(2.0);
	glCallList(2);
	if (lighting)
	    glEnable(GL_LIGHTING);
	glColor3f(1.0, 1.0, 1.0);
	glLineWidth(1.0);
#else
	draw_edges();
#endif
    }
    glPopMatrix();		/* assuming modelview */

    CHECK_ERROR("OpenGL Error in redraw()");
    glutSwapBuffers();
}
// Inherited from BatchRenderer
void SceneObject_Decal_BatchRenderer::Execute()
{
	if(!GetScene()->m_renderingDeferred)
		return;

	glEnable(GL_STENCIL_TEST);
	glClearStencil(0);
	glClear(GL_STENCIL_BUFFER_BIT);

	glDepthFunc(GL_LEQUAL);
	
	glDepthMask(false);

	glEnable(GL_POLYGON_OFFSET_FILL);
	
	for(unsigned int i = 0, numDecals = m_pDecals.size(); i < numDecals;)
	{
		// Stencil in batches of 8
		glColorMask(false, false, false, false);
		Shader::Unbind();

		glPolygonOffset(2.0f, 2.0f);

		// Mark parts where depth test fails
		glStencilFunc(GL_ALWAYS, 0xff, 0xff);
		glStencilOp(GL_KEEP, GL_REPLACE, GL_KEEP);

		unsigned int firstDecalInBatchIndex = i;

		// Stencil out regions with stencil mask
		for(unsigned int j = 0; j < 8 && i < numDecals; j++, i++)
		{
			glStencilMask(m_decalIndices[j]);
			m_pDecals[i]->Render_Batch_NoTexture();
		}

		glColorMask(true, true, true, true);

		// Stencil test
		glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
	
		glPolygonOffset(-2.0f, -2.0f);

		// Re-render, second pass
		i = firstDecalInBatchIndex;

		GetScene()->RebindGBufferRenderShader();

		for(unsigned int j = 0; j < 8 && i < numDecals; j++, i++)
		{
			glStencilFunc(GL_EQUAL, 0xff, m_decalIndices[j]);

			m_pDecals[i]->Render_Batch_Textured();
		}

		glClear(GL_STENCIL_BUFFER_BIT);
	}

	GetScene()->SetCurrentGBufferRenderShader(Scene::e_plain);

	glDisable(GL_POLYGON_OFFSET_FILL);
	glDepthMask(true);

	glDepthFunc(GL_LESS);

	glDisable(GL_STENCIL_TEST);
}
Пример #13
0
void GLWrapper::PolygonOffset(GLfloat param0, GLfloat param1)
{
	GLLOG(glPolygonOffset(param0, param1));ERROR_CHECK;
}
Пример #14
0
void e_beginpass(e_device_t* device,unsigned int pass)
{
	glPushAttrib(GL_ENABLE_BIT|GL_STENCIL_BUFFER_BIT|GL_POLYGON_BIT);
	switch(pass)
	{
		case E_RENDER_MESHES:
			glBindProgramARB(GL_VERTEX_PROGRAM_ARB,e_programids[E_PROGRAM_PASSTOFRAGMENT]);
			glEnable(GL_VERTEX_PROGRAM_ARB);
			glEnable(GL_FRAGMENT_PROGRAM_ARB);

			glEnable(GL_DEPTH_TEST);
			glEnable(GL_CULL_FACE);
			break;
		case E_RENDER_SHADOWS:
			//The support of this extension depends on the 3D card
			if(glActiveStencilFaceEXT)
			{
				glActiveStencilFaceEXT(GL_BACK);
				glStencilOp(GL_KEEP,GL_INCR_WRAP_EXT,GL_KEEP);
				glActiveStencilFaceEXT(GL_FRONT);
				glStencilOp(GL_KEEP,GL_DECR_WRAP_EXT,GL_KEEP);
				glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);
			}
			else
				glEnable(GL_CULL_FACE);

			glBindProgramARB(GL_VERTEX_PROGRAM_ARB,e_programids[E_PROGRAM_SHADOW]);
			glEnable(GL_VERTEX_PROGRAM_ARB);

			glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
			glDepthMask(GL_FALSE);
			glEnable(GL_STENCIL_TEST);
			glStencilFunc(GL_ALWAYS,0,~0);
			glEnable(GL_DEPTH_TEST);
			break;
		case E_RENDER_SHADING:
			glBindProgramARB(GL_VERTEX_PROGRAM_ARB,e_programids[E_PROGRAM_PASSTOFRAGMENT]);
			glEnable(GL_VERTEX_PROGRAM_ARB);
			glEnable(GL_FRAGMENT_PROGRAM_ARB);

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

			glEnable(GL_STENCIL_TEST);
			glStencilFunc(GL_EQUAL,0,~0);
			glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP);
			glDepthFunc(GL_LEQUAL);

			glEnable(GL_CULL_FACE);
			glEnable(GL_DEPTH_TEST);
			break;
		case E_RENDER_OUTLINES:
			glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
#ifdef E_OUTLINES_SMOOTH
			glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
			glEnable(GL_LINE_SMOOTH);
			glEnable(GL_BLEND);
#endif
			glLineWidth(E_OUTLINES_WIDTH);
			glPolygonOffset(1.0f,1.0f);
			glEnable(GL_POLYGON_OFFSET_LINE);
			glColor3ub(0,0,0);
			glEnable(GL_CULL_FACE);
			glCullFace(GL_FRONT);
			glEnable(GL_DEPTH_TEST);
			break;
	}
}
Пример #15
0
int main(int argc, char **argv)
{
  int i;

  glutInit(&argc, argv);

  for (i=1; i<argc; i++) {
    if (!strcmp("-linear", argv[i])) {
      linearFiltering = 1;
    } else if (!strcmp("-mipmap", argv[i])) {
      useMipmaps = 1;
    } else if (!strcmp("-ext", argv[i])) {
      forceExtension = 1;
    }
  }

  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL | GLUT_MULTISAMPLE);

#if 0
  /* In GLUT 4.0, you'll be able to do this an be sure to
     get 2 bits of stencil if the machine has it for you. */
  glutInitDisplayString("samples stencil>=2 rgb double depth");
#endif

  glutCreateWindow("Shadowy Leapin' Lizards");

  if (glutGet(GLUT_WINDOW_STENCIL_SIZE) <= 1) {
    printf("dinoshade: Sorry, I need at least 2 bits of stencil.\n");
    //exit(1);
  }

  /* Register GLUT callbacks. */
  glutDisplayFunc(redraw);
  glutMouseFunc(mouse);
  glutMotionFunc(motion);
  glutVisibilityFunc(visible);
  glutKeyboardFunc(key);
  glutSpecialFunc(special);

  glutCreateMenu(controlLights);

  glutAddMenuEntry("Toggle motion", M_MOTION);
  glutAddMenuEntry("-----------------------", M_NONE);
  glutAddMenuEntry("Toggle light", M_LIGHT);
  glutAddMenuEntry("Toggle texture", M_TEXTURE);
  glutAddMenuEntry("Toggle shadows", M_SHADOWS);
  glutAddMenuEntry("Toggle reflection", M_REFLECTION);
  glutAddMenuEntry("Toggle dinosaur", M_DINOSAUR);
  glutAddMenuEntry("-----------------------", M_NONE);
  glutAddMenuEntry("Toggle reflection stenciling", M_STENCIL_REFLECTION);
  glutAddMenuEntry("Toggle shadow stenciling", M_STENCIL_SHADOW);
  glutAddMenuEntry("Toggle shadow offset", M_OFFSET_SHADOW);
  glutAddMenuEntry("----------------------", M_NONE);
  glutAddMenuEntry("Positional light", M_POSITIONAL);
  glutAddMenuEntry("Directional light", M_DIRECTIONAL);
  glutAddMenuEntry("-----------------------", M_NONE);
  glutAddMenuEntry("Toggle performance", M_PERFORMANCE);
  glutAttachMenu(GLUT_RIGHT_BUTTON);
  makeDinosaur();

#ifdef GL_VERSION_1_1
  if (supportsOneDotOne() && !forceExtension) {
    polygonOffsetVersion = ONE_DOT_ONE;
    glPolygonOffset(-2.0, -1.0);
  } else
#endif
  {
#ifdef GL_EXT_polygon_offset
  /* check for the polygon offset extension */
  if (glutExtensionSupported("GL_EXT_polygon_offset")) {
    polygonOffsetVersion = EXTENSION;
    glPolygonOffsetEXT(-0.1, -0.002);
  } else 
#endif
    {
      polygonOffsetVersion = MISSING;
      printf("\ndinoshine: Missing polygon offset.\n");
      printf("           Expect shadow depth aliasing artifacts.\n\n");
    }
  }

  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_TEXTURE_2D);
  glLineWidth(3.0);

  glMatrixMode(GL_PROJECTION);
  gluPerspective( /* field of view in degree */ 40.0,
  /* aspect ratio */ 1.0,
    /* Z near */ 20.0, /* Z far */ 100.0);
  glMatrixMode(GL_MODELVIEW);
  gluLookAt(0.0, 8.0, 60.0,  /* eye is at (0,8,60) */
    0.0, 8.0, 0.0,      /* center is at (0,8,0) */
    0.0, 1.0, 0.);      /* up is in postivie Y direction */

  glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor);
  glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1);
  glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05);
  glEnable(GL_LIGHT0);
  glEnable(GL_LIGHTING);

  makeFloorTexture();

  /* Setup floor plane for projected shadow calculations. */
  findPlane(floorPlane, floorVertices[1], floorVertices[2], floorVertices[3]);

  glutMainLoop();
  return 0;             /* ANSI C requires main to return int. */
}
Пример #16
0
void main(int argc, char **argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(500, 500);
	glutCreateWindow("wave");
	if(argc > 1 && argv[1] != 0) TexFilename1 = argv[1];
	if(argc > 2 && argv[2] != 0) TexFilename2 = argv[2];
	glEnable	(GL_DEPTH_TEST);
	glDepthFunc	(GL_LEQUAL);
	glClearColor	(0.0, 0.0, 0.0, 0.0);
	glPolygonOffset	(1.0, 1.0);
	glEnable	(GL_CULL_FACE);
	glHint		(GL_LINE_SMOOTH_HINT, GL_NICEST);
	glHint		(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
	glHint		(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glEnable	(GL_COLOR_MATERIAL);
	glColorMaterial	(GL_FRONT, GL_DIFFUSE);
	glLightfv	(GL_LIGHT0, GL_POSITION, lightPosition);
	glEnable	(GL_LIGHT0);
	loadImageTexture();

	setSize	  (MEDIUM);
	setSpeed  (NORMAL);
	setDisplay(FLATSHADED);
	setOther  (ENVMAP);
	reset	  (HILLFOUR);

	glutReshapeFunc(reshape);
	glutDisplayFunc(display);
	glutVisibilityFunc(visibility);

	glutKeyboardFunc(keyboard);
	glutMouseFunc   (mouse);
	glutMotionFunc  (motion);

	displayMenu = glutCreateMenu(setDisplay);
	glutAddMenuEntry("Wireframe",     WIREFRAME);
	glutAddMenuEntry("Hidden Line",   HIDDENLINE);
	glutAddMenuEntry("Flat Shaded",   FLATSHADED);
	glutAddMenuEntry("Smooth Shaded", SMOOTHSHADED);
	glutAddMenuEntry("Textured",      TEXTURED);

	otherMenu = glutCreateMenu(setOther);
	glutAddMenuEntry("Full Screen",  FULLSCREEN);
	glutAddMenuEntry("Face Normals", FACENORMALS);
	glutAddMenuEntry("Antialias",    ANTIALIAS);
	glutAddMenuEntry("Environment Map", ENVMAP);

	speedMenu = glutCreateMenu(setSpeed);
	glutAddMenuEntry("Weak",   WEAK);
	glutAddMenuEntry("Normal", NORMAL);
	glutAddMenuEntry("Strong", STRONG);

	sizeMenu = glutCreateMenu(setSize);
	glutAddMenuEntry("Small",  SMALL);
	glutAddMenuEntry("Medium", MEDIUM);
	glutAddMenuEntry("Large",  LARGE);
	glutAddMenuEntry("Extra Large", XLARGE);

	resetMenu = glutCreateMenu(reset);
	glutAddMenuEntry("Current",	  CURRENT);
	glutAddMenuEntry("Spike",	  SPIKE);
	glutAddMenuEntry("Hole",	  HOLE);
	glutAddMenuEntry("Diagonal Wall", DIAGONALWALL);
	glutAddMenuEntry("Side Wall",     SIDEWALL);
	glutAddMenuEntry("Middle Block",  MIDDLEBLOCK);
	glutAddMenuEntry("Diagonal Block",DIAGONALBLOCK);
	glutAddMenuEntry("Corner Block",  CORNERBLOCK);
	glutAddMenuEntry("Hill",          HILL);
	glutAddMenuEntry("Hill Four",     HILLFOUR);

	mainMenu = glutCreateMenu(setMain);
	glutAddMenuEntry("Go",      2);
	glutAddMenuEntry("Stop",    3);
	glutAddMenuEntry("Reverse", 4);
	glutAddSubMenu("Display",   displayMenu);
	glutAddSubMenu("Reset",     resetMenu);
	glutAddSubMenu("Size",      sizeMenu);
	glutAddSubMenu("Speed",     speedMenu);
	glutAddSubMenu("Other",     otherMenu);
	glutAddMenuEntry("Exit",    5);
	glutAttachMenu(GLUT_RIGHT_BUTTON);

	glutMainLoop();
}
void GEPrimitive::render(GE_RENDER_MODE mode)
{
	// If it's not supouse to be visible don't render at all.
	if (!Visible) return;

	// Bind this model.
	glBindVertexArray(m_vertexArrayID);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);

	if (mode == GE_RENDER_MODE_NORMAL)
	{
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		if (Wireframe)
		{
			glEnable(GL_POLYGON_OFFSET_FILL);
			glPolygonOffset(1, 1);
		}

		// Material and model matrices.
		m_blinnPhongShader->Material = &Material;
		m_blinnPhongShader->ModelMatrix = &m_finalMatrix;
		m_blinnPhongShader->NormalMatrix = &m_orientationMatrix;

		m_blinnPhongShader->useProgram();

		glCullFace(GL_BACK);

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferID);
		glDrawElements(GL_TRIANGLES, m_indexCount, GL_UNSIGNED_INT, NULL);

		if (Wireframe)
		{
			glEnable(GL_DEPTH_TEST);
			glDisable(GL_BLEND);
			glDisable(GL_POLYGON_OFFSET_FILL);
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

			glLineWidth(1.0f);

			m_colorShader->Material = &m_wireframeMaerial;
			m_colorShader->ModelMatrix = &m_finalMatrix;
			m_colorShader->useProgram();

			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferID);
			glDrawElements(GL_TRIANGLES, m_indexCount, GL_UNSIGNED_INT, NULL);


			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
		}
	}
	else if (mode == GE_RENDER_MODE_DEPTH)
	{
		// Disable blend.
		glDisable(GL_BLEND);
		glEnable(GL_DEPTH_TEST);

		m_depthShader->ModelMatrix = &m_finalMatrix;
		m_depthShader->useProgram();

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferID);
		glDrawElements(GL_TRIANGLES, m_indexCount, GL_UNSIGNED_INT, NULL);
	}
}
Пример #18
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();

}
Пример #19
0
void OpenGLExampleBrowser::update(float deltaTime)
{

		assert(glGetError()==GL_NO_ERROR);
		s_instancingRenderer->init();
        DrawGridData dg;
        dg.upAxis = s_app->getUpAxis();

        {
            BT_PROFILE("Update Camera and Light");

	

            s_instancingRenderer->updateCamera(dg.upAxis);
        }

		if (renderGrid)
        {
            BT_PROFILE("Draw Grid");
			glPolygonOffset(3.0, 3);
			glEnable(GL_POLYGON_OFFSET_FILL);
            s_app->drawGrid(dg);
			
        }
		static int frameCount = 0;
		frameCount++;

		if (0)
		{
            BT_PROFILE("Draw frame counter");
            char bla[1024];
            sprintf(bla,"Frame %d", frameCount);
            s_app->drawText(bla,10,10);
		}

		
		if (sCurrentDemo)
		{
			if (!pauseSimulation)
			{
				//printf("---------------------------------------------------\n");
				//printf("Framecount = %d\n",frameCount);

				if (gPngFileName)
				{
					
					static int skip = 0;
					skip++;
					if (skip>4)
					{
						skip=0;
						//printf("gPngFileName=%s\n",gPngFileName);
						static int s_frameCount = 100;
						
						sprintf(staticPngFileName,"%s%d.png",gPngFileName,s_frameCount++);
						//b3Printf("Made screenshot %s",staticPngFileName);
						s_app->dumpNextFrameToPng(staticPngFileName);
						 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
					}
				}
				

				if (gFixedTimeStep>0)
				{
					sCurrentDemo->stepSimulation(gFixedTimeStep);
				} else
				{
					sCurrentDemo->stepSimulation(deltaTime);//1./60.f);
				}
			}
			
			if (renderVisualGeometry && ((gDebugDrawFlags&btIDebugDraw::DBG_DrawWireframe)==0))
            {
				if (visualWireframe)
				{
					glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
				}
                BT_PROFILE("Render Scene");
                sCurrentDemo->renderScene();
            }
            {
				
				glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
                sCurrentDemo->physicsDebugDraw(gDebugDrawFlags);
            }
		}

		{
			
			if (s_guiHelper && s_guiHelper->getRenderInterface() && s_guiHelper->getRenderInterface()->getActiveCamera())
			{
				char msg[1024];
				float camDist = s_guiHelper->getRenderInterface()->getActiveCamera()->getCameraDistance();
				float pitch = s_guiHelper->getRenderInterface()->getActiveCamera()->getCameraPitch();
				float yaw = s_guiHelper->getRenderInterface()->getActiveCamera()->getCameraYaw();
				float camTarget[3];
				s_guiHelper->getRenderInterface()->getActiveCamera()->getCameraTargetPosition(camTarget);
				sprintf(msg,"dist=%f, pitch=%f, yaw=%f,target=%f,%f,%f", camDist,pitch,yaw,camTarget[0],camTarget[1],camTarget[2]);
				gui->setStatusBarMessage(msg, true);	
			}
			
		}

		static int toggle = 1;
		if (renderGui)
		{
            if (!pauseSimulation)
                processProfileData(s_profWindow,false);

            if (sUseOpenGL2)
			{
					
				saveOpenGLState(s_instancingRenderer->getScreenWidth(),s_instancingRenderer->getScreenHeight());
			}
            BT_PROFILE("Draw Gwen GUI");
            gui->draw(s_instancingRenderer->getScreenWidth(),s_instancingRenderer->getScreenHeight());
            if (sUseOpenGL2)
            {
                restoreOpenGLState();
            }

		}
	
	
	
				
		toggle=1-toggle;
        {
            BT_PROFILE("Sync Parameters");
            s_parameterInterface->syncParameters();
        }
        {
            BT_PROFILE("Swap Buffers");
            s_app->swapBuffer();
        }
	
		gui->forceUpdateScrollBars();

}
Пример #20
0
/* Set up display */
void display(void) {
  glClearColor(0.0, 0.0, 0.0, 1.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  //glColor4f(0.48627451, 0.223529412, 0.815686275, 1.0);
  
  glMatrixMode(GL_MODELVIEW);
  
  // Draw Glass
  glFrontFace(GL_CCW);
  glCullFace(GL_BACK);
  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
  glDisable(GL_BLEND);
  glass(1);
  glTranslatef(0,0.4,0);
  glCullFace(GL_FRONT);
  donut(1);
  glCullFace(GL_BACK);
  glTranslatef(0,-0.4,0);
  
  // Draw Table
  glEnable(GL_STENCIL_TEST);
  glStencilFunc(GL_ALWAYS, 1, 1);
  glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  table();
  
  // Draw Reflections
  glClear(GL_DEPTH_BUFFER_BIT);
  glStencilFunc(GL_EQUAL, 1, 1);
  glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glScalef(1, 1, -1);
  glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
  glCullFace(GL_FRONT);
  glass(1);
  glTranslatef(0,.4,0);
  glCullFace(GL_BACK);
  donut(1);
  glCullFace(GL_FRONT);
  glTranslatef(0,-.4,0);
  glMatrixMode(GL_MODELVIEW);
  glPopMatrix();
  glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
  glCullFace(GL_BACK);
  
  // Alpha Blend Table 
  glClear(GL_DEPTH_BUFFER_BIT);
  glStencilFunc(GL_EQUAL, 1, 1);
  glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  glEnable(GL_BLEND);
  glBlendColor(1,1,1,0.4);
  glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA);
  table();
  glDisable(GL_BLEND);
  
  // Draw Shadow
  glClear(GL_DEPTH_BUFFER_BIT);
  glDisable(GL_LIGHTING);
  glDisable(GL_LIGHT0);
  glEnable(GL_BLEND);
  glColor4f(0,0,0, 0.7);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glStencilFunc(GL_EQUAL, 1, 1);
  glStencilOp(GL_KEEP, GL_KEEP, GL_ZERO);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  shadowTransform(light0_position, tablePlane);
  glMultMatrixf((GLfloat *) shadowMatrix);
  glPolygonOffset(-1.0, -1.0);
  glEnable(GL_POLYGON_OFFSET_FILL);
  glass(0);
  glTranslatef(0,.4,0);
  glCullFace(GL_BACK);
  donut(0);
  glCullFace(GL_FRONT);
  glTranslatef(0,-.4,0);
  glDisable(GL_POLYGON_OFFSET_FILL);
  glMatrixMode(GL_MODELVIEW);
  glPopMatrix();
  glDisable(GL_STENCIL_TEST);
  glDisable(GL_BLEND);
  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);
  
  glutSwapBuffers();
}
Пример #21
0
void CUnit::Draw()
{
    glPushMatrix();
    float3 interPos=pos+speed*gu->timeOffset;

    if (physicalState == Flying && unitDef->canmove) {
        //aircraft or skidding ground unit
        CMatrix44f transMatrix(interPos,-rightdir,updir,frontdir);

        glMultMatrixf(&transMatrix[0]);
    } else if(upright || !unitDef->canmove) {
        glTranslatef3(interPos);
        if(heading!=0)
            glRotatef(heading*(180.0/32768.0),0,1,0);
    } else {
        float3 frontDir=GetVectorFromHeading(heading);		//making local copies of vectors
        float3 upDir=ground->GetSmoothNormal(pos.x,pos.z);
        float3 rightDir=frontDir.cross(upDir);
        rightDir.Normalize();
        frontDir=upDir.cross(rightDir);

        CMatrix44f transMatrix(interPos,-rightDir,upDir,frontDir);

        glMultMatrixf(&transMatrix[0]);
    }

    if(beingBuilt && unitDef->showNanoFrame) {
        if(shadowHandler->inShadowPass) {
            if(buildProgress>0.66)
                localmodel->Draw();
        } else {
            float height=model->height;
            float start=model->miny;
            glEnable(GL_CLIP_PLANE0);
            glEnable(GL_CLIP_PLANE1);
            //float col=fabs(128.0-((gs->frameNum*4)&255))/255.0+0.5f;
            float3 fc;// fc frame color
            if(gu->teamNanospray) {
                unsigned char* tcol=gs->Team(team)->color;
                fc = float3(tcol[0]*(1./255.),tcol[1]*(1./255.),tcol[2]*(1./255.));
            } else {
                fc = unitDef->nanoColor;
            }
            glColorf3(fc);

            unitDrawer->UnitDrawingTexturesOff(model);

            double plane[4]= {0,-1,0,start+height*buildProgress*3};
            glClipPlane(GL_CLIP_PLANE0 ,plane);
            double plane2[4]= {0,1,0,-start-height*(buildProgress*10-9)};
            glClipPlane(GL_CLIP_PLANE1 ,plane2);
            glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
            localmodel->Draw();
            glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

            if(buildProgress>0.33) {
                glColorf3(fc*1.4f);
                double plane[4]= {0,-1,0,start+height*(buildProgress*3-1)};
                glClipPlane(GL_CLIP_PLANE0 ,plane);
                double plane2[4]= {0,1,0,-start-height*(buildProgress*3-2)};
                glClipPlane(GL_CLIP_PLANE1 ,plane2);

                localmodel->Draw();
            }
            glDisable(GL_CLIP_PLANE1);
            unitDrawer->UnitDrawingTexturesOn(model);

            if(buildProgress>0.66) {
                double plane[4]= {0,-1,0,start+height*(buildProgress*3-2)};
                glClipPlane(GL_CLIP_PLANE0 ,plane);
                if(shadowHandler->drawShadows && !water->drawReflection) {
                    glPolygonOffset(1,1);
                    glEnable(GL_POLYGON_OFFSET_FILL);
                }
                localmodel->Draw();
                if(shadowHandler->drawShadows && !water->drawReflection) {
                    glDisable(GL_POLYGON_OFFSET_FILL);
                }
            }
            glDisable(GL_CLIP_PLANE0);
        }
    } else {
        localmodel->Draw();
    }
    if(gu->drawdebug) {
        glPushMatrix();
        glTranslatef3(frontdir*relMidPos.z + updir*relMidPos.y + rightdir*relMidPos.x);
        GLUquadricObj* q=gluNewQuadric();
        gluQuadricDrawStyle(q,GLU_LINE);
        gluSphere(q,radius,10,10);
        gluDeleteQuadric(q);
        glPopMatrix();
    }/**/
    glPopMatrix();
}
Пример #22
0
void PLYObject::draw()
{
  int i, j;

  if (box) {
    glDisable(GL_COLOR_MATERIAL);
    glDisable(GL_LIGHTING);
    glColor3f(1.0, 0.0, 0.0);
    glPointSize(5.0);
    glBegin(GL_LINE_LOOP);
    glVertex3f(min[0], min[1], min[2]);
    glVertex3f(min[0], min[1], max[2]);
    glVertex3f(min[0], max[1], max[2]);
    glVertex3f(min[0], max[1], min[2]);
    glEnd();
    glBegin(GL_LINE_LOOP);
    glVertex3f(max[0], max[1], max[2]);
    glVertex3f(max[0], max[1], min[2]);
    glVertex3f(max[0], min[1], min[2]);
    glVertex3f(max[0], min[1], max[2]);
    glEnd();
    glBegin(GL_LINES);
    glVertex3f(min[0], min[1], min[2]);
    glVertex3f(max[0], min[1], min[2]);
    glVertex3f(min[0], min[1], max[2]);
    glVertex3f(max[0], min[1], max[2]);
    glVertex3f(min[0], max[1], max[2]);
    glVertex3f(max[0], max[1], max[2]);
    glVertex3f(min[0], max[1], min[2]);
    glVertex3f(max[0], max[1], min[2]);
    glEnd();
  }

  // setup default material
  glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, diffuse);
  glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);
  glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess);

  // render wireframe model
  if (wire) {
    glDisable(GL_LIGHTING);
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    glColor3f(0.05, 0.05, 0.05);
    
    glBegin(GL_TRIANGLES);
    for (i = 0; i < nf; i++){
      for (j = 0; j < 3; j++){
#ifdef INTERLEAVED
        glVertex3fv(vertices[faces[i][j]].pos);	// vertex coordinates
#else
        glVertex3fv(vertices[faces[i][j]]);	// vertex coordinates
		//printf("%d-(%f,%f,%f),", j, vertices[faces[i][j]][0], vertices[faces[i][j]][1], vertices[faces[i][j]][2]);
#endif
	  }
	  //printf("\n");
	}
    glEnd();

    glEnable(GL_POLYGON_OFFSET_FILL);
    glPolygonOffset(0.5, 1.0);
  }

  // setup per-point color mode
  //glColor3fv(diffuse);
  // fill_me

  if (hascolor) {
    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
	printf("hascolor...\n");
  }

  // set lighting if enabled
  if (light){
	glEnable(GL_LIGHTING);
  }
  else{
	glDisable(GL_LIGHTING);  
	glColor4fv(diffuse); // fish
  }

  // setup texture mode
  if (texture && hastexture) {
    glEnable(GL_TEXTURE_2D);

    // setup white object color for use with texture modulation
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, diffuse);
  }

  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  
  glBegin(GL_TRIANGLES);

  for (i = 0; i < nf; i++) {
    if (flat)
      glNormal3fv(fnormals[i]);			// face normal
    
    for (j = 0; j < 3; j++) {
	  if (texture && hastexture){
		glTexCoord2f(texcoords[i][j*2], texcoords[i][j*2+1]);
	  }
#ifdef INTERLEAVED
      if (!texture && hascolor)
        glColor3ubv((GLubyte*)vertices[faces[i][j]].c);
      if (!flat)
        glNormal3fv(vertices[faces[i][j]].nor);	// vertex normal

      glVertex3fv(vertices[faces[i][j]].pos);	// vertex coordinates
#else
      if (!texture && hascolor)
        glColor3ubv((GLubyte*)colors[faces[i][j]]);
      if (!flat)
        glNormal3fv(normals[faces[i][j]]);	// vertex normal

      glVertex3fv(vertices[faces[i][j]]);	// vertex coordinates
#endif
    }
  }
  glEnd();

  glDisable(GL_POLYGON_OFFSET_FILL);
  if (hascolor)
    glDisable(GL_COLOR_MATERIAL);
  if (texture && hastexture){
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_COLOR_MATERIAL);
  }
}
Пример #23
0
void MLSelectionBuffers::drawSelection(ML_SELECTION_TYPE selbuf) const
{
	QReadLocker locker(&_lock);

	if ((selbuf == ML_PERVERT_SEL) && (_m.cm.svn != 0))
	{
		const size_t privchunksize = std::min(size_t(_m.cm.VN()), size_t(_primitivebatch));
		
		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glDisable(GL_LIGHTING);
		glDisable(GL_TEXTURE_2D);
		glEnable(GL_BLEND);
		glDepthMask(GL_FALSE);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glColor4f(1.0f, 0.0, 0.0, .3f);
		glDepthRange(0.00, 0.999);
		glPointSize(3.0);
		glPushMatrix();
		glMultMatrix(_m.cm.Tr);

		if (_pointsize > 0.0f)
			glPointSize((GLfloat)_pointsize);
		for (size_t ii = 0; ii < _selmap[ML_PERVERT_SEL].size(); ++ii)
		{
			glBindBuffer(GL_ARRAY_BUFFER, _selmap[ML_PERVERT_SEL][ii]);
			glVertexPointer(3, GL_FLOAT, GLsizei(0), 0);
			glEnableClientState(GL_VERTEX_ARRAY);
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			unsigned int todraw = privchunksize;
			if (ii == (_selmap[ML_PERVERT_SEL].size() - 1))
				todraw = _m.cm.svn -  (privchunksize * ii); 

			//glGetBufferSubData(GL_ARRAY_BUFFER, 0, rp.size() * sizeof(vcg::Point3f), &(rp[0]));
			glDrawArrays(GL_POINTS, 0, todraw);

			glBindBuffer(GL_ARRAY_BUFFER, _selmap[ML_PERVERT_SEL][ii]);
			glDisableClientState(GL_VERTEX_ARRAY);
			glBindBuffer(GL_ARRAY_BUFFER, 0);
		}

		glPopMatrix();
		glPopAttrib();
	}


	if ((selbuf == ML_PERFACE_SEL) && (_m.cm.sfn != 0))
	{
		const size_t privchunksize = std::min(size_t(_m.cm.FN()), size_t(_primitivebatch));

		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glEnable(GL_POLYGON_OFFSET_FILL);
		glDisable(GL_LIGHTING);
		glDisable(GL_TEXTURE_2D);
		glEnable(GL_BLEND);
		glDepthMask(GL_FALSE);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glColor4f(1.0f, 0.0, 0.0, .3f);
		glPolygonOffset(-1.0, -1);
		glPushMatrix();
		glMultMatrix(_m.cm.Tr);


		for (size_t ii = 0; ii < _selmap[ML_PERFACE_SEL].size(); ++ii)
		{
			glBindBuffer(GL_ARRAY_BUFFER, _selmap[ML_PERFACE_SEL][ii]);
			glVertexPointer(3, GL_FLOAT, GLsizei(0), 0);
			glEnableClientState(GL_VERTEX_ARRAY);
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			unsigned int todraw = privchunksize;
			if (ii == _selmap[ML_PERFACE_SEL].size() - 1)
				todraw = _m.cm.sfn - (privchunksize * ii);
			glDrawArrays(GL_TRIANGLES, 0, 3 * todraw);
			glBindBuffer(GL_ARRAY_BUFFER, _selmap[ML_PERFACE_SEL][ii]);
			glDisableClientState(GL_VERTEX_ARRAY);
			glBindBuffer(GL_ARRAY_BUFFER, 0);

		}
		
		glPopMatrix();
		glPopAttrib();
	}
}
Пример #24
0
void World::draw(){
	double halfWidth = width/2;
	double halfHeight = height/2;

	glEnable(GL_POLYGON_OFFSET_FILL);
	glPolygonOffset(2,2);
	glBegin(GL_QUADS);
		//Back side
		glNormal3i(0, 1, 0);
		glTexCoord2f(0.33, 0);
		glVertex3f(-halfWidth, -halfHeight, 0.0f);
		glTexCoord2f(0.33, 0.33);
		glVertex3f(-halfWidth, -halfHeight, HIGH);
		glTexCoord2f(0.66, 0.33);
		glVertex3f(halfWidth, -halfHeight, HIGH);
		glTexCoord2f(0.66, 0);
		glVertex3f(halfWidth, -halfHeight, 0.0f);

		//Left side
		glNormal3i(1, 0, 0);
		glTexCoord2f(0, 0.66);
		glVertex3f(-halfWidth, halfHeight, 0.0f);
		glTexCoord2f(0.33, 0.66);
		glVertex3f(-halfWidth, halfHeight, HIGH);
		glTexCoord2f(0.33, 0.33);
		glVertex3f(-halfWidth, -halfHeight, HIGH);
		glTexCoord2f(0, 0.33);
		glVertex3f(-halfWidth, -halfHeight, 0.0f);

		//Right side
		glNormal3i(-1, 0, 0);
		glTexCoord2d(1, 0.33);
		glVertex3f(halfWidth, -halfHeight, 0.0f);
		glTexCoord2d(0.66, 0.33);
		glVertex3f(halfWidth, -halfHeight, HIGH);
		glTexCoord2d(0.66, 0.66);
		glVertex3f(halfWidth, halfHeight, HIGH);
		glTexCoord2d(1, 0.66);
		glVertex3f(halfWidth, halfHeight, 0.0f);

		//Front side
		glNormal3i(0, -1, 0);
		glTexCoord2d(0.66, 1);
		glVertex3f(halfWidth, halfHeight, 0.0f);
		glTexCoord2d(0.66, 0.66);
		glVertex3f(halfWidth, halfHeight, HIGH);
		glTexCoord2d(0.33, 0.66);
		glVertex3f(-halfWidth, halfHeight, HIGH);
		glTexCoord2d(0.33, 1);
		glVertex3f(-halfWidth, halfHeight, 0.0f);

		//Top side
		glNormal3i(0, 0, -1);
		glTexCoord2d(0.66, 0.66);
		glVertex3f(halfWidth, halfHeight, HIGH);
		glTexCoord2d(0.66, 0.33);
		glVertex3f(halfWidth, -halfHeight, HIGH);
		glTexCoord2d(0.33, 0.33);
		glVertex3f(-halfWidth, -halfHeight, HIGH);
		glTexCoord2d(0.33, 0.66);
		glVertex3f(-halfWidth, halfHeight, HIGH);
	glEnd();
	glPolygonOffset(0,0);
	glDisable(GL_POLYGON_OFFSET_FILL);
}
Пример #25
0
void Renderer::drawCovers(bool showTarget){
#ifdef COVER_ALPHA
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_ALPHA_TEST);
	glAlphaFunc(GL_GREATER,0.1f);
#endif
	
	if (cfgHighlightWidth == 0)
		showTarget = false;

	if (appInstance->albumCollection->getCount() == 0)
		return;

	float centerOffset = displayPos->getCenteredOffset();
	CollectionPos centerCover = displayPos->getCenteredPos();
	CollectionPos firstCover = displayPos->getOffsetPos(coverPos.getFirstCover() + 1);
	CollectionPos lastCover = displayPos->getOffsetPos(coverPos.getLastCover());
	lastCover++; // getOffsetPos does not return the end() element
	CollectionPos targetCover = appInstance->albumCollection->getTargetPos();

	int offset = appInstance->albumCollection->rank(firstCover) - appInstance->albumCollection->rank(centerCover);
	
	for (CollectionPos p = firstCover; p != lastCover; ++p, ++offset){
		float co = -centerOffset + offset;

		shared_ptr<ImgTexture> tex = texLoader->getLoadedImgTexture(p);
		tex->glBind();
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

		// calculate darkening
		float g = 1-(min(1.0f,(abs(co)-2)/5))*0.5f;
		if (abs(co) < 2)
			g = 1;
		/*float g = 1 - (abs(co)-2)*0.2f;
		g = 1 - abs(co)*0.1f;
		g = 1 - abs(zRot)/80;
		g= 1;
		if (g < 0) g = 0;*/
		glColor3f( g, g, g);
		glVectord origin(0, 0.5, 0);

		glQuad coverQuad = coverPos.getCoverQuad(co, tex->getAspect());
		
		glPushName(SELECTION_CENTER + offset);

		glBegin(GL_QUADS);
		if (glFogCoordf) glFogCoordf((GLfloat)coverPos.distanceToMirror(coverQuad.topLeft));
			glTexCoord2f(0.0f, 1.0f); // top left
			glVertex3fv((GLfloat*)&(coverQuad.topLeft.x));

			if (glFogCoordf) glFogCoordf((GLfloat)coverPos.distanceToMirror(coverQuad.topRight));
			glTexCoord2f(1.0f, 1.0f); // top right
			glVertex3fv((GLfloat*)&(coverQuad.topRight.x));

			if (glFogCoordf) glFogCoordf((GLfloat)coverPos.distanceToMirror(coverQuad.bottomRight));
			glTexCoord2f(1.0f, 0.0f); // bottom right
			glVertex3fv((GLfloat*)&(coverQuad.bottomRight.x));

			if (glFogCoordf) glFogCoordf((GLfloat)coverPos.distanceToMirror(coverQuad.bottomLeft));
			glTexCoord2f(0.0f, 0.0f); // bottom left
			glVertex3fv((GLfloat*)&(coverQuad.bottomLeft.x));
		glEnd();
		glPopName();

		if (showTarget){
			if (p == targetCover){
				bool clipPlane = false;
				if (glIsEnabled(GL_CLIP_PLANE0)){
					glDisable(GL_CLIP_PLANE0);
					clipPlane = true;
				}

				showTarget = false;
				
				glColor3f(GetRValue(cfgTitleColor) / 255.0f, GetGValue(cfgTitleColor) / 255.0f, GetBValue(cfgTitleColor) / 255.0f);

				glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
				glDisable(GL_TEXTURE_2D);

				glLineWidth((GLfloat)cfgHighlightWidth);
				glPolygonOffset(-1.0f, -1.0f);
				glEnable(GL_POLYGON_OFFSET_LINE);

				glEnable(GL_VERTEX_ARRAY);
				glVertexPointer(3, GL_FLOAT, 0, (void*) &coverQuad);
				glDrawArrays(GL_QUADS, 0, 4);

				glDisable(GL_POLYGON_OFFSET_LINE);

				glEnable(GL_TEXTURE_2D);


				if (clipPlane)
					glEnable(GL_CLIP_PLANE0);
			}
		}
	}

#ifdef COVER_ALPHA
	glDisable(GL_BLEND);
	glDisable(GL_ALPHA_TEST);
#endif
}
Пример #26
0
static void glsm_state_bind(void)
{
   glBindBuffer(GL_ARRAY_BUFFER, 0);

   unsigned i;

   for (i = 0; i < MAX_ATTRIB; i++)
   {
      if (gl_state.vertex_attrib_pointer.enabled[i])
         glEnableVertexAttribArray(i);
      else
         glDisableVertexAttribArray(i);

      if (gl_state.attrib_pointer.used[i]){
         glVertexAttribPointer(
            i,
            gl_state.attrib_pointer.size[i],
            gl_state.attrib_pointer.type[i],
            gl_state.attrib_pointer.normalized[i],
            gl_state.attrib_pointer.stride[i],
            gl_state.attrib_pointer.pointer[i]);
      }
   }

   for(i = 0; i < SGL_CAP_MAX; i ++)
   {
      if (gl_state.cap_state[i])
         glEnable(gl_state.cap_translate[i]);
   }

   glBindFramebuffer(RARCH_GL_FRAMEBUFFER, gl_state.framebuf);

   if (gl_state.blendfunc.used)
      glBlendFunc(
            gl_state.blendfunc.sfactor,
            gl_state.blendfunc.dfactor);

   glClearColor(
         gl_state.clear_color.r,
         gl_state.clear_color.g,
         gl_state.clear_color.b,
         gl_state.clear_color.a);

   if (gl_state.depthfunc.used)
      glDepthFunc(gl_state.depthfunc.func);

   if (gl_state.cullface.used)
      glCullFace(gl_state.cullface.mode);

   if (gl_state.depthmask.used)
      glDepthMask(gl_state.depthmask.mask);

   if (gl_state.polygonoffset.used)
      glPolygonOffset(
            gl_state.polygonoffset.factor,
            gl_state.polygonoffset.units);

   if (gl_state.scissor.used)
      glScissor(
            gl_state.scissor.x,
            gl_state.scissor.y,
            gl_state.scissor.w,
            gl_state.scissor.h);

   glUseProgram(gl_state.program);

   glViewport(
         gl_state.viewport.x,
         gl_state.viewport.y,
         gl_state.viewport.w,
         gl_state.viewport.h);

   for (i = 0; i < glsm_max_textures; i ++)
   {
      glActiveTexture(GL_TEXTURE0 + i);
      glBindTexture(GL_TEXTURE_2D, gl_state.bind_textures.ids[i]);
   }

   glActiveTexture(GL_TEXTURE0 + gl_state.active_texture);
}
Пример #27
0
//==========================================================================
//
// 
//
//==========================================================================
void GLWall::Draw(int pass)
{
	int rel;
	int tmode;

#ifdef _DEBUG
	if (seg->linedef-lines==879)
	{
		int a = 0;
	}
#endif


	switch (pass)
	{
	case GLPASS_LIGHTSONLY:
		SetupLights();
		break;

	case GLPASS_ALL:
		SetupLights();
		// fall through
	case GLPASS_PLAIN:
		rel = rellight + getExtraLight();
		gl_SetColor(lightlevel, rel, Colormap,1.0f);
		tmode = gl_RenderState.GetTextureMode();
		if (type!=RENDERWALL_M2SNF) gl_SetFog(lightlevel, rel, &Colormap, false);
		else
		{
			if (flags & GLT_CLAMPY)
			{
				if (tmode == TM_MODULATE) gl_RenderState.SetTextureMode(TM_CLAMPY);
			}
			gl_SetFog(255, 0, NULL, false);
		}
		gl_RenderState.EnableGlow(!!(flags & GLWF_GLOW));
		gl_RenderState.SetMaterial(gltexture, flags & 3, false, -1, false);
		RenderWall(RWF_TEXTURED|RWF_GLOW);
		gl_RenderState.EnableGlow(false);
		gl_RenderState.SetTextureMode(tmode);
		break;

	case GLPASS_TRANSLUCENT:


		switch (type)
		{
		case RENDERWALL_MIRRORSURFACE:
			RenderMirrorSurface();
			break;

		case RENDERWALL_FOGBOUNDARY:
			RenderFogBoundary();
			break;

		case RENDERWALL_COLORLAYER:
			glEnable(GL_POLYGON_OFFSET_FILL);
			glPolygonOffset(-1.0f, -128.0f);
			RenderTranslucentWall();
			glDisable(GL_POLYGON_OFFSET_FILL);
			glPolygonOffset(0, 0);

		default:
			RenderTranslucentWall();
			break;
		}
	}
}
Пример #28
0
void CProjectileDrawer::DrawGroundFlashes()
{
	static const GLfloat black[] = {0.0f, 0.0f, 0.0f, 0.0f};

	glDepthMask(GL_FALSE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	glActiveTexture(GL_TEXTURE0);
	groundFXAtlas->BindTexture();
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_ALPHA_TEST);
	glAlphaFunc(GL_GREATER, 0.01f);
	glPolygonOffset(-20, -1000);
	glEnable(GL_POLYGON_OFFSET_FILL);
	glFogfv(GL_FOG_COLOR, black);

	{
		GML_STDMUTEX_LOCK(rflash); // DrawGroundFlashes

		projectileHandler->groundFlashes.delete_delayed();
		projectileHandler->groundFlashes.add_delayed();
	}

	CGroundFlash::va = GetVertexArray();
	CGroundFlash::va->Initialize();
	CGroundFlash::va->EnlargeArrays(8, 0, VA_SIZE_TC);

	GroundFlashContainer& gfc = projectileHandler->groundFlashes;
	GroundFlashContainer::render_iterator gfi;

	bool depthTest = true;
	bool depthMask = false;

	for (gfi = gfc.render_begin(); gfi != gfc.render_end(); ++gfi) {
		CGroundFlash* gf = *gfi;

		const bool los = gu->spectatingFullView || loshandler->InAirLos(gf->pos, gu->myAllyTeam);
		const bool vis = camera->InView(gf->pos, gf->size);

		if (depthTest != gf->depthTest) {
			depthTest = gf->depthTest;

			if (depthTest) {
				glEnable(GL_DEPTH_TEST);
			} else {
				glDisable(GL_DEPTH_TEST);
			}
		}
		if (depthMask != gf->depthMask) {
			depthMask = gf->depthMask;

			if (depthMask) {
				glDepthMask(GL_TRUE);
			} else {
				glDepthMask(GL_FALSE);
			}
		}

		if ((gf->alwaysVisible || los) && vis) {
			gf->Draw();
		}

		CGroundFlash::va->DrawArrayTC(GL_QUADS);
		CGroundFlash::va->Initialize();
	}


	glFogfv(GL_FOG_COLOR, mapInfo->atmosphere.fogColor);
	glDisable(GL_POLYGON_OFFSET_FILL);
	glDisable(GL_ALPHA_TEST);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glDisable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
}
Пример #29
0
static void glsm_state_bind(void)
{
   unsigned i;

   for (i = 0; i < MAX_ATTRIB; i++)
   {
      if (gl_state.vertex_attrib_pointer.enabled[i])
         glEnableVertexAttribArray(i);
      else
         glDisableVertexAttribArray(i);
   }

   glBindFramebuffer(RARCH_GL_FRAMEBUFFER, hw_render.get_current_framebuffer());

   if (gl_state.blendfunc.used)
      glBlendFunc(
            gl_state.blendfunc.sfactor,
            gl_state.blendfunc.dfactor);

   if (gl_state.blendfunc_separate.used)
      glBlendFuncSeparate(
            gl_state.blendfunc_separate.srcRGB,
            gl_state.blendfunc_separate.dstRGB,
            gl_state.blendfunc_separate.srcAlpha,
            gl_state.blendfunc_separate.dstAlpha
            );

   glClearColor(
         gl_state.clear_color.r,
         gl_state.clear_color.g,
         gl_state.clear_color.b,
         gl_state.clear_color.a);

   if (gl_state.depthfunc.used)
      glDepthFunc(gl_state.depthfunc.func);

   if (gl_state.colormask.used)
      glColorMask(
            gl_state.colormask.red,
            gl_state.colormask.green,
            gl_state.colormask.blue,
            gl_state.colormask.alpha);

   if (gl_state.cullface.used)
      glCullFace(gl_state.cullface.mode);

   if (gl_state.depthmask.used)
      glDepthMask(gl_state.depthmask.mask);

   if (gl_state.polygonoffset.used)
      glPolygonOffset(
            gl_state.polygonoffset.factor,
            gl_state.polygonoffset.units);

   if (gl_state.scissor.used)
      glScissor(
            gl_state.scissor.x,
            gl_state.scissor.y,
            gl_state.scissor.w,
            gl_state.scissor.h);

   glUseProgram(gl_state.program);

   glViewport(
         gl_state.viewport.x,
         gl_state.viewport.y,
         gl_state.viewport.w,
         gl_state.viewport.h);
#ifdef CORE
   glBindVertexArray(gl_state.vao);
#endif
   for(i = 0; i < SGL_CAP_MAX; i ++)
   {
      if (gl_state.cap_state[i])
         glEnable(gl_state.cap_translate[i]);
   }

   if (gl_state.frontface.used)
      glFrontFace(gl_state.frontface.mode);

   if (gl_state.stencilmask.used)
      glStencilMask(gl_state.stencilmask.mask);

   if (gl_state.stencilop.used)
      glStencilOp(gl_state.stencilop.sfail,
            gl_state.stencilop.dpfail,
            gl_state.stencilop.dppass);

   if (gl_state.stencilfunc.used)
      glStencilFunc(
            gl_state.stencilfunc.func,
            gl_state.stencilfunc.ref,
            gl_state.stencilfunc.mask);

   for (i = 0; i < MAX_TEXTURE; i ++)
   {
      glActiveTexture(GL_TEXTURE0 + i);
      glBindTexture(GL_TEXTURE_2D, gl_state.bind_textures.ids[i]);
   }

   glActiveTexture(GL_TEXTURE0 + gl_state.active_texture);

   glBindBuffer(GL_ARRAY_BUFFER, 0);
}
Пример #30
0
//==============================
// VRMenuMgrLocal::RenderSubmitted
void VRMenuMgrLocal::RenderSubmitted( Matrix4f const & worldMVP ) const
{
	if ( NumSubmitted == 0 )
	{
		return;
	}

	GL_CheckErrors( "VRMenuMgrLocal::RenderSubmitted - pre" );

	//LOG( "VRMenuMgrLocal::RenderSubmitted" );

	//LOG( "VRMenuMgrLocal::RenderSubmitted - rendering %i objects", NumSubmitted );
	bool depthEnabled = true;
	glEnable( GL_DEPTH_TEST );
	bool polygonOffset = false;
	glDisable( GL_POLYGON_OFFSET_FILL );
	glPolygonOffset( 0.0f, -10.0f );

	for ( int i = 0; i < NumSubmitted; ++i )
	{
		int idx = SortKeys[i].Key & 0xFFFFFFFF;
#if 0
		int di = SortKeys[i].Key >> 32ULL;
		float const df = *((float*)(&di ));
		LOG( "Surface '%s', sk = %llu, df = %.2f, idx = %i", Submitted[idx].SurfaceName.ToCStr(), SortKeys[i].Key, df, idx );
#endif
		SubmittedMenuObject const & cur = Submitted[idx];
			
		VRMenuObjectLocal const * obj = static_cast< VRMenuObjectLocal const * >( ToObject( cur.Handle ) );
		if ( obj != NULL )
		{
			// TODO: this could be made into a generic template for any glEnable() flag
			if ( cur.Flags & VRMENU_RENDER_NO_DEPTH )
			{
				if ( depthEnabled )
				{
					glDisable( GL_DEPTH_TEST );
					depthEnabled = false;
				}
			}
			else if ( !( cur.Flags & VRMENU_RENDER_NO_DEPTH ) )
			{
				if ( !depthEnabled )
				{
					glEnable( GL_DEPTH_TEST );
					depthEnabled = true;
				}
			}
			if ( cur.Flags & VRMENU_RENDER_POLYGON_OFFSET )
			{
				if ( !polygonOffset )
				{
					glEnable( GL_POLYGON_OFFSET_FILL );
					polygonOffset = true;
				}
			}
			else
			{
				if ( polygonOffset )
				{
					glDisable( GL_POLYGON_OFFSET_FILL );
					polygonOffset = false;
				}
			}
			Vector3f translation( cur.Pose.Position.x + cur.Offsets.x, cur.Pose.Position.y + cur.Offsets.y, cur.Pose.Position.z );
			Matrix4f transform( cur.Pose.Orientation );
			Matrix4f scaleMatrix;
			scaleMatrix.M[0][0] = cur.Scale.x;
			scaleMatrix.M[1][1] = cur.Scale.y;
			scaleMatrix.M[2][2] = cur.Scale.z;
			transform *= scaleMatrix;
			transform.SetTranslation( translation );
			Matrix4f mvp = transform.Transposed() * worldMVP;
			obj->RenderSurface( *this, mvp, cur );
		}
	}

	glDisable( GL_POLYGON_OFFSET_FILL );

	GL_CheckErrors( "VRMenuMgrLocal::RenderSubmitted - post" );
}