コード例 #1
0
ファイル: main.cpp プロジェクト: llq664301573/rubick
int main()
{
	Cube::init(cubes);

	glfwSetErrorCallback(error_callback);
	if (!glfwInit())
		return EXIT_FAILURE;

	glfwWindowHint(GLFW_SAMPLES, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	GLFWwindow* window = glfwCreateWindow(640, 480, "rubick-cube", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return EXIT_FAILURE;
	}

	glfwMakeContextCurrent(window);
	glfwSetKeyCallback(window, key_callback);
	glfwSetMouseButtonCallback(window, mousebutton_callback);
	glfwSetCursorPosCallback(window, cursorpos_callback);
	glfwSetScrollCallback(window, scroll_callback);
	glfwSetWindowSizeCallback(window, windowsize_callback);

	// Initialize GLEW
	glewExperimental = true; // Needed for core profile
	if (glewInit() != GLEW_OK) {
		fprintf(stderr, "Failed to initialize GLEW\n");
		return EXIT_FAILURE;
	}

	GLuint VertexArrayID;
	glGenVertexArrays(1, &VertexArrayID);
	glBindVertexArray(VertexArrayID);

	// Create and compile our GLSL program from the shaders
	GLuint programID = loadShaders(2, "shaders/SimpleVertexShader.vertexshader", "shaders/SimpleFragmentShader.fragmentshader" );

	GLuint matrixID = glGetUniformLocation(programID, "MVP");

	projection = perspective(45.0f, 4.0f / 3.0f, 1.0f, 1000.0f);
	view = lookAt(eye, vec3(0, 0, 0), vec3(0, 1, 0));

	camera = rotate(mat4(), 45.0f, vec3(1, 0, 0)) * rotate(mat4(), 45.0f, vec3(0, 1, 0));

	const GLuint Texture = 1000;
	TextureManager::Inst()->LoadTexture("images/cube.png", Texture, GL_BGRA);
	GLuint TextureID  = glGetUniformLocation(programID, "myTextureSampler");


	GLuint vertexbuffer;
	glGenBuffers(1, &vertexbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer_data), vertex_buffer_data, GL_STATIC_DRAW);

	GLuint uvbuffer;
	glGenBuffers(1, &uvbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(uv_buffer_data), uv_buffer_data, GL_STATIC_DRAW);


	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);

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

	while (!glfwWindowShouldClose(window))
	{
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glUseProgram(programID);

		// Bind our texture in Texture Unit 0
		glActiveTexture(GL_TEXTURE0);
		TextureManager::Inst()->BindTexture(TextureID);
		// Set our "myTextureSampler" sampler to user Texture Unit 0
		glUniform1i(TextureID, 0);


		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
		glVertexAttribPointer(
			0,                  // match the layout in the shader.
			3,                  // size
			GL_FLOAT,           // type
			GL_FALSE,           // normalized?
			0,                  // stride
			(void*)0            // array buffer offset
		);

		glEnableVertexAttribArray(1);
		glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
		glVertexAttribPointer(
			1,                  // match the layout in the shader.
			2,                  // size
			GL_FLOAT,           // type
			GL_FALSE,           // normalized?
			0,                  // stride
			(void*)0            // array buffer offset
		);

		const float delta = 15;
		if(picker.angle > 0)
			picker.angle -= delta;

		for (int i=0;i<cubes.size();i++)
		{
			Cube* cube = cubes[i];

			mat4 MVP;
			if(picker.face[0] != NULL && picker.face[1] != NULL)
			{
				const vec3& pivot = picker.rotation.pivot;
				const vec3& axis = picker.rotation.axis;
				mat4 rotMatrix = rotate(mat4(), delta, axis);
				const vec3& v1 = picker.face[0]->center;
				const vec3& v2 = picker.face[1]->center;
				if(pivot.x == v1.x && pivot.x == v2.x)
				{
					if(cube->pos.x == pivot.x)
					{
						cube->pickMatirx = rotMatrix * cube->pickMatirx;
						cube->pos = rotMatrix * cube->pos;

						if(picker.angle == 0)
							cube->pos = round(cube->pos);
					}
				}
				else if(pivot.y == v1.y && pivot.y == v2.y)
				{
					if(cube->pos.y == pivot.y)
					{
						cube->pickMatirx = rotMatrix * cube->pickMatirx;
						cube->pos = rotMatrix * cube->pos;

						if(picker.angle == 0)
							cube->pos = round(cube->pos);
					}
				}
				else
				{
					if(cube->pos.z == pivot.z)
					{
						cube->pickMatirx = rotMatrix * cube->pickMatirx;
						cube->pos = rotMatrix * cube->pos;

						if(picker.angle == 0)
							cube->pos = round(cube->pos);
					}
				}	
			}

			MVP = projection * view * camera * scroll * cube->pickMatirx * cube->modelMatrix;
			
			glUniformMatrix4fv(matrixID, 1, GL_FALSE, (float*)&MVP);
			glDrawArrays(GL_TRIANGLES, 0, 12 * 3);
		}

		glDisableVertexAttribArray(1);
		glDisableVertexAttribArray(0);

		if(picker.face[0] != NULL && picker.face[1] != NULL && picker.angle == 0)
			picker.face[0] = picker.face[1] = NULL;

		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	glDeleteBuffers(1, &uvbuffer);
	glDeleteBuffers(1, &vertexbuffer);
	glDeleteProgram(programID);
	glDeleteVertexArrays(1, &VertexArrayID);

	Cube::clear(cubes);

	glfwDestroyWindow(window);
	glfwTerminate();
	
	return EXIT_SUCCESS;
}
コード例 #2
0
ファイル: renderer.cpp プロジェクト: rostj/pedantica
void Renderer::render(const Player& player, const std::vector<Entity>& entities, const std::vector<Enemy*>& enemies, const Camera* currentCamera, const bool cameraIsFPS) {
	static float scaleval{};
	static bool direction{};

	if(direction) {
		if(scaleval<50.0f)
			scaleval+=0.005f;
		else
			direction=false;
	}
	else {
		if(scaleval>0.005f)
			scaleval-=0.005f;
		else
			direction=true;
	}



	mat4 projection{1.0f};

	const float obliqueZoom{1.0f};

	if(cameraIsFPS==false)
		projection*=ortho(0.0f, contextW/64.0f/obliqueZoom, 0.0f,contextH/64.0f/obliqueZoom, -20.0f, 20.0f);
	else
		projection*=perspective(radians(60.0f+(float)(currentCamera->getSights()*60)),aspectRatio,0.05f,400.0f);

	std::stack<mat4> modelview;

	modelview.push(mat4{1.0f});

	if(cameraIsFPS==false) {
		projection*=rotate(radians(60.0f), vec3(1.0f, 0.0f, 0.0f));
		projection*=translate(currentCamera->getPosition());
		//glViewport((contextW-contextH)/2.0f,0,contextH,contextH);
	}
	else {
		projection*=lookAt(
			currentCamera->getPosition(),
			vec3(
				currentCamera->getPosition().x-currentCamera->sinAlfa()*currentCamera->cosBeta(),
				currentCamera->getPosition().y-currentCamera->sinBeta(),
				currentCamera->getPosition().z+currentCamera->cosAlfa()*currentCamera->cosBeta()
			),
			vec3{0.0f,1.0f,0.0f}
		);

		glViewport(0,0,contextW,contextH);
	}

	//Upload camera projection matrix

	program->use();
	program->projectionMatrix(projection);
	program->normalMatrix(modelview.top());





	glUniform1f(glGetUniformLocation(program->getId(),"displacementValue"),scaleval);



	glError();

//set listener position
ALfloat pos[]={currentCamera->getPosition().x,currentCamera->getPosition().y,currentCamera->getPosition().z};
ALfloat orientation[]={
	ALfloat(currentCamera->sinAlfa()*currentCamera->cosBeta()),
	ALfloat(currentCamera->sinBeta()),
	ALfloat(currentCamera->cosAlfa()*currentCamera->cosBeta())
};

alListenerfv(AL_POSITION,pos);
alListenerfv(AL_ORIENTATION,orientation);


	//Start rendering by clearing buffers

	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

	//
	// Render gun
	//

	modelview.push(modelview.top());
	modelview.top()*=translate(currentCamera->getPosition());

	modelview.top()*=rotate(radians((float)-currentCamera->getYaw()+180.0f),vec3(0.0f,1.0f,0.0f));
	modelview.top()*=rotate(radians((float)-currentCamera->getPitch()),vec3(1.0f,0.0f,0.0f));

	//delay effect
	const double sightsCompensation{((currentCamera->getSights()+0.18)*0.2)*20};
	const double delayX{currentCamera->getDelay()*sightsCompensation};
	const double delayY{currentCamera->getDelayY()*sightsCompensation};

	modelview.top()*=translate(
		vec3{	-(delayX*5.0),
				delayY*5.0,
			currentCamera->getRecoil()+fabs(delayY*5.0)+fabs(5.0f*delayX)+fabs(5.0f*delayX)
		});
	//looking down sights
	modelview.top()*=translate(vec3{currentCamera->getSights(),0.0f,0.0f-(currentCamera->getSights())});
	program->modelviewMatrix(modelview.top());

	for(auto m: models) {
		if(m->getName()=="models/gun.obj") //"models/knife.obj"
			m->render(program->getId());
	}

	//Update Gun Ammo Texture and don't update it every frame

	for(auto m: models) {
		if(m->getName()=="models/gun_display.obj") {
			static Texture* temp{nullptr}; //rendered texture for ammo display
			static int renderedAmmo{-1}; //last update for rendering ammo texture
			const unsigned int ammo{player.getGunAmmo()}; //current ammo

			if(renderedAmmo!=ammo) {
				std::stringstream ss;

				delete temp;
				ss<<(ammo<10?"  ":" ")<<ammo<<(ammo<10?"  ":" ");
				temp=fManager.renderToTexture(ss.str(),FontSize::MEDIUM);
				m->parts[0].mat->displacement=temp;

				const float ammoDivided{1.0f-((40.0f-float(ammo))/40.0f)};

				//inverse colors
				const vec3 green{1.0,0.0,1.0};
				const vec3 red{0.0,1.0,1.0};
				const vec3 yellow{0.0,0.0,1.0};

				m->parts[0].mat->dcolor=glm::normalize((mix(red,yellow,ammoDivided*0.5))+(ammoDivided*green*2));
				//green m->parts[0].mat->dcolor=vec3{1.0,0.0,1.0};
				//red m->parts[0].mat->dcolor=vec3{0.0,1.0,1.0};
				//yellow m->parts[0].mat->dcolor=vec3{0.0,0.15,1.0};
				renderedAmmo=ammo;
			}

			glUniform1f(glGetUniformLocation(program->getId(),"renderTL"),3.0f);
			m->render(program->getId());
			glUniform1f(glGetUniformLocation(program->getId(),"renderTL"),0.0f);
		}
	}

			modelview.pop();
	//
	// END RENDER GUN
	//


	const float RENDER_CLIP_DISTANCE{24.0f*10};


	double asdf=0.0;


//add falling flying enemies
	std::vector<Enemy*> tmpEnemies=enemies;

	for(auto e: entities) {
		if(e.modelName=="models/flyingenemy-spikes.obj") {
			tmpEnemies.push_back(new FlyingEnemy{vec3{},vec3{},100});
			tmpEnemies.back()->rotationMatrix=e.rotationMatrix;
		}
	}

	//Render flying enemies
	for(auto enemy: tmpEnemies) {
		//check if in distance
		if( glm::distance(currentCamera->getPosition(),enemy->position) > RENDER_CLIP_DISTANCE )
			continue;

		auto parts=enemy->renderableEntities();
		//Render each enemy part
		for(size_t i=0; i<parts.size(); ++i) {
			modelview.push(modelview.top());
			//modelview.top()*=glm::scale(vec3{0.5f,0.5f,0.5f});

			//compensate tentacles position
			if(i>0) {
				modelview.top()*=translate(parts[0].position);
				modelview.top()*=glm::mat4_cast(glm::quat{vec3{parts[0].rotation}});
				modelview.top()*=parts[0].rotationMatrix;
			}

			modelview.top()*=translate(parts[i].position);
			modelview.top()*=glm::mat4_cast(glm::quat{vec3{parts[i].rotation}});
			modelview.top()*=parts[i].rotationMatrix;

			program->modelviewMatrix(modelview.top());

			if(parts[i].modelName=="models/tentacle.obj") {
				asdf++;
				glUniform1f(glGetUniformLocation(program->getId(),"displacementValue"),scaleval+(asdf));
				glUniform1f(glGetUniformLocation(program->getId(),"renderTL"),99.0f);
			}

			for(auto m: models) {
				if(m->getName()==parts[i].modelName) {
					m->render(program->getId());
				}
			}

			glUniform1f(glGetUniformLocation(program->getId(),"renderTL"),0.0f);
			modelview.pop();
		}
	}

	//Render other entities
	for(auto entity: entities) {
		//check if in distance
		if( glm::distance(currentCamera->getPosition(),entity.position) > RENDER_CLIP_DISTANCE )
			continue;

		if(entity.modelName=="models/flyingenemy-spikes.obj")
			continue;

		modelview.push(modelview.top());
		//modelview.top()*=translate(entity.position);
		modelview.top()*=rotate(radians(entity.rotation.w),glm::vec3{entity.rotation});
		modelview.top()*=entity.rotationMatrix;

		program->modelviewMatrix(modelview.top());


		for(auto m: models) {
			if(m->getName()==entity.modelName) {
				Texture* temp{nullptr};

				//
				//	Render Traffic Light
				//
				if(m->getName()=="models/traffic_light_pedestrian.obj") {
					static size_t ticks=SDL_GetTicks()+9000;
//FIXME move to logic classes
					std::stringstream ss;
					int result=ticks-SDL_GetTicks();

					if(result<0)
						result=0;

					result/=1000;

					if(result>0) {
						glUniform1f(glGetUniformLocation(program->getId(),"renderTL"),1.0f);
						ss<<result;
						temp=fManager.renderToTexture(result<1?" ":ss.str(),FontSize::SMALL);
						m->parts[1].mat->displacement=temp;

						m->parts[0].mat->dcolor=vec3{0.0,0.0,0.0};
					}
					else {
						glUniform1f(glGetUniformLocation(program->getId(),"renderTL"),2.0f);
						m->parts[1].mat->dcolor=vec3{0.0,0.0,0.0};
						m->parts[0].mat->dcolor=vec3{0.0,1.0,0.0};
					}
				}

				m->render(program->getId());
				glUniform1f(glGetUniformLocation(program->getId(),"renderTL"),0.0f);
				delete temp;
			}

		}

		modelview.pop();
	}

}
コード例 #3
0
ファイル: Matrices.cpp プロジェクト: yhnchang/yup
Matrix4& Matrix4::lookAt(float tx, float ty, float tz, float ux, float uy, float uz)
{
    return lookAt(Vector3(tx, ty, tz), Vector3(ux, uy, uz));
}
コード例 #4
0
ファイル: main.cpp プロジェクト: PONT-MAX/TSBK07
void display(void)
{
    //std::cout << "time boost = " << time_boost << std::endl;
    if (time_boost >= 1) {
        time_boost -= 1;
        if (time_boost < 1) {
            std::cout << "BOOST OFF!" << std::endl;
            game_->ball_speed = game_->ball_speed_global;
            game_->imortality = false;
        }
    }
    
    
    //printf("d1 \n");

    
    t += 0.005;
    game_->world_dir();
    // clear the screen
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    
    mat4 total, modelView, camMatrix;
    
    printError("pre display");
    
    glUseProgram(program);
    // Build matrix

    vec3 cam = vec3(0, 5, 8);
    vec3 lookAtPoint = vec3(2, 0, 2);
    camMatrix = lookAt(cam.x, cam.y, cam.z,
                       lookAtPoint.x, lookAtPoint.y, lookAtPoint.z,
                       0.0, 1.0, 0.0);
    modelView = IdentityMatrix();
    total = Mult(camMatrix, modelView);
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    glUniformMatrix4fv(glGetUniformLocation(program, "Camera"), 1, GL_TRUE, camera.m);
    
    // skybox
    
    // Disable Z-buffer to draw sky
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
    
    // Use skytex as texture and switch to skyprogram
    glUseProgram(skyprogram);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, skytex);
    
    
    // Sky
    mat4 skylookAT = camera;
    skylookAT.m[3] = 0;
    skylookAT.m[7] = 0;
    skylookAT.m[11] = 0;
    
    skylookAT = Mult(T(-0.2,0,0), skylookAT);
    mat4 skyrot = Ry(game_->turn_angle*game_->pol_dir);
    skytot = Mult(skytot, skyrot);

    glUniformMatrix4fv(glGetUniformLocation(skyprogram, "lookAT"), 1, GL_TRUE, skylookAT.m);
    
    glUniformMatrix4fv(glGetUniformLocation(skyprogram, "mdlMatrix"),1, GL_TRUE, skytot.m);
    DrawModel(skybox, skyprogram, "in_Position", NULL, "in_TexCoord");
    printError("sky shader");
    
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glUseProgram(program);

    
    glBindTexture(GL_TEXTURE_2D, tex1);		// Bind Our Texture tex1
    glActiveTexture(GL_TEXTURE0);
    
    
    // game clock
    if (!game_->dead) {
        // game clock
        time_count += 0.02;
        snprintf(buffer, 50, "%f", time_count);
        sfDrawString(30, 30, "Elapsed Time:");
        sfDrawString(170, 30, buffer);
        if (game_->ball_speed_global < 5) {
            game_->ball_speed_global += 0.0002;
        }
        
    }
    
    
    
    //Current
    total = game_->maze->get_total();
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(game_->maze->track, program, "inPosition", "inNormal", "inTexCoord");
    
    //left
    total = game_->maze->left->get_total();
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(game_->maze->left->track, program, "inPosition", "inNormal", "inTexCoord");
    
    //left->left
    total = game_->maze->left->left->get_total();
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(game_->maze->left->left->track, program, "inPosition", "inNormal", "inTexCoord");
    
    //left->right
    total = game_->maze->left->right->get_total();
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(game_->maze->left->right->track, program, "inPosition", "inNormal", "inTexCoord");
    
    
    //right
    total = game_->maze->right->get_total();
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(game_->maze->right->track, program, "inPosition", "inNormal", "inTexCoord");
    //right->left
    total = game_->maze->right->left->get_total();
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(game_->maze->right->left->track, program, "inPosition", "inNormal", "inTexCoord");
    //right->right
    total = game_->maze->right->right->get_total();
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(game_->maze->right->right->track, program, "inPosition", "inNormal", "inTexCoord");
    
    
    


    //sphere
    glBindTexture(GL_TEXTURE_2D, tex2);
    glActiveTexture(GL_TEXTURE0);

    //    GLfloat y_pos_des = height_controll(x_pos, z_pos,&ttex,tm)+0.1;
    //    y_pos -= (y_pos - y_pos_des)/1*0.5;
    game_->update();
    if (game_->generate_terrain_bool) {
        NewTerrain(game_->x_pos);
        game_->generate_terrain_bool = false;
    }

    //trans = T(0,0,0); // <<< --  Vart spheren är
    //rot = Rx(0);
    //rot = Ry(M_PI_2/4);
    //total = game_->player_->total_pos();//Mult(game_->strans, rot);

    camera = game_->update_camera();
    
    //Body
    total = game_->player_->body_total;
    
    glBindTexture(GL_TEXTURE_2D, tex_body);
    glActiveTexture(GL_TEXTURE0);
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(Body,program,"inPosition","inNormal","inTexCoord");
    
    //Rest of player init tex
    glBindTexture(GL_TEXTURE_2D, tex_head);
    glActiveTexture(GL_TEXTURE0);
    
    total = game_->player_->head_total;
    
    //head
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(Body,program,"inPosition","inNormal","inTexCoord");
    
    //arms
    total = game_->player_->arm_total_l;
    //lsft
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(ArmL,program,"inPosition","inNormal","inTexCoord");
    
    total = game_->player_->arm_total_r;
    //right
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(ArmR,program,"inPosition","inNormal","inTexCoord");
    
    //legs
    total = game_->player_->leg_total_l;
    //Left
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(LegL,program,"inPosition","inNormal","inTexCoord");
    
    total = game_->player_->leg_total_r;
    //Right
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
    DrawModel(LegR,program,"inPosition","inNormal","inTexCoord");
    
    
    //Lava
    glBindTexture(GL_TEXTURE_2D, lavatex);
    glActiveTexture(GL_TEXTURE0);
    
    lavatot = Mult(T(0.0,(game_->y_pos_t),0.0),lavatot);
    lavatot = Mult(lavatot, skyrot);
    
    glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, lavatot.m);
    DrawModel(Lava,program,"inPosition","inNormal","inTexCoord");
    
    
    
    //BOOSTERS
    // ---------------------- ______________------------------
    //printf("b1 \n");
    
    bool b_col = game_->maze->b_collision;
    // printf("bool b_collision: %d \n", b_col );
    
    if (b_col == false){
        
        game_->boost_collision();
        draw_boost(game_->maze);
        b_col = game_->maze->b_collision;
        if (b_col == true) { // if collision give points
            time_count += 100;
            time_boost = (3*(1+game_->ball_speed))*(1/0.02);
            std::cout << "tB = " << time_boost << std::endl;
            if (game_->maze->boost == 1) { //if speed
                game_->ball_speed += 1;
            }
            else{ // if imortality
                game_->imortality = true;
            }
        }
        
    }

    draw_boost(game_->maze->right);
    draw_boost(game_->maze->left);
    
    

    
    //  printf("obstacle main%d \n", obstacle );
    //  printf("obstaclex main %d \n", obstacle_x_pos );

    draw_obsticle(game_->maze);
        draw_obsticle(game_->maze->left);
        draw_obsticle(game_->maze->right);
    
    
    if (game_->dead) {
        sfSetRasterSize(600, 200);
        sfDrawString(250, 90, "GAME OVER");
        
        GLfloat time_score = time_count;
        snprintf(buffer, 50, "%f", time_score);
        sfDrawString(220, 110, "Score: ");
        sfDrawString(290, 110, buffer);
    }

   
    printError("display 2");
    
    glutSwapBuffers();
}
コード例 #5
0
ファイル: ofEasyCam.cpp プロジェクト: nanu-c/openFrameworks
//----------------------------------------
void ofEasyCam::setTarget(const glm::vec3& targetPoint){
	target.setPosition(targetPoint);
	lookAt(target);
}
コード例 #6
0
ファイル: geActor.cpp プロジェクト: ileben/GameEngine
 void Actor3D::lookInto (const Vector3 &point, Vector3 up)
 {
   Vector3 center = mat.getColumn(3).xyz();
   lookAt( point - center, up );
 }
コード例 #7
0
ファイル: Camera.cpp プロジェクト: cozza13/hifi
void Camera::update(float deltaTime) {
    if (_isKeepLookingAt) {
        lookAt(_lookingAt);
    }
    return;
}
コード例 #8
0
ファイル: GLCamera.cpp プロジェクト: FreakyBytes/CG-OpenGL
  //--------------------------------------------------------------------------------------
  // Update the view matrix based on user input & elapsed time
  //--------------------------------------------------------------------------------------
  void CFirstPersonCamera::FrameMove( double fElapsedTime )
  {
      if( IsKeyDown( mKeys[CAM_RESET] ) ) {
          Reset();
      }

      if (IsKeyDown(mKeys[CAM_ACCELERATE])) {
        if (mKeyboardMoveScaler < 10000.0) {
          mKeyboardMoveScaler *= 1.2;
        }

        if (mMouseMoveScaler < 10000.0) {
          mMouseMoveScaler *= 1.2;
        }
        //since accelerating shouldn't be done continously, force key up here
        HandleKeys(CAM_ACCELERATE, false);
      }
      if (IsKeyDown(mKeys[CAM_THROTTLE])) {
        if (mKeyboardMoveScaler > 0.1) {
          mKeyboardMoveScaler /= 1.2;
        }

        if (mMouseMoveScaler > 0.1) {
          mMouseMoveScaler /= 1.2;
        }

        HandleKeys(CAM_THROTTLE, false);
      }

      // Get keyboard/mouse/gamepad input
      GetInput( mEnablePositionMovement, ( mActiveButtonMask & mCurrentButtonMask ) || mRotateWithoutButtonDown,
                true, mResetCursorAfterMove );

      // Get amount of velocity based on the keyboard input and drag (if any)
      UpdateVelocity( fElapsedTime );

      // Simple euler method to calculate position delta
      dvec3 vPosDelta = mVelocity * fElapsedTime;

      // If rotating the camera 
      if (mMouseRotates) {
        if( ( mActiveButtonMask & mCurrentButtonMask ) || mRotateWithoutButtonDown) {

            // Update the pitch & yaw angle based on mouse movement
          double fYawDelta = mRotVelocity.x;
          double fPitchDelta = mRotVelocity.y;

            // Invert pitch if requested
            if( mInvertPitch )
                fPitchDelta = -fPitchDelta;

            mCameraPitchAngle -= fPitchDelta;
            mCameraYawAngle -= fYawDelta;

            // Limit pitch to straight up or straight down
            mCameraPitchAngle = std::max( -pi<double>() * 0.499, mCameraPitchAngle );
            mCameraPitchAngle = std::min( +pi<double>() * 0.499, mCameraPitchAngle );
        }
      }

      // Make a rotation matrix based on the camera's yaw & pitch
      dmat4 mCameraRot = yawPitchRoll(mCameraYawAngle, mCameraPitchAngle, 0.0);


      // Transform vectors based on camera's rotation matrix
      dvec3 vWorldUp, vWorldAhead;
      const dvec3 vLocalUp = dvec3( 0, 1, 0 );
      const dvec3 vLocalAhead = dvec3( 0, 0, -1 );

      vWorldUp = Vec3TransformCoord(vLocalUp, mCameraRot);
      vWorldAhead = Vec3TransformCoord(vLocalAhead, mCameraRot);

      // Transform the position delta by the camera's rotation 
      dvec3 vPosDeltaWorld;
      if( !mEnableYAxisMovement )
      {
          // If restricting Y movement, do not include pitch
          // when transforming position delta vector.
          mCameraRot = yawPitchRoll(mCameraYawAngle, 0.0, 0.0 );
      }

      vPosDeltaWorld = Vec3TransformCoord(vPosDelta, mCameraRot );

      // Move the eye position 
      mEye += vPosDeltaWorld;
      if( mClipToBoundary )
          ConstrainToBoundary( &mEye );

      // Update the lookAt position based on the eye position 
      mLookAt = mEye + vWorldAhead;

      // Update the view matrix
      mViewMatrix = lookAt(mEye, mLookAt, vWorldUp );

      mCameraWorld = inverse(mViewMatrix );
  }
コード例 #9
0
ファイル: App.cpp プロジェクト: ZachMassia/GAME303
void App::createScene()
{
#pragma region Plane
	// Define the mathematical plane
	Ogre::Plane plane(Vector3::UNIT_Y, 0);
	
	// Create the plane into memory
	Ogre::MeshManager::getSingleton().createPlane(
		"plane",
		ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		plane,
		500, 500, // size
		25, 25,   // how many quads are used to make the plane
		true,
		1, 5, 5, Vector3::UNIT_Z);

	// Create an instance of the plane
	auto planeEnt = mSceneMgr->createEntity("PlaneEntity", "plane");
	planeEnt->setMaterialName("Examples/BeachStones");

	// Create a node for the plane and attach he plane to it
	mSceneMgr->getRootSceneNode()->createChildSceneNode("planeNode")->attachObject(planeEnt);
#pragma endregion

#pragma region Lights
	// Directional
	auto sunlight = mSceneMgr->createLight("sun");
	sunlight->setType(Ogre::Light::LT_DIRECTIONAL);
	sunlight->setDirection(Ogre::Vector3(0, -1, -1));
	sunlight->setDiffuseColour(Ogre::ColourValue(.30, .30, 0));
	sunlight->setSpecularColour(Ogre::ColourValue(.30, .30, 0));

	// Spotlight
	auto spotlight = mSceneMgr->createLight("spotlight");
	spotlight->setType(Ogre::Light::LT_SPOTLIGHT);
	
	spotlight->setSpotlightRange(
		Ogre::Degree(5.0f),  // inner angle
		Ogre::Degree(15.0f), // outer angle
		0.0f);               // falloff
	
	spotlight->setDiffuseColour(Ogre::ColourValue(1.0f, 0.0f, 0.0f));

	// Sphere to visualize the spotlights source
	auto sphereEnt = mSceneMgr->createEntity("sphere", "sphere.mesh");
	sphereEnt->setMaterialName("Examples/checker");
	auto sphereNode = mSceneMgr->getSceneNode("planeNode")->createChildSceneNode("spotlightNode");
	sphereNode->attachObject(sphereEnt);
	sphereNode->attachObject(spotlight);
	sphereNode->scale(0.02f, 0.02f, 0.02f);
	sphereNode->translate(0.0f, 15.0f, 0.0f);
	sphereNode->lookAt(Ogre::Vector3(0, 0, 0), Ogre::Node::TS_PARENT);
#pragma endregion

#pragma region Entities
	std::array<Ogre::Entity*, 6> entities;
	auto entParentNode = mSceneMgr->getSceneNode("planeNode")->createChildSceneNode("entParentNode");

	float angleOffset = 360.0f / 6.0f;
	float radius = 30.0f;

	for (int i = 0; i < entities.size(); ++i)
	{
		auto e = mSceneMgr->createEntity("Sinbad.mesh");
		entParentNode->createChildSceneNode(Ogre::Vector3(
			radius * Math::Cos(Math::DegreesToRadians(angleOffset * i)),  // x = r cos(t)
			6.75f,                                                        // y = height
			radius * Math::Sin(Math::DegreesToRadians(angleOffset * i)))) // z = r sin(t)
		->attachObject(e);
	}

	// Barrel
	auto barrel = mSceneMgr->createEntity("barrel.mesh");
	mSceneMgr->getSceneNode("planeNode")->createChildSceneNode("barrel", Ogre::Vector3(0, 2.5f, 0))->attachObject(barrel);
#pragma endregion

	// Skybox
	mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 5000, false);
}
コード例 #10
0
// -----------------------------------------------------------------------------------------
void CPepeEngineCamera::lookAt(const IPepeEngineRenderable& entity)
{
    lookAt(entity.getWorldPosition());
}
コード例 #11
0
ファイル: lab2-4.c プロジェクト: LordStraider/TSBK07
void init(void) {	
	/* two vertex buffer objects, used for uploading the*/

	unsigned int bunnyVertexBufferObjID;
	unsigned int bunnyIndexBufferObjID;
	unsigned int bunnyNormalBufferObjID;
	unsigned int bunnyTexCoordBufferObjID;

	/* Reference to shader program*/

	/* GL inits*/
	glClearColor(0.2,0.2,0.5,0);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_TRUE);
	glActiveTexture(GL_TEXTURE0);
	printError("GL inits");

	/* Load and compile shader*/
	program = loadShaders("lab2-1.vert", "lab2-1.frag");
	glUseProgram(program);
	printError("init shader");
	/* Upload geometry to the GPU:*/

	m = LoadModel("bunnyplus.obj");
	LoadTGATextureSimple("maskros512.tga", &myTex);

    glGenVertexArrays(1, &bunnyVertexArrayObjID);
    glGenBuffers(1, &bunnyVertexBufferObjID);
    glGenBuffers(1, &bunnyIndexBufferObjID);
    glGenBuffers(1, &bunnyNormalBufferObjID);
    glGenBuffers(1, &bunnyTexCoordBufferObjID);
    
    glBindVertexArray(bunnyVertexArrayObjID);
	
	glBindTexture(GL_TEXTURE_2D, myTex);
	glUniform1i(glGetUniformLocation(program, "texUnit"), 0); // Texture unit 0


    if (m->texCoordArray != NULL)
    {
	    glBindBuffer(GL_ARRAY_BUFFER, bunnyTexCoordBufferObjID);
	    glBufferData(GL_ARRAY_BUFFER, m->numVertices*2*sizeof(GLfloat), m->texCoordArray, GL_STATIC_DRAW);
	    glVertexAttribPointer(glGetAttribLocation(program, "inTexCoord"), 2, GL_FLOAT, GL_FALSE, 0, 0);
	    glEnableVertexAttribArray(glGetAttribLocation(program, "inTexCoord"));
	}

    // VBO for vertex data
    glBindBuffer(GL_ARRAY_BUFFER, bunnyVertexBufferObjID);
    glBufferData(GL_ARRAY_BUFFER, m->numVertices*3*sizeof(GLfloat), m->vertexArray, GL_STATIC_DRAW);
    glVertexAttribPointer(glGetAttribLocation(program, "inPosition"), 3, GL_FLOAT, GL_FALSE, 0, 0); 
    glEnableVertexAttribArray(glGetAttribLocation(program, "inPosition"));

    // VBO for normal data
    glBindBuffer(GL_ARRAY_BUFFER, bunnyNormalBufferObjID);
    glBufferData(GL_ARRAY_BUFFER, m->numVertices*3*sizeof(GLfloat), m->normalArray, GL_STATIC_DRAW);
    glVertexAttribPointer(glGetAttribLocation(program, "inNormal"), 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(glGetAttribLocation(program, "inNormal"));
    
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bunnyIndexBufferObjID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, m->numIndices*sizeof(GLuint), m->indexArray, GL_STATIC_DRAW);


 	/* End of upload of geometry*/
 	Point3D p,l;
 	SetVector(0.0, 4.0, 0.0, &p);
 	SetVector(0.0, 0.0, -3.0, &l);

	lookAt(&p, &l, 0.0, 1.0, 0.0, &cam);

	T(0, 0, -2, trans);
	Ry(0.0, rot);
    Mult(rot, trans, total);

	glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total);
	glUniformMatrix4fv(glGetUniformLocation(program, "camMatrix"), 1, GL_TRUE, cam);
	glUniformMatrix4fv(glGetUniformLocation(program, "projMatrix"), 1, GL_TRUE, projMatrix);


	printError("init arrays");
}
コード例 #12
0
// -----------------------------------------------------------------------------------------
void CPepeEngineCamera::lookAt(float x, float y, float z)
{
    lookAt(CPepeEngineVector3(x, y, z));
}
コード例 #13
0
void Camera::lookAt(const Vector3 &target)
{
    lookAt(m_eye, target, m_yAxis);
}
コード例 #14
0
void Camera::setBehavior(CameraBehavior newBehavior)
{
    // Switch to a new camera mode (i.e., behavior).
    // This method is complicated by the fact that it tries to save the current
    // behavior's state prior to making the switch to the new camera behavior.
    // Doing this allows seamless switching between camera behaviors.

    CameraBehavior prevBehavior = m_behavior;

    if (prevBehavior == newBehavior)
        return;

    m_behavior = newBehavior;

    switch (newBehavior)
    {
    case CAMERA_BEHAVIOR_FIRST_PERSON:
        switch (prevBehavior)
        {
        default:
            break;

        case CAMERA_BEHAVIOR_FLIGHT:
            m_eye.y = m_firstPersonYOffset;
            updateViewMatrix();
            break;

        case CAMERA_BEHAVIOR_SPECTATOR:
            m_eye.y = m_firstPersonYOffset;
            updateViewMatrix();
            break;

        case CAMERA_BEHAVIOR_ORBIT:
            m_eye.x = m_savedEye.x;
            m_eye.z = m_savedEye.z;
            m_eye.y = m_firstPersonYOffset;
            m_orientation = m_savedOrientation;
            m_accumPitchDegrees = m_savedAccumPitchDegrees;
            updateViewMatrix();
            break;
        }

        undoRoll();
        break;

    case CAMERA_BEHAVIOR_SPECTATOR:
        switch (prevBehavior)
        {
        default:
            break;

        case CAMERA_BEHAVIOR_FLIGHT:
            updateViewMatrix();
            break;

        case CAMERA_BEHAVIOR_ORBIT:
            m_eye = m_savedEye;
            m_orientation = m_savedOrientation;
            m_accumPitchDegrees = m_savedAccumPitchDegrees;
            updateViewMatrix();
            break;
        }

        undoRoll();
        break;
    
    case CAMERA_BEHAVIOR_FLIGHT:
        if (prevBehavior == CAMERA_BEHAVIOR_ORBIT)
        {
            m_eye = m_savedEye;
            m_orientation = m_savedOrientation;
            m_accumPitchDegrees = m_savedAccumPitchDegrees;
            updateViewMatrix();
        }
        else
        {
            m_savedEye = m_eye;
            updateViewMatrix();
        }
        break;
    
    case CAMERA_BEHAVIOR_ORBIT:
        if (prevBehavior == CAMERA_BEHAVIOR_FIRST_PERSON)
            m_firstPersonYOffset = m_eye.y;

        m_savedEye = m_eye;
        m_savedOrientation = m_orientation;
        m_savedAccumPitchDegrees = m_accumPitchDegrees;
        
        m_targetYAxis = m_yAxis;

        Vector3 newEye = m_eye + m_zAxis * m_orbitOffsetDistance;
        Vector3 newTarget = m_eye;
        
        lookAt(newEye, newTarget, m_targetYAxis);
        break;
    }
}
コード例 #15
0
void renderScene(void) {

	GLint loc;
	FrameCount++;
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	// load identity matrices
	loadIdentity(VIEW);
	loadIdentity(MODEL);

	float carX = car.getPosition().getX();
	float carZ = car.getPosition().getZ();

	Vector3 dir = car.getDirection() + car.getPosition();
	float dirX = dir.getX();
	float dirZ = dir.getZ();

	Vector3 cam = car.getPosition() - car.getDirection();

	float cX = cam.getX();
	float cZ = cam.getZ();

	//if (_current_camera == 2) lookAt(cX, 2, cZ, dirX, 1, dirZ, 0, 1, 0);

		if (_current_camera == 2) {
			if (clicking) {
				lookAt(carX, 3, carZ, carX + camX, 1, carZ + camZ, 0, 1, 0);
			}
			else {
				lookAt(cX, 2, cZ, dirX, 1, dirZ, 0, 1, 0);
			}
		}
		else lookAt(0, 10, 0.1, 0, 0, 0, 0, 1, 0);
	// use our shader
	glUseProgram(shader.getProgramIndex());

	//send the light position in eye coordinates
	//glUniform4fv(lPos_uniformId, 1, lightPos); //efeito capacete do mineiro, ou seja lighPos foi definido em eye coord 
	
	_spotLights[0]->setPosition(car.getPosition().getX() + (0.1f * car.getDirection().getX()),
		car.getPosition().getY() + 1.0f,
		car.getPosition().getZ()  + (0.1f * car.getDirection().getZ()),
		1.0f);
	_spotLights[1]->setPosition(car.getPosition().getX() + (0.1f * car.getDirection().getX()),
		car.getPosition().getY() + 1.0f,
		car.getPosition().getZ() + (0.1f * car.getDirection().getZ()),
		1.0f);
	//LIGHTS
	drawLights();

	//Associar os Texture Units aos Objects Texture
	//stone.tga loaded in TU0; checker.tga loaded in TU1;  lightwood.tga loaded in TU2

	//Indicar aos tres samplers do GLSL quais os Texture Units a serem usados
	glUniform1i(tex_loc1, 0);
	glUniform1i(tex_loc2, 1);
	
	for (int i = 0; i < 128; i++) {
		cheerioArray[i].draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
	}

	car.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);

	butter2.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
	butter1.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);

	glEnable(GL_STENCIL_TEST);

	// Draw floor
	glStencilFunc(GL_ALWAYS, 1, 0xFF); // Set any stencil to 1
	glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
	glStencilMask(0xFF); // Write to stencil buffer
	glDepthMask(GL_FALSE); // Don't write to depth buffer
	glClear(GL_STENCIL_BUFFER_BIT); // Clear stencil buffer (0 by default)

	table.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);

	// Draw cube reflection
	glStencilFunc(GL_EQUAL, 1, 0xFF); // Pass test if stencil value is 1
	glStencilMask(0x00); // Don't write anything to stencil buffer
	glDepthMask(GL_TRUE); // Write to depth buffer

	glUniform1i(darken_uniformId, true);
	butter1ref.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
	butter2ref.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
	glUniform1i(darken_uniformId, false);

	glDisable(GL_STENCIL_TEST);

	for (int i = 0; i < orangeArray.size(); i++) {
		if (!orangeArray[i].getDelayDraw()) {
			orangeArray[i].draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
		}
	}

	glUniform1i(texMode_uniformId, true);
	road.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
	glUniform1i(texMode_uniformId, false);

	drawBroccoli();

	glUniform1i(lightsOff_uniformId, true);
	glUniform1i(texMode_uniformId, true);
	sun.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
	glUniform1i(texMode_uniformId, false);
	glUniform1i(lightsOff_uniformId, false);
	

	if (fireworks) {
		glUniform1i(texMode_uniformId, true);
		glUniform1i(lightsOff_uniformId, true);
		particles.render(textureArray[5], mesh[11], vm_uniformId, pvm_uniformId, normal_uniformId, shader, car.getAngle() - 180);
		glUniform1i(texMode_uniformId, false);
		glUniform1i(lightsOff_uniformId, false);
	}

	cup.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);

	FLARE_DEF renderFlare;
	renderFlare.fScale = 1;
	renderFlare.fMaxSize = 1.0;
	renderFlare.nPieces = 4;
	renderFlare.element[0].texture = &textureArray[6];
	renderFlare.element[0].fDistance = 0;
	renderFlare.element[0].fSize = 1.0;
	renderFlare.element[0].argb = 0xff6060ff;

	renderFlare.element[1].texture = &textureArray[7];
	renderFlare.element[1].fDistance = 1.0;
	renderFlare.element[1].fSize = 1.0;
	renderFlare.element[1].argb = 0xff6060ff;

	renderFlare.element[2].texture = &textureArray[8];
	renderFlare.element[2].fDistance = 2.0;
	renderFlare.element[2].fSize = 1.0;
	renderFlare.element[2].argb = 0xff6060ff;

	renderFlare.element[3].texture = &textureArray[9];
	renderFlare.element[3].fDistance = 3.0;
	renderFlare.element[3].fSize = 1.0;
	renderFlare.element[3].argb = 0xff6060ff;

	float sunp[4] = { sun.getPosition().getX(), sun.getPosition().getY(), sun.getPosition().getZ(), 1.0f };
	float view[16];
	float projection[16];
	double viewd[16];
	double projd[16];
	double winx, winy, winz;
	int viewp[4];

	memcpy(view, mMatrix[VIEW], 16 * sizeof(float));
	memcpy(projection, mMatrix[PROJECTION], 16 * sizeof(float));

	for (int i = 0; i < 16; i++) {
		viewd[i] = (double)view[i];
		projd[i] = (double)projection[i];
	}
	glGetIntegerv(GL_VIEWPORT, viewp);
	gluProject(sunp[0], sunp[1], sunp[2], viewd, projd, viewp, &winx, &winy, &winz);
	float sun_pos_x = winx;
	float sun_pos_y = winy;
	if (sun_pos_y <= 400)
		sun_pos_y = -500;

	//HUD stuff
	float ratio = (1.0f * glutGet(GLUT_WINDOW_WIDTH)) / glutGet(GLUT_WINDOW_HEIGHT);
	pushMatrix(PROJECTION); // Save the current matrix
	loadIdentity(PROJECTION); // We initialize the projection matrix as identity
	_hudCamera->update(ratio);
	pushMatrix(VIEW); // Save the current matrix
	loadIdentity(VIEW); // Initialize the model matrix as identity

	glUniform1i(lightsOff_uniformId, true);
	glUniform1i(texMode_uniformId, true);
	if (70 < car.getAngle() && car.getAngle() < 230 && _current_camera == 2) {
		flare.render(&renderFlare, sun_pos_x, sun_pos_y, glutGet(GLUT_WINDOW_WIDTH) / 2, glutGet(GLUT_WINDOW_HEIGHT) / 2,
			shader, mesh[11], pvm_uniformId, vm_uniformId, normal_uniformId);
	}
	glUniform1i(texMode_uniformId, false);
	glUniform1i(lightsOff_uniformId, false);

	if (paused) {

		glDepthMask(GL_FALSE);

		glUniform1i(lightsOff_uniformId, true);
		glUniform1i(texMode_uniformId, true);
		if (remainingLives > 0) {
			pauseScreen.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
		}
		else {
			deathScreen.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
		}
		glUniform1i(lightsOff_uniformId, false);
		glUniform1i(texMode_uniformId, false);

		glDepthMask(GL_TRUE);
	}

	glUniform1i(lightsOff_uniformId, true);
	HUDbg.draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
	for (int i = 0; i < remainingLives; i++) {
		_lives.at(i)->draw(shader, pvm_uniformId, vm_uniformId, normal_uniformId);
	}
	glUniform1i(lightsOff_uniformId, false);

	popMatrix(VIEW); // Restore the previous matrix
	popMatrix(PROJECTION); // Restore the previous matrix

	glBindTexture(GL_TEXTURE_2D, 0);
	glutSwapBuffers();
}
コード例 #16
0
ファイル: camera.cpp プロジェクト: dextero/sandbox
 void Camera::rotate(const Vec3& axis, Radians angle)
 {
     Quat rot = glm::angleAxis(angle.value(), axis.normalized());
     lookAt(mEye, mEye + (rot * (mAt - mEye)), mUp);
 }
コード例 #17
0
ファイル: OpenGL.cpp プロジェクト: mjs513/cs4620-1
void lookAt(const Point &eye, const Vector &direction, const Vector &up)
{
    Point center = eye + direction;
    
    lookAt(eye,center,up);
}
コード例 #18
0
ファイル: camera.cpp プロジェクト: dextero/sandbox
 void Camera::rotateAround(Radians angle)
 {
     Quat rot = glm::angleAxis(angle.value(), mUpReal);
     lookAt(mAt + (rot * (mEye - mAt)), mAt, mUp);
 }
コード例 #19
0
ファイル: Camera.cpp プロジェクト: cozza13/hifi
void Camera::keepLookingAt(const glm::vec3& point) {
    lookAt(point);
    _isKeepLookingAt = true;
    _lookingAt = point;
}
コード例 #20
0
ファイル: Camera.cpp プロジェクト: bakarih/hifi
void Camera::setRotation(const glm::quat& rotation) {
    _rotation = rotation; 
    if (_isKeepLookingAt) {
        lookAt(_lookingAt);
    }
}
コード例 #21
0
ファイル: main.cpp プロジェクト: PONT-MAX/TSBK07
void init(void)
{
    
    printf("i1 \n");
    sfMakeRasterFont();
    
    sphere = LoadModelPlus("./OBJ/groundsphere.obj");
    
    camera = lookAt(0.0,2.0,-8.0,
                    0.0,0.0,0.0,
                    0.0,1.0,0.0);
    srand (time(NULL));
    
    skytot = T(0.0,0.0,0.0);
    lavatot = Mult(T(0,-1, 0), S(20, 0, 20));
    
    // GL inits
    glClearColor(0.2,0.2,0.5,0);
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
    printError("GL inits");
    
    projectionMatrix = frustum(-0.1, 0.1, -0.1, 0.1, 0.2, 100.0);
    
    printf("i2 \n");
    // Load and compile shader
    program = loadShaders("./Shader/terrain.vert", "./Shader/terrain.frag");
    skyprogram = loadShaders("./Shader/sky.vert", "./Shader/sky.frag");
    glUseProgram(program);
    printError("init shader");
    
    glUniformMatrix4fv(glGetUniformLocation(program, "projMatrix"), 1, GL_TRUE, projectionMatrix.m);
    glUniform1i(glGetUniformLocation(program, "tex"), 0); // Texture unit 0
    LoadTGATextureSimple("./TGA/lavaroad.tga", &tex1);
    LoadTGATextureSimple("./TGA/conc.tga", &tex2);
    

    printf("i3 \n");
    // Load terrain data
    InitTerrain();
    
    LoadTGATextureData("./TGA/fft-terrain.tga", &ttex);
    printError("init terrain");
    
    //Body
    LoadTGATextureSimple("./TGA/tex_01_lfy_weapon1out.tga", &tex_head);
    LoadTGATextureSimple("./TGA/red.tga", &tex_body);
    
    LegR = LoadModelPlus("./OBJ/LegR.obj");//Load Right Leg
    LegL = LoadModelPlus("./OBJ/LegL.obj");//Load Left Leg
    Body = LoadModelPlus("./OBJ/groundsphere.obj"); //Load Body & head
    ArmR = LoadModelPlus("./OBJ/armr.obj");//Load Right Arm
    ArmL = LoadModelPlus("./OBJ/arml.obj");//Load Right Arm
    printf("i4 \n");
    //boost & Obst
    LoadTGATextureSimple("./TGA/red.tga", &startex);
    LoadTGATextureSimple("./TGA/speed.tga", &speedtex);
    LoadTGATextureSimple("./TGA/imortal.tga", &imortaltex);
    //LoadTGATextureSimple("./TGA/spike.tga", &gatetex);
    LoadTGATextureSimple("./TGA/dirt.tga", &gatetex); //NY ANDREAS

    Star = LoadModelPlus("./OBJ/groundsphere.obj");//extra points
    SpeedObj = LoadModelPlus("./OBJ/groundsphere.obj");//speed
    Imortal = LoadModelPlus("./OBJ/groundsphere.obj");//speed

    //Gate = LoadModelPlus("./OBJ/spike.obj");//gate
    Gate = LoadModelPlus("./OBJ/gatecube.obj");//gate //NY ANDREREAS

    
    
    // Lava Ground
    Lava = LoadModelPlus("./OBJ/ground.obj");//load ground aka lava
    LoadTGATextureSimple("./TGA/lava.tga", &lavatex); //load the lava texture
    
    //Sky
    skybox = LoadModelPlus("./OBJ/cubeplus.obj");//Load skybox
    glUseProgram(skyprogram);
    glUniformMatrix4fv(glGetUniformLocation(skyprogram, "projMatrix"), 1, GL_TRUE, projectionMatrix.m);
    LoadTGATextureSimple("./TGA/skybox2.tga", &skytex); 	// Texture unit 1
    glUseProgram(program);
    
}
コード例 #22
0
ファイル: Camera.cpp プロジェクト: bakarih/hifi
void Camera::setHmdPosition(const glm::vec3& hmdPosition) {
    _hmdPosition = hmdPosition; 
    if (_isKeepLookingAt) {
        lookAt(_lookingAt);
    }
}
コード例 #23
0
  NxI32 CommandCallback(NxI32 token,NxI32 count,const char **arglist)
  {
  	NxI32 ret = 0;

    saveMenuState();

		switch ( token )
		{
      case MC_MEMORY_REPORT:
        break;

      case MC_FLOATING_POINT_RESOLUTION:
        if ( count == 2 )
        {
          MultiFloatType type = MFT_MEDIUM;
          if ( stricmp(arglist[1],"SMALL") == 0 )
            type = MFT_SMALL;
          else if ( stricmp(arglist[1],"MEDIUM") == 0 )
            type = MFT_MEDIUM;
          else if ( stricmp(arglist[1],"BIGFLOAT") == 0 )
            type = MFT_BIG;
          else if ( stricmp(arglist[1],"FIXED32") == 0 )
            type = MFT_FIXED32;
          tf_setFloatingPointResolution(gTfrac,type);
          gLog->Display("Setting Floating Point Resolution to: %s\r\n", arglist[1] );
        }
        break;
      case MC_SHOW_NORMALS:
        if ( count == 2 )
        {
          setShowNormals( getBool(arglist[1]) );
        }
        break;
      case MC_ENVIRONMENT_TEXTURE:
        if ( count == 2 )
        {
          const char *t = arglist[1];
          if ( gFileSystem ) t = gFileSystem->FileOpenString(t,true);
          gPd3d->setEnvironmentTexture(t);
        }
        break;
      case MC_ROTATION_SPEED:
        if ( count == 2 )
        {
          NxF32 rspeed = (NxF32)atof( arglist[1] );
          setRotationSpeed(rspeed);
        }
        break;
		  case MC_OPTIMIZE_MESH:
				if ( !mStartup )
				{
					tf_state(gTfrac,TS_OPTIMIZE_MESH);
				}
				break;
      case MC_FILTER_FRACTAL:
        if ( !mStartup )
        {
          tf_state(gTfrac,TS_FILTER_FRACTAL);
        }
        break;
      case MC_DEFAULT_MANDELBROT:
				if ( !mStartup )
				{
          BigFloat xleft;
          BigFloat xright;
          BigFloat ytop;
          xleft.FromDouble(-2.5);
          xright.FromDouble(0.75);
          ytop.FromDouble(-1.5);
          tf_setFractalCoordinates(gTfrac,xleft,xright,ytop);
          tf_action(gTfrac,FA_MOUSE_CENTER,false,1024/2,768/2);
				}
        break;
      case MC_CLAMP_LOW:
        if ( count == 2 && gTfrac )
        {
          NxF32 c = (NxF32) atof( arglist[1] );
          tf_state(gTfrac,TS_CLAMP_LOW,false,0,c);
        }
        break;
      case MC_CLAMP_HIGH:
        if ( count == 2 && gTfrac )
        {
          NxF32 c = (NxF32) atof( arglist[1] );
          tf_state(gTfrac,TS_CLAMP_HIGH,false,0,c);
        }
        break;
      case MC_CLAMP_SCALE:
        if ( count == 2 && gTfrac )
        {
          NxF32 c = (NxF32) atof( arglist[1] );
          tf_state(gTfrac,TS_CLAMP_SCALE,false,0,c);
        }
        break;
      case MC_WIREFRAME_OVERLAY:
        if ( count == 2 && gTfrac )
        {
          bool state = getBool(arglist[1]);
          tf_state(gTfrac,TS_WIREFAME_OVERLAY,state);
        }
        break;
      case MC_VIEW3D:
        if ( count == 2 )
        {
					gView3d = getBool(arglist[1]);
          if ( gView3d )
          {
            NxF32 eye[3];
            NxF32 look[3];
            look[0] = 0;
            look[1] = 0;
            look[2] = 0;
            eye[0] = 200;
            eye[1] = 250;
            eye[2] = 200;
            lookAt(eye,look);
          }
        }
        break;
      case MC_FRACTAL_COORDINATES:
        if ( count == 4 && gTfrac )
        {
          BigFloat xleft =  arglist[1];
          BigFloat xright = arglist[2];
          BigFloat ytop   = arglist[3];
          tf_setFractalCoordinates(gTfrac,xleft,xright,ytop);
        }
        break;
      case MC_COLOR_PALETTE:
        if ( count == 2 && gTfrac )
        {
          tf_setPal(gTfrac,arglist[1]);
        }
        break;
		  case MC_ITERATION_COUNT:
				if ( count == 2 && gTfrac )
				{
					NxU32 icount = (NxU32)atoi(arglist[1]);
					tf_state(gTfrac,TS_ITERATION_COUNT,false,icount);
				}
				break;
		  case MC_CLOCK_CYCLES:
				if ( count == 2 && gTfrac )
				{
					NxU32 icount = (NxU32)atoi(arglist[1]);
					tf_state(gTfrac,TS_CLOCK_CYCLES,false,icount);
				}
				break;
			case MC_USE_THREADING:
				if ( count == 2 && gTfrac )
				{
					bool state = getBool(arglist[1]);
  			  tf_state(gTfrac,TS_THREADING,state);
  			}
				break;

			case MC_SMOOTH_COLOR:
				if ( count == 2 && gTfrac )
				{
					NxI32 cscale  = atoi(arglist[1]);
					tf_state(gTfrac,TS_SMOOTH_COLOR,false,cscale);
				}
				break;

      case MC_PREVIEW_ONLY:
        if ( count == 2 && gTfrac )
        {
          bool state = getBool(arglist[1]);
          tf_state(gTfrac,TS_PREVIEW_ONLY,state);
        }
        break;
			case MC_RECTANGLE_SUBDIVISION:
        if ( count == 2 && gTfrac )
        {
          bool state = getBool(arglist[1]);
          tf_state(gTfrac,TS_RECTANGLE_SUBDIVISION,state);
        }
        break;
			case MC_PSLOOKAT:
				//            0      1      2      3       4      5       6
				// Usage: PsLookAt <eyex> <eyey> <eyez> <lookx> <looky> <lookz>
				if ( count == 7 )
				{
					NxF32 eye[3];
					NxF32 look[3];

					eye[0] = (NxF32) atof( arglist[1] );
					eye[1] = (NxF32) atof( arglist[2] );
					eye[2] = (NxF32) atof( arglist[3] );

					look[0] = (NxF32) atof(arglist[4] );
					look[1] = (NxF32) atof(arglist[5] );
					look[2] = (NxF32) atof(arglist[6] );

					lookAt(eye,look);

				}
				break;
			case MC_PSSCRIPT:
				{
					const char *fname = 0;
					if ( count >= 2 )
					{
						fname = arglist[1];
					}
#if TODO
  				SoftFileInterface *sfi = gSoftBodySystem->getSoftFileInterface();
  				if ( sfi )
  				{
  					fname = sfi->getLoadFileName(".psc", "Select a demo script to run.");
  				}
  				if ( fname )
  				{
  					CPARSER.Parse("Run \"%s\"",fname);
  				}
#endif
				}
				break;
		}


    return ret;
  }
コード例 #24
0
ファイル: Camera.cpp プロジェクト: bakarih/hifi
void Camera::setHmdRotation(const glm::quat& hmdRotation) {
    _hmdRotation = hmdRotation; 
    if (_isKeepLookingAt) {
        lookAt(_lookingAt);
    }
}
コード例 #25
0
ファイル: ofEasyCam.cpp プロジェクト: nanu-c/openFrameworks
//----------------------------------------
void ofEasyCam::setTarget(ofNode& targetNode){
	target = targetNode;
	lookAt(target);
}
コード例 #26
0
ファイル: Node.cpp プロジェクト: TheRyaz/c_reading
void Node::lookAt( const Node* other, const Vector3& up )
{
	lookAt( other->worldTransform().translation(), up );
}
コード例 #27
0
ファイル: Matrices.cpp プロジェクト: yhnchang/yup
Matrix4& Matrix4::lookAt(float tx, float ty, float tz)
{
    return lookAt(Vector3(tx, ty, tz));
}
コード例 #28
0
void ViewController::lookAt( float x, float y, float z )
{
  Ogre::Vector3 point( x, y, z );
  lookAt( point );
}
コード例 #29
0
Scene* Chapter10_5::createScene()
{
    //cocos2d::Rect visibleRect = Director::getInstance()->getOpenGLView()->getVisibleRect();
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    auto winSize = Director::getInstance()->getWinSize();
    
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // create a scene
    // 'scene' is an autorelease object
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    auto scene = Scene::create();
    
    // add title
    auto label = LabelTTF::create("camera test", "Arial", 24);
    label->setPosition(Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x,
                       Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height).y - 30);
    
    scene->addChild(label, -1);
    
    //add the menu item for back to main menu
    label = LabelTTF::create("MainMenu", "Arial", 24);
    
    auto menuItem = MenuItemLabel::create(label);
    menuItem->setCallback([&](cocos2d::Ref *sender) {
        Director::getInstance()->replaceScene(Chapter10::createScene());
    });
    auto menu = Menu::create(menuItem, nullptr);
    
    menu->setPosition( Vec2::ZERO );
    menuItem->setPosition( Vec2( Vec2(origin.x+visibleSize.width, origin.y+visibleSize.height/2).x - 80, Vec2(origin.x+visibleSize.width/2, origin.y).y + 25) );
    
    scene->addChild(menu, 1);
    
    auto layer3D=Layer::create();
    scene->addChild(layer3D,2);
    
    std::string fileName = "orc.c3b";
    
    auto sprite = Sprite3D::create(fileName);
    sprite->setScale(5.f);
    sprite->setRotation3D(Vec3(0,180,0));
    sprite->setPosition( Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).x,
                        Vec2(origin.x+visibleSize.width/2, origin.y+visibleSize.height/2).y );
    
    // play animation
    auto animation = Animation3D::create(fileName);
    if (animation)
    {
        auto animate = Animate3D::create(animation);
        animate->setSpeed(1);
        sprite->runAction(RepeatForever::create(animate));
    }
    
    //add to scene
    layer3D->addChild(sprite);
    
    // add camera
    auto camera=Camera::createPerspective(60, (GLfloat)winSize.width/winSize.height, 1, 1000);
    camera->setCameraFlag(CameraFlag::USER1);// set camera flag
    camera->setPosition3D(Vec3(0, 0, 230) + sprite->getPosition3D());
    camera->lookAt(sprite->getPosition3D(), Vec3(0,1,0));
    
    // create camera action
    auto action = MoveBy::create(3, Vec2(100, 0));
    auto action_back = action->reverse();
    auto action1 = MoveBy::create(3, Vec2(0, 100));
    auto action_back1 = action1->reverse();
    auto seq = Sequence::create( action, action_back, action1, action_back1, nullptr );
    
    // run camera action
    camera->runAction( RepeatForever::create(seq) );
    
    layer3D->addChild(camera);
    
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // set camera mask
    // when node's camera-mask & camer-flag result is true, the node is visible for this camera.
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    layer3D->setCameraMask(0x2);
    
    // return the scene
    return scene;
}
コード例 #30
0
ファイル: critterviewer.cpp プロジェクト: jstty/OlderProjects
void cCritterViewer::update(CPopView *pactiveview, Real dt)
{		
	cCritter::update(pactiveview, dt);
	setZClipPlanes((cRealBox3(pgame()->border())).outerBox(cSprite::MAXPRISMDZ)); 
		/* This call updates _znear and _zfar.  It explicity requires a
		cRealBox3 input, and we do cast of pgame()->border() BEFORE we compute
		the outer box. */
	if (_trackplayer && pgame()->visibleplayer() &&
		 !(plistener() && plistener()->GetRuntimeClass() == RUNTIME_CLASS(cListenerViewerRide)))
		/* The meaning of the visibleplayer() condition is that it doesn't make sense
		to track the player if it's not an onscreen player. The reason for the
		listener condition is that you don't want to stare at the player when
		riding it. */
/*  I should  explain that the goal here is to not bother turning when the player 
is  moving around in the middle of the veiw area, and only to turn when he's near
the edge, but to have the turning when he's near the edge be smoooth.
	The use of the 0.85 foveaproportion parameter means that you react before the player
gets right up to the edge.  The reactproportion factor in lookAtProportional and
moveToProportional is delicate and should probably be adjusted according to the
current player speed relative to the visible window.  The issue is that (a) if I make
reactproportion too small, like 0.01, then the viewer doesn't turn (or move) fast
enough to catch up with the player and keep it in view, but (b) if I make reactpropotion
too big, like 0.5, then the turning or moving is such an abrupt jump that the visual
effect is jerky.  The goal is to do turns that are just big enough to not look jerky,
but to have the turns be big enough so you aren't turning more often than you really
have to.  Another downside of a toosmall reactproportion, by the way, is that it can be
computationally expensive to react. 
	The way we finally solved this is to do a while loop to turn just
far enough, moving just a little at a time so as to not overshoot. */
	{
		if (isVisible(pgame()->pplayer()->position()))// Uses _foveaproportion
			_lastgoodplayeroffset = position() - pgame()->pplayer()->position();
			/*I'm not sure about constantly changing _lastgoodplayeroffset.  On the
			one hand, the offset I set in setViewpoint was a standard good one, so why
			not keep it.  On the other, if I want to move my viewpoint around then I
			do want to be able to get a new value here. It seems ok for now.*/
		else //not visible, so do somehting about it. 
		{
			int loopcount = 0; /* Never have a while loop without a loopcount
				to make sure you don't spin inside the while forever under some
				unexpected situation like at startup. */
			cVector lookat = pgame()->pplayer()->position();
			cVector viewerpos = lookat + _lastgoodplayeroffset;
			if (pgame()->worldShape() == cGame::SHAPE_XSCROLLER)
			{
				lookat = cVector(pgame()->pplayer()->position().x(),
					pgame()->border().midy(), pgame()->pplayer()->position().z());
				viewerpos = cVector(lookat.x(), position().y(), position().z()); 
			}
			if (pgame()->worldShape() == cGame::SHAPE_YSCROLLER)
			{
				lookat = cVector(pgame()->border().midx(),
					pgame()->pplayer()->position().y(), pgame()->pplayer()->position().z());
				viewerpos = cVector(position().x(), lookat.y(), position().z()); 
			} 
			if (_perspective)
				while (!isVisible(lookat) && loopcount < 100)// Uses _foveaproportion
				{
#ifdef TURNMYHEADTOTRACKPLAYER
					lookAtProportional(lookat, cCritterViewer::TURNPROPORTION);
#else //Don't TURNMYHEADTOTRACKPLAYER, instead move with the player.
					moveToProportional(viewerpos, cCritterViewer::TURNPROPORTION);
#endif //TURNMYHEADTOTRACKPLAYER
					loopcount++;
				}
			else //ortho case
				while( !isVisible(lookat) && loopcount < 100)// Uses _foveaproportion
				{
					moveToProportional(lookat +	10.0*pgame()->pplayer()->binormal(),
						cCritterViewer::TURNPROPORTION);
					loopcount++;
				}
		}
	}
//Possibly ride the player. 
	if (plistener()->IsKindOf(RUNTIME_CLASS(cListenerViewerRide)))
	{
		cCritter *pplayer = pgame()->pplayer();
		cVector offset = ((cListenerViewerRide*)plistener())->offset();
		moveTo(pplayer->position() + 
			offset.x()*pplayer->attitudeTangent() +
			offset.y()*pplayer->attitudeNormal() +
			offset.z()*pplayer->attitudeBinormal());
#ifdef COLLIDEVIEWER
		cRealBox skeleton = pplayer->moveBox();
		if (skeleton.zsize()<0.5)
			skeleton.setZRange(0.0, offset.z());
		if (skeleton.ysize()<0.5)
			skeleton.setYRange(0.0, offset.z());
		skeleton.clamp(_position);
		for (int i=0; i<pgame()->pbiota()->count(); i++)
		{
			cCritter* pother = pgame()->pbiota()->GetAt(i);
			if (pother->IsKindOf(RUNTIME_CLASS(cCritterWall)))
				pother->collide(this);
		}
		/* colliding with the wall may have twisted the viwer's orientation,
		so align it once again. */
#endif //COLLIDEVIEWER
		setAttitude(pplayer->attitude()); /* Before we call lookAt, 
			make sure your attitude matches the player.  For one thing,
			you may have gotten twisted around in the COLLIDEVIEWER code. */
		lookAt(pplayer->position() +
			cListenerViewerRide::PLAYERLOOKAHEAD * pplayer->radius() * 
			pplayer->attitudeTangent());
			 /* This has the effect that as offset gets large you change your
			looking direction see right in front of the player. The multiplier
			cCritterViewer::PLAYERLOOKAHEAD is tweaked to work well
			with the default cCritterViewer::OFFSET. */
	}
}