Example #1
0
void Hologram::on_key(Key key)
{
    switch (key) {
    case KEY_SHUTDOWN:
    case KEY_ESC:
        shell_->quit();
        break;
    case KEY_UP:
        camera_.eye_pos -= glm::vec3(0.05f);
        update_camera();
        break;
    case KEY_DOWN:
        camera_.eye_pos += glm::vec3(0.05f);
        update_camera();
        break;
    case KEY_SPACE:
        sim_paused_ = !sim_paused_;
        break;
    case KEY_F:
        sim_fade_ = !sim_fade_;
        break;
    default:
        break;
    }
}
Example #2
0
bool Background::init() {
    //We need to create an orthographic camera
    camera_id_ = manager_->window->new_camera();
    update_camera(Viewport()); //FIXME: Only fullscreen??

    //Create a stage to add to the render pipeline
    stage_id_ = manager_->window->new_stage(PARTITIONER_NULL);

    {
        auto stage = manager_->window->stage(stage_id_);

        actor_id_ = stage->new_actor();
        //Load the background material
        material_id_ = stage->assets->new_material_from_file(Material::BuiltIns::TEXTURE_ONLY);

        auto mesh = stage->assets->new_mesh_as_rectangle(1, 1, Vec2(0.5, 0.5));
        stage->actor(actor_id_)->set_mesh(mesh);
        stage->assets->mesh(mesh)->set_material_id(material_id_);
    }

    //Add a pass for this background
    pipeline_id_ = manager_->window->render(stage_id_, camera_id_).with_priority(
        smlt::RENDER_PRIORITY_BACKGROUND + manager_->background_count()
    );

    return true;
}
Example #3
0
	// *******************************************************	
	// display(): called once per frame, whenever OpenGL decides it's time to redraw.
	virtual void display( float animation_delta_time, Vector2d &window_steering )
	{		
		if( animate ) animation_time += animation_delta_time;

		update_camera( animation_delta_time , window_steering );

		int basis_id = 0;

		float atime = animation_time * 10;
		Matrix4d model_transform = Matrix4d::Identity();
		Matrix4d std_model = model_transform;

		*m_tree = Tree(Matrix4d::Identity(), atime);
		// Start coding here!!!! 
		m_bee->timepassby(atime);

		// Plane
		model_transform = std_model * Affine3d(Translation3d(5, -5, -60)).matrix();				// Position
		glUniform4fv(g_addrs->color_loc, 1, Vector4f(.0f, .7f, .9f, 1).data());			// Color
		m_plane->draw ( projection_transform, camera_transform, model_transform, "" );

		// Tree
		model_transform = std_model * Affine3d(Translation3d(4, -5, -40)).matrix();				// Position
		glUniform4fv( g_addrs->color_loc, 1, Vector4f( .0f, .6f ,.2f ,1 ).data());			// Color
		m_tree->draw( basis_id++, projection_transform, camera_transform, model_transform, "");

		// Leg
		model_transform = std_model * Affine3d(Translation3d(4, 1+2*(abs(20.0 - ((int)atime % 41)))/10, -40)).matrix();				// Position
		model_transform *= Affine3d(AngleAxisd((-PI / 60 * atime), Vector3d(0, 1, 0))).matrix();
		model_transform *= Affine3d(Translation3d(20, 0, 0)).matrix();
		m_bee->draw(basis_id++, projection_transform, camera_transform, model_transform, "");
	}
Example #4
0
        bool d3d_display::render() {
            // Update our time
            static float t = 0.0f;
            static float dt = 0.f;
            if (_driverType == D3D_DRIVER_TYPE_REFERENCE) {
                t += (float)XM_PI * 0.0125f;
            } else {
                static uint64_t dwTimeStart = 0;
                static uint64_t dwTimeLast = 0;
                uint64_t dwTimeCur = GetTickCount64();
                if (dwTimeStart == 0)
                    dwTimeStart = dwTimeCur;
                t = (dwTimeCur - dwTimeStart) / 1000.0f;
                dt = (dwTimeCur - dwTimeLast) / 1000.0f;
                dwTimeLast = dwTimeCur;
            }

            {
                std::lock_guard<std::mutex> _lock(_render_lock);
                
                _pImmediateContext->ClearRenderTargetView(_pRenderTargetView, Colors::MidnightBlue);
                _pImmediateContext->ClearDepthStencilView(_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);

                update_camera();
                step();

                _pSwapChain->Present(0, 0);
            }

            return true;
        }
Example #5
0
void Hologram::attach_swapchain() {
    const Shell::Context &ctx = shell_->context();

    prepare_viewport(ctx.extent);
    prepare_framebuffers(ctx.swapchain);

    update_camera();
}
Example #6
0
/**
 * Update loop
 */
void update_callback()
{
    input_update(); /* updates input system */
    update_light();
    update_camera(); /* update camera after input is refreshed */
    eng_update();   /* updates engine and renders the frame */
    app_window_swapbuffers();
}
Example #7
0
void turn_right()
{
   rotation_angle += ROTATION_SPEED;

   float angle_in_rads = rotation_angle * (PI / 180);
   centerX = (MOVEMENT_SPEED * cos(angle_in_rads)) + eyeX;
   centerZ = (MOVEMENT_SPEED * sin(angle_in_rads)) + eyeZ;

   update_camera();
}
Example #8
0
void move_forward()
{
   eyeX = centerX;
   eyeZ = centerZ;

   float angle_in_rads = rotation_angle * (PI / 180);
   centerX = (MOVEMENT_SPEED * cos(angle_in_rads)) + eyeX;
   centerZ = (MOVEMENT_SPEED * sin(angle_in_rads)) + eyeZ;

   update_camera();
}
Example #9
0
void move_backward()
{
   centerX = eyeX;
   centerZ = eyeZ;

   float angle_in_rads = (rotation_angle + 180) * (PI / 180);
   eyeX = (MOVEMENT_SPEED * cos(angle_in_rads)) + eyeX;
   eyeZ = (MOVEMENT_SPEED * sin(angle_in_rads)) + eyeZ;

   update_camera();
}
void GameScene::update(float dt)
{
    for (Entity* d : decorations_)
    {
        d->update(dt);
    }

    for (Entity* p : platforms_)
    {
        p->update(dt);
    }

    for (Entity* g : goalflags_)
    {
        g->update(dt);
    }

    update_effects(dt);

    for (Entity* c : collectibles_)
    {
        c->update(dt);

        sf::FloatRect bbox(c->collision_area());
        if (!c->animation().hidden() &&
            bbox.Intersects(player_.collision_area()))
        {
            explode(c,true);
            collectsnd_.Play();
        }
    }

    update_player(dt);

    bool out_of_bounds = true;
    for (Entity* p : platforms_)
    {
        if (vector_magnitude(
            p->position() - player_.position())
            < 1000)
        {
            out_of_bounds = false;
        }
    }

    if (out_of_bounds)
    {
        init_world();
    }

    update_camera(dt);
}
void Smoke::on_key(Key key)
{
    switch (key) {
    case KEY_SHUTDOWN:
    case KEY_ESC:
        quit();
        break;
    case KEY_UP:
        camera_.eye_pos -= glm::vec3(0.05f);
        update_camera();
        break;
    case KEY_DOWN:
        camera_.eye_pos += glm::vec3(0.05f);
        update_camera();
        break;
    case KEY_SPACE:
        sim_paused_ = !sim_paused_;
        break;
    default:
        break;
    }
}
Example #12
0
void EngineView::update() {
	if(ImGui::IsWindowHovered()) {
		if(ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1) || ImGui::IsMouseClicked(2)) {
			ImGui::SetWindowFocus();
			update_picking();
		}
	}

	if(ImGui::IsWindowFocused()) {
		context()->scene().set_scene_view(&_scene_view);
	}

	// process inputs
	update_camera();
}
void GameScene::init()
{
    init_world();

    bgm_.OpenFromFile("sound/gamebgm.wav");
    collectsndbuf_.LoadFromFile("sound/collect.wav");
    collectsnd_.SetBuffer(collectsndbuf_);

    bgm_.Play();

    camera_position_ = rect_center(player_.bounding_box());
    camera_target_ = camera_position_;
    camera_zoom_ = sf::Vector2f(0.5f,0.5f);
    camera_zoom_target_ = camera_zoom_;
    camera_zoom_lerp_ratio_ = 0.7;
    camera_pan_lerp_ratio_ = 0.9f;
    update_camera(1);
}
Example #14
0
void run()
{
    renderer.running = true;
    while (renderer.running) {
        Profiler::start_timer("-> Frame time");

        handle_input();

        update_camera();

        animate_models();

        culling();

        renderer.render(camera);

        Profiler::start_timer("Swap");
        SDL_GL_SwapWindow(main_window);
        Profiler::stop_timer("Swap");
        Profiler::stop_timer("-> Frame time");
    }
}
Example #15
0
bool Background::init() {
    //Create a stage to add to the render pipeline
    stage_id_ = window().new_stage(PARTITIONER_NULL);

    //We need to create an orthographic camera
    camera_id_ = window().new_camera();
    update_camera(Viewport()); //FIXME: Only fullscreen??

    //Add a pass for this background
    pipeline_id_ = window().render(stage_id_, camera_id_).with_priority(kglt::RENDER_PRIORITY_BACKGROUND);
    actor_id_ = window().stage(stage_id_)->new_actor();
    //Load the background material
    material_id_ = window().stage(stage_id_)->new_material_from_file("kglt/materials/background.kglm");

    auto mesh = window().stage(stage_id_)->new_mesh_as_rectangle(1, 1, Vec2(0.5, 0.5));
    window().stage(stage_id_)->actor(actor_id_)->set_mesh(mesh);
    window().stage(stage_id_)->mesh(mesh)->set_material_id(material_id_);

    window().stage(stage_id_)->material(material_id_)->pass(0).set_blending(BLEND_ALPHA);
    window().stage(stage_id_)->material(material_id_)->pass(0).set_depth_test_enabled(false);
    window().stage(stage_id_)->material(material_id_)->pass(0).set_depth_write_enabled(false);
    return true;
}
Example #16
0
  //=========================================================//
  //=========================================================//
static void display(void)
{
	update_camera();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_LIGHTING);

	// position the light
	GLfloat pos[4] = { 5.0, 5.0, 5.0, 0.0 };
	glLightfv(GL_LIGHT0, GL_POSITION, pos);

	// rotation is used for animation
	static GLfloat rotation = 0.0;
	// it's increased by one every frame
	rotation += 0.1*horseSpeed;
	// and ranges between 0 and 360
	if (rotation > 360.0)
		rotation = 0.0;


	//glDisable(GL_LIGHTING);
	glColor3d(0.1, 0.1, 0.4);

	output(5, -6, "Mignon Kramp / A385 Computer Graphics");
	output(4.5, -6, "- LR move leftright");
	output(4, -6, "- look up or down: A / Z");
	output(3.5, -6, "- look right/left: arrows ->/<-");
	output(3, -6, "- walk forward/backward: arrows UP/Down");
	output(2.5, -6, "XYZ " + std::to_string(horse.angle));

	DrawGround();
	DrawLinesXYZ();
	UpdateHorse();

	glutSwapBuffers();
}
Example #17
0
File: main.c Project: Df458/Halberd
int main(int argc, char** argv)
{
    if(!glfwInit()) {
        error("Failed to intialize GLFW.");
        return 1;
    }

    GLFWwindow* win;
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    win = glfwCreateWindow(800, 600, "Halberd", NULL, NULL);
    if(!win) {
        error("Unable to create window.");
        return 1;
    }
    glfwSetFramebufferSizeCallback(win, sizeCallback);
    glfwMakeContextCurrent(win);

	glewExperimental = 1;
	if(glewInit() != GLEW_OK) {
        error("glewInit() failed.");
        glfwDestroyWindow(win);
        return 1;
    }
    glGetError(); // Because GLEW is silly. <http://stackoverflow.com/questions/20034615/why-does-glewinit-result-in-gl-invalid-enum-after-making-some-calls-to-glfwwin>
    GLuint VAO; // FIXME: Stupid Hack. <http://stackoverflow.com/questions/13403807/glvertexattribpointer-raising-gl-invalid-operation>
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    init_graphics();
    update_camera(800, 600);
    init_input(win);
    init_player(0, 0);
    init_ui();
    init_settings();

    /*init_maps();*/
    // TODO: Figure out the correct way to start up
    /*get_tileset_id("Plains.png");*/
    /*load_maps("test");*/

    float delta = 0;
    glfwSetTime(0);
    do {
        delta = glfwGetTime();
        glfwSetTime(0);
        glfwPollEvents();

        if(!ui_present())
            update_player(delta);
        update_actors(delta);
        update_ui(delta);
        update_input_states(delta);

        render_game();

        glfwSwapBuffers(win);
    } while(!glfwWindowShouldClose(win) && get_input_state(4) != 2);

    destroy_player_actor();
    destroy_actors();
    /*destroy_maps();*/
    destroy_ui();
    destroy_graphics();
    cleanup_settings();

    glfwDestroyWindow(win);
    glfwTerminate();
    return 0;
}
Example #18
0
File: main.c Project: Df458/Halberd
void sizeCallback(GLFWwindow* win, int width, int height)
{
    glViewport(0, 0, width, height);
    update_camera(width, height);
}
Example #19
0
void update_ShowScene(void){
  if(update_playmovie==1){
    enable_disable_playmovie();
    update_playmovie = 0;
  }
  update_render_start_button();
  if(update_makemovie == 1)MakeMovie();
  if(compute_fed == 1)DefineAllFEDs();
  if(restart_time == 1){
    restart_time = 0;
    reset_itimes0();
  }
  if(loadfiles_at_startup==1&&update_load_Files == 1){
    load_Files();
  }
  if(update_startup_view == 1){
    camera *ca;

    ca = get_camera(label_startup_view);
    if(ca != NULL){
      ResetMenu(ca->view_id);
    }
    update_rotation_center = 0;
    update_rotation_center_ini = 0;
    update_startup_view = 0;
  }
  if(menusmooth == 1 && smoothing_blocks == 0 && updatesmoothblocks == 1){
    smooth_blockages();
  }
  if(update_tourlist == 1){
    Update_Tourlist();
  }
  if(update_gslice == 1){
    update_gslice_parms();
  }
#define MESH_LIST 4
  if(update_rotation_center == 1){
    camera_current->rotation_index = glui_rotation_index;
    Motion_CB(MESH_LIST);
    update_rotation_center = 0;
  }
  if(update_rotation_center_ini == 1){
    camera_current->rotation_index = glui_rotation_index_ini;
    Motion_CB(MESH_LIST);
    update_rotation_center_ini = 0;
  }
  if(camera_current->dirty == 1){
    update_camera(camera_current);
  }
  if(updateclipvals == 1){
    clip2cam(camera_current);
    update_clip_all();
    updateclipvals = 0;
  }
  if(update_selectedtour_index == 1){
    update_tourindex();
  }
  if(trainer_mode == 1 && fontindex != LARGE_FONT)FontMenu(LARGE_FONT);
  if(updateindexcolors == 1){
    UpdateIndexColors();
  }
  if(force_isometric == 1){
    force_isometric = 0;
    projection_type = 1;
    camera_current->projection_type = projection_type;
    ZoomMenu(UPDATE_PROJECTION);
  }
  if(convert_ini == 1){
    writeini(SCRIPT_INI, ini_to);
    exit(0);
  }
  Update_Show();
  if(global_times!=NULL&&updateUpdateFrameRateMenu==1)FrameRateMenu(frameratevalue);
  if(updatefaces==1)UpdateFaces();
  if(updatefacelists==1)UpdateFacelists();
}
Example #20
0
Game::Game(const std::string &level, float near, float far, float fov) :
    camera(fov, resolution.x/(float)resolution.y, near, far)
    , music(nullptr)
    , current_mode(MODE_READY)
{
    composition = new RenderTarget(resolution, GL_RGB8, RenderTarget::DEPTH_BUFFER | RenderTarget::DOUBLE_BUFFER);
    geometry = new RenderTarget(resolution, GL_RGB8, RenderTarget::DEPTH_BUFFER);

    printf("Loading level %s\n", level.c_str());

    std::string base_dir = PATH_BASE "data/levels/" + level;

    Config config = Config::parse(base_dir + "/level.cfg");

    //Read config:
    start_position = config["/player/start_position"]->as_float();
    sky_color = config["/environment/sky_color"]->as_color();
    static const glm::vec2 terrain_scale = config["/environment/terrain/scale"]->as_vec2();
    static const float fog_intensity = config["/environment/fog_intensity"]->as_float();
    camera_offset = config["/player/camera/offset"]->as_vec3();
    look_at_offset = config["/player/camera/look_at_offset"]->as_float();
    movement_speed = config["/player/speed/normal"]->as_float();
    brake_movement_speed = config["/player/speed/brake"]->as_float();

    spawn_area_start = config["/game/spawn_area/start"]->as_float();
    spawn_area_end = config["/game/spawn_area/end"]->as_float();
    spawn_area_size = spawn_area_end - spawn_area_start;
    spawn_distance = config["/game/spawn_area/distance"]->as_float();
    despawn_distance = config["/game/spawn_area/despawn_distance"]->as_float();
    difficulty_increase = config["/game/difficulty_increase"]->as_float();

    static const Shader::fog_t fog = { glm::vec4(sky_color.to_vec3(), 1.f), fog_intensity };
    Shader::upload_fog(fog);

    TextureArray * colors = TextureArray::from_filename( (base_dir +"/color0.png").c_str(),
                            (base_dir + "/color1.png").c_str(), nullptr);
    TextureArray *  normals = TextureArray::from_filename( (base_dir +"/normal0.png").c_str(),
                              (base_dir + "/normal1.png").c_str(), nullptr);

    terrain = new Terrain(base_dir + "/map.png", terrain_scale.x, terrain_scale.y, colors, normals);

    Data * path_file = Data::open(base_dir + "/path.svg");

    SVGPath * svg_path = svgParse((char*) path_file->data());

    delete path_file;

    std::vector<glm::vec3> path_nodes;

    for(int i=0; i< svg_path->npts; ++i) {
        path_nodes.push_back(glm::vec3(
                                 svg_path->pts[i*2],
                                 0,
                                 svg_path->pts[i*2 + 1]
                             ) * terrain_scale.x);
    }

    svgDelete(svg_path);

    Path::optimize_vector(path_nodes);

    // Gets max elevation for a radius around a point to avoid the rails cliping into the ground.
    for(glm::vec3 &v : path_nodes) {
        v.y = glm::max(glm::max(glm::max(terrain->height_at(v.x+1.5f, v.z),terrain->height_at(v.x-1.5f, v.z)),terrain->height_at(v.x, v.z+1.5f)),terrain->height_at(v.x, v.z-1.5f)) + 0.2f;
    }

    path = new Path(path_nodes, false);

    rails = new Rails(path, 1.f);
    rail_texture = Texture2D::from_filename(PATH_BASE "data/textures/rails.png");
    rail_material.texture = rail_texture;

    //Setup player:
    player.canon_offset = config["/player/canon_offset"]->as_vec3();
    player.canon_length = config["/player/canon_length"]->as_float();
    //Configure lights:

    lights.ambient_intensity() = config["/environment/light/ambient"]->as_vec3();
    lights.num_lights() = 1;

    lights.lights[0]->intensity = config["/environment/light/sunlight"]->as_vec3();
    lights.lights[0]->type = MovableLight::DIRECTIONAL_LIGHT;

    //Load enemies:
    EnemyTemplate::init(Config::parse(base_dir + "/enemies.cfg"), this);

//Set up camera:

    update_camera();

//Create particle systems:

    wind_velocity = config["/environment/wind_velocity"]->as_vec3();
    gravity = glm::vec4(config["/environment/gravity"]->as_vec3(), 1.f);

    particle_shader = Shader::create_shader("particles");
    passthru = Shader::create_shader("passthru");

    static const Config particle_config = Config::parse(base_dir + "/particles.cfg");

    static const float canon_inner_radius = particle_config["/particles/spawn_radius"]->as_float();

    particle_textures = TextureArray::from_filename( PATH_BASE "data/textures/smoke.png",
                        PATH_BASE "data/textures/fog.png",
                        PATH_BASE "data/textures/particle.png",
                        PATH_BASE "data/textures/fire1.png",
                        PATH_BASE "data/textures/fire2.png",
                        PATH_BASE "data/textures/fire3.png",
                        nullptr);

    static const int max_attack_particles = particle_config["/particles/max_attack_particles"]->as_int();
    static const int max_smoke_particles = particle_config["/particles/max_smoke_particles"]->as_int();
    static const int max_dust_particles = particle_config["/particles/max_dust_particles"]->as_int();
    static const int max_explosion_particles = particle_config["/particles/max_explosion_particles"]->as_int();

    attack_particles = new HittingParticles(max_attack_particles, particle_textures, EnemyTemplate::max_num_enemies, false);
    attack_particles->config.gravity = gravity;
    system_configs.push_back(&(attack_particles->config));
    attack_particles->config.spawn_area = glm::vec4(0.f, 0.f, 0.f, canon_inner_radius);

    for(auto &p : particle_types) {
        p.config = attack_particles->config; //Get reasonable defaults
        system_configs.push_back(&(p.config));
    }

    read_particle_config(particle_config["/particles/light"], particle_types[LIGHT_PARTICLES].config);
    particle_types[LIGHT_PARTICLES].count = particle_config["/particles/light/count"]->as_int();
    particle_types[LIGHT_PARTICLES].spawn_speed = particle_config["/particles/light/spawn_speed"]->as_float();
    particle_types[LIGHT_PARTICLES].damage = particle_config["/particles/light/damage"]->as_float();

    read_particle_config(particle_config["/particles/medium"], particle_types[MEDIUM_PARTICLES].config);
    particle_types[MEDIUM_PARTICLES].count = particle_config["/particles/medium/count"]->as_int();
    particle_types[MEDIUM_PARTICLES].spawn_speed = particle_config["/particles/medium/spawn_speed"]->as_float();
    particle_types[MEDIUM_PARTICLES].damage = particle_config["/particles/medium/damage"]->as_float();

    read_particle_config(particle_config["/particles/heavy"], particle_types[HEAVY_PARTICLES].config);
    particle_types[HEAVY_PARTICLES].count = particle_config["/particles/heavy/count"]->as_int();
    particle_types[HEAVY_PARTICLES].spawn_speed = particle_config["/particles/heavy/spawn_speed"]->as_float();
    particle_types[HEAVY_PARTICLES].damage = particle_config["/particles/heavy/damage"]->as_float();

    //Smoke:
    smoke = new ParticleSystem(max_smoke_particles, particle_textures, false);
    smoke->config.gravity = gravity;
    system_configs.push_back(&(smoke->config));
    smoke->config.spawn_area = glm::vec4(0.f, 0.f, 0.f, canon_inner_radius * 2.0);

    read_particle_config(particle_config["/particles/smoke"], smoke->config);
    smoke_count = particle_config["/particles/smoke/count"]->as_int();
    smoke_spawn_speed = particle_config["/particles/smoke/spawn_speed"]->as_float();

    //Dust:
    dust = new ParticleSystem(max_dust_particles, particle_textures, true);

    read_particle_config(particle_config["/particles/dust"], dust->config);

    dust->config.gravity = gravity;
    system_configs.push_back(&(dust->config));
    dust->config.spawn_area = particle_config["/particles/dust/spawn_area"]->as_vec4();
    dust->config.avg_spawn_velocity = glm::vec4(particle_config["/particles/dust/avg_spawn_velocity"]->as_vec3(), 0);
    dust->avg_spawn_rate = particle_config["/particles/dust/avg_spawn_rate"]->as_float();
    dust->spawn_rate_var = particle_config["/particles/dust/spawn_rate_var"]->as_float();
    dust_spawn_ahead = particle_config["/particles/dust/spawn_ahead"]->as_float();
    half_dust_spawn_area = glm::vec3(dust->config.spawn_area.x, dust->config.spawn_area.y, dust->config.spawn_area.z) / 2.f;

    dust->config.spawn_position = glm::vec4(player.position() - half_dust_spawn_area, 1.f);
    dust->update_config();
    dust->spawn(dust->avg_spawn_rate * 5.0);
    dust->config.spawn_position += glm::vec4(path->at(player.path_position() + dust_spawn_ahead / 2.f), 0.f);
    dust->spawn(dust->avg_spawn_rate * 5.0);

    //Explosions
    explosions = new ParticleSystem(max_explosion_particles, particle_textures, false);

    hit_explosion = explosions->config;
    system_configs.push_back(&(hit_explosion));
    kill_explosion = explosions->config;
    system_configs.push_back(&(kill_explosion));
    read_particle_config(particle_config["/particles/hit_explosion"], hit_explosion);
    read_particle_config(particle_config["/particles/kill_explosion"], kill_explosion);

    explosions->config.gravity = gravity;
    system_configs.push_back(&(explosions->config));
    hit_explosion_count = particle_config["/particles/hit_explosion/count"]->as_int();
    kill_explosion_count = particle_config["/particles/kill_explosion/count"]->as_int();
    kill_explosion.spawn_area = particle_config["/particles/kill_explosion/spawn_area"]->as_vec4();
    kill_explosion.avg_spawn_velocity = glm::vec4(particle_config["/particles/kill_explosion/avg_spawn_velocity"]->as_vec3(), 0);
    hit_explosion.spawn_area = particle_config["/particles/hit_explosion/spawn_area"]->as_vec4();
    hit_explosion.avg_spawn_velocity = glm::vec4(particle_config["/particles/hit_explosion/avg_spawn_velocity"]->as_vec3(), 0);

    update_wind_velocity();
    //Setup HUD




    hud_scale = glm::vec2(resolution.x / 800.f, resolution.y / 600.f);
    hud_static_elements_tex = Texture2D::from_filename(PATH_BASE "/data/textures/hudStatic.png");
    fullscreen_quad = new Quad();
    fullscreen_quad->set_scale(glm::vec3(resolution.x,resolution.y,0));

    hud_lightpos =  glm::vec2(594,490) * hud_scale;
    hud_mediumpos = glm::vec2(644,490) * hud_scale;
    hud_heavypos =  glm::vec2(700,490) * hud_scale;

    hud_choice_tex = Texture2D::from_filename(PATH_BASE "/data/textures/weap_select.png");
    hud_choice_quad = new Quad();
    hud_choice_quad->set_scale(glm::vec3(97,92,0) * glm::vec3(hud_scale , 0));

    hud_break_tex = Texture2D::from_filename(PATH_BASE "/data/textures/breaks_ready.png");
    hud_break_quad = new Quad();
    hud_break_quad->set_scale(glm::vec3(190, 25, 0) * glm::vec3(hud_scale, 0));
    hud_break_quad->set_position(glm::vec3(glm::vec2(30, 530) * hud_scale, 0.f));

    life_text.set_color(hud_font_color);
    life_text.set_scale(20.0 * hud_scale.x);
    life_text.set_position(glm::vec3(glm::vec2(26.f, 44.5f) * hud_scale, 0.f));

    //Highscore stuff:
    highscore = new Highscore(base_dir + "/highscore", NUM_HIGHSCORE_ENTRIES);
    float hs_scale = 40.f;
    glm::vec2 higscore_base = glm::vec2(735.f, 85.f);
    int i=0;
    for(Text &t : highscore_entries) {
        t.set_position(glm::vec3( (higscore_base + glm::vec2(0.f, (i++)*hs_scale)) * hud_scale, 0.f));
        t.set_scale(hs_scale);
        t.set_text("");
        t.set_alignment(Text::RIGHT_ALIGNED);
    }

    //Textures
    game_over_texture = Texture2D::from_filename(PATH_BASE "/data/textures/gameover.png");
    startscreen_texture = Texture2D::from_filename(PATH_BASE "/data/textures/start_screen.png");
}
Example #21
0
int					main_loop(t_data *data)
{
	SDL_Event	event;
	int			quit = 0;
	t_elem		*elem;
	t_elem		*new_elem;

	while (!quit)
	{
		while (SDL_PollEvent(&event))
		{
			if (event.type == SDL_QUIT)
				quit = 1;
			if (event.type == SDL_KEYDOWN)
			{
				if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE)
					quit = 1;
				if (event.key.keysym.scancode == SDL_SCANCODE_UP)
					data->camera.y -= data->camera.speed;
				if (event.key.keysym.scancode == SDL_SCANCODE_DOWN)
					data->camera.y += data->camera.speed;
				if (event.key.keysym.scancode == SDL_SCANCODE_RIGHT)
					data->camera.x += data->camera.speed;
				if (event.key.keysym.scancode == SDL_SCANCODE_LEFT)
					data->camera.x -= data->camera.speed;
				if (event.key.keysym.scancode == SDL_SCANCODE_LSHIFT)
					data->shift = 1;
				if (event.key.keysym.scancode == SDL_SCANCODE_LCTRL)
					data->ctrl = 1;
			}
			if (event.type == SDL_KEYUP)
			{
				if (event.key.keysym.scancode == SDL_SCANCODE_LSHIFT)
					data->shift = 0;
				if (event.key.keysym.scancode == SDL_SCANCODE_LCTRL)
					data->ctrl = 0;
			}
			if (event.type == SDL_MOUSEMOTION)
			{
				data->mouse_x = event.motion.x;
				data->mouse_y = event.motion.y;
			}
			if (event.type == SDL_MOUSEBUTTONDOWN)
			{
				if (event.button.button == SDL_BUTTON_LEFT)
				{
					if (!data->shift && !list_clear(data->selected))
						return (0);
					elem = data->wizards->head;
					while (elem)
					{
						if (mouse_in_hitcl(data->mouse_x + data->camera.x, data->mouse_y + data->camera.y, &elem->wizard->hitcl))
						{
							if (!(new_elem = create_elem(TYPE_NONE)))
								return (0);
							new_elem->wizard = elem->wizard;
							if (!(data->selected = list_push_back(data->selected, new_elem)))
								return (0);
						}
						elem = elem->next;
					}
					data->selection.status = 1;
					data->selection.sx = data->mouse_x + data->camera.x;
					data->selection.sy = data->mouse_y + data->camera.y;
					data->selection.cx = data->selection.sx;
					data->selection.cy = data->selection.sy;
				}
				if (event.button.button == SDL_BUTTON_RIGHT)
				{
					if (data->selected->size > 0)
					{
						if (!new_wizard_formation(data->selected, data->mouse_x + data->camera.x, data->mouse_y + data->camera.y))
							return (0);
					}
/*					elem = data->selected->head;
					while (elem)
					{
						elem->wizard->vdest.x = data->mouse_x + data->camera.x;
						elem->wizard->vdest.y = data->mouse_y + data->camera.y;
						elem->wizard->move = 1;
						if (!set_new_wizard_angle(elem->wizard, elem->wizard->vdest.x, elem->wizard->vdest.y))
							return (0);
						elem = elem->next;
					}*/
				}
			}
			if (event.type == SDL_MOUSEBUTTONUP)
			{
				if (event.button.button == SDL_BUTTON_LEFT)
				{
					data->selection.status = 0;
					if (!select_in_box(data, &data->selection))
						return (0);
				}
			}
		}

		if (!update_camera(data))
			return (0);
		update_selection_box(data, &data->selection);
		elem = data->wizards->head;
		while (elem)
		{
			if (!update_wizard(elem->wizard))
				return (0);
			update_wizard_collision(data->wizards, elem->wizard);
			elem = elem->next;
		}

		render(data);

		SDL_GL_SwapWindow(data->window);
		SDL_Delay(1000 / 60);
	}
	return (1);
}
Example #22
0
void size_callback(int width, int height)
{
    glViewport(0, 0, width, height);
    update_camera(width, height);
}
Example #23
0
void Game::update(float dt) {

    switch(current_mode) {
    case MODE_READY:
        fade_music(dt);
        if(start_pressed()) {
            current_mode = MODE_GAME;
            initialize();
        }
        break;
    case MODE_GAME:
    {
        if(life <= 0) {

            // Delete all enemies.
            for(auto it = enemies.begin(); it != enemies.end(); ) {
                delete *it;
                it = enemies.erase(it);
            }

            //delete music;
            current_mode = MODE_HIGHSCORE;

            highscore->add_entry(score);

            score_text.set_alignment(Text::RIGHT_ALIGNED);
            score_text.set_number(score);
            score_text.set_color(highscore_color);
            score_text.set_scale(30.0 * hud_scale.x);
            score_text.set_position(glm::vec3(glm::vec2(150.f, 270.f) * hud_scale, 0.f));

            int i = 0;
            bool selected = false;
            for(int e : highscore->get_entries()) {
                if(e > 0) {
                    if(!selected && e == score) {
                        highscore_entries[i].set_color(hud_font_color);
                    } else {
                        highscore_entries[i].set_color(highscore_color);
                    }
                    highscore_entries[i].set_number(e);
                } else {
                    highscore_entries[i].set_text("");
                }
                ++i;
            }
#ifdef WIN32
            if(useWII) WII->setRumble(false);
#endif

            return;
        }

        // Change wind direction
        wind_velocity = glm::rotateY(wind_velocity, (float)(0.8f + sin(global_time)));
        update_wind_velocity();

        //input.update_object(camera, dt);

        bool buttonFirePressed = (input.has_changed(Input::ACTION_0, 0.2f) && input.current_value(Input::ACTION_0) > 0.9f);
        bool buttonSwapForwPressed = (input.has_changed(Input::ACTION_3, 0.2f) && input.current_value(Input::ACTION_3) > 0.9f);
        bool buttonSwapBackPressed = (input.has_changed(Input::ACTION_2, 0.2f) && input.current_value(Input::ACTION_2) > 0.9f);
        bool buttonBreakPressed = (input.has_changed(Input::ACTION_1, 0.2f) && input.current_value(Input::ACTION_1) > 0.9f);
        bool buttonMutePressed = false;

#ifdef WIN32
        if (useWII) {
            float pitch = WII->getPitch(), roll = -1 * WII->getRoll(); // [-90, 90].
            pitch = glm::clamp(pitch - 10, -90.0f, 90.0f);
            //pitch = glm::clamp(-10 + 90 * glm::sign(pitch) * glm::pow(glm::abs(1.0f * pitch / 90), 1.0f), -90.0f, 90.0f);
            //roll = glm::clamp(90 * glm::sign(roll) * glm::pow(glm::abs(1.0f * roll / 90), 1.0f), -90.0f, 90.0f);
            player.set_canon_pitch(pitch);
            player.set_canon_yaw(roll);

            buttonFirePressed = WII->getButtonAPressed();
            buttonSwapBackPressed = WII->getArrowLeftPressed();

            buttonSwapForwPressed = WII->getArrowRightPressed();
            buttonBreakPressed = WII->getButtonBDown();
            //buttonMutePressed = WII->getArrowUpPressed();
            const bool wiiSwapAB = false;
            if (wiiSwapAB) std::swap(buttonFirePressed, buttonBreakPressed);
        } else {
#endif
            player.set_canon_pitch(input.current_value(Input::MOVE_Y) * 90.f);
            player.set_canon_yaw(input.current_value(Input::MOVE_X) * 90.f);
#ifdef WIN32
        }
#endif
        if (buttonFirePressed) {
            shoot();

#ifdef WIN32
            if(useWII) WII->setRumble(true);
        } else {
            if(useWII) WII->setRumble(false);
#endif

        }

        if(buttonMutePressed) {
            music_mute = !music_mute;
            if(music_mute) {
                music ->stop();
            }
            //change_particles(-1);

        }

        if (buttonSwapForwPressed) {
            change_particles(1);
        }
        if (buttonSwapBackPressed) {
            change_particles(-1);
        }

        if( buttonBreakPressed && global_time - last_break > break_cooldown)
            last_break = global_time;

        float speed = current_movement_speed;
        if (global_time - last_break < break_duration)
            speed *= break_factor;



        player.update_position(path, player.path_position() + speed * dt);

        update_camera();

        update_enemies(dt);

        smoke->update(dt);
        attack_particles->update(dt, enemies, this);

        dust->config.spawn_position = glm::vec4(path->at(player.path_position() + dust_spawn_ahead) - half_dust_spawn_area, 1.f);
        dust->update_config();
        dust->update(dt);

        explosions->update(dt);

        life_text.set_number(life);
        score_text.set_number(score);

        dust->config.spawn_position = glm::vec4(path->at(player.path_position() + dust_spawn_ahead) - half_dust_spawn_area, 1.f);
        dust->update_config();
        dust->update(dt);

        explosions->update(dt);

        active_sounds.remove_if([](const Sound * s) {
            if(s->is_done()) {
                delete s;
                return true;
            };
            return false;
        });
        // Really ugly way of looping the music:
        if(music != nullptr && music->is_done() && !music_mute)
        {
            delete music;
            music = new Sound("ecstacy.mp3", 5);
            music->play();
        }
    }
    break;
    case MODE_HIGHSCORE:
        fade_music(dt);
        if(start_pressed()) {
            current_mode = MODE_READY;
        }
        break;
    }

    input.update(dt);
}
void C3DGraphicChessboard::display(int* a_board)
{
	// First update camera position and orientation
	update_camera();
			
	
	glEnable(GL_TEXTURE_2D);
	glDisable(GL_LIGHTING);
		
	glColor3f(1.0f,1.0f,1.0f);
	texture_board->bind();
	glCallList(models_list+MODEL_BOARD);
	
	DisplaySkyBox();

	glDisable(GL_TEXTURE_2D);
	glEnable(GL_LIGHTING);
	glDisable(GL_LIGHT1);
	
	const GLfloat lightPosition1    [] = { 7.0f, 10.0f, 7.0f, 0.0f };
	glLightfv(GL_LIGHT1, GL_POSITION, lightPosition1);
	
	// display chessboard
	glMaterialfv(GL_FRONT,GL_AMBIENT,material_chessboard_Ka);
	glMaterialfv(GL_FRONT,GL_DIFFUSE,material_chessboard_Kd);
	glMaterialfv(GL_FRONT,GL_SPECULAR,material_chessboard_Ks);
	glMaterialfv(GL_FRONT,GL_EMISSION,material_chessboard_Ke);
	glMaterialf(GL_FRONT,GL_SHININESS,51.2f);//51.2f = 128.0f*0.4f
		
	glPushMatrix();
	glTranslatef(7.0f,-0.1f,7.0f);
	glCallList(models_list+MODEL_CHESSBOARD);
	glPopMatrix();

	glEnable(GL_LIGHT1);
	glEnable(GL_BLEND);
	
	// diplay all the pieces
	int a,b,c;
	
	for (a = 1; a <= 8; a++) 
	{
		for (b = 0; b <= 11; b++) 
		{
			c = 24 + a*12 -b;
			
			switch(a_board[c])
			{
				case 1:  DisplayPiece(models_list+MODEL_PAWN,b-3,a-1,WHITE);	break;
				case 2:  DisplayPiece(models_list+MODEL_PAWN,b-3,a-1,BLACK);	break;
				case 3:  DisplayPiece(models_list+MODEL_KNIGHT,b-3,a-1,WHITE);	break;
				case 4:  DisplayPiece(models_list+MODEL_KNIGHT,b-3,a-1,BLACK);	break;
				case 5:  DisplayPiece(models_list+MODEL_KING,b-3,a-1,WHITE);	break;
				case 6:  DisplayPiece(models_list+MODEL_KING,b-3,a-1,BLACK);	break;
				case 7:  DisplayPiece(models_list+MODEL_ROOK,b-3,a-1,WHITE);	break;
				case 8:  DisplayPiece(models_list+MODEL_ROOK,b-3,a-1,BLACK);	break;
				case 9:  DisplayPiece(models_list+MODEL_QUEEN,b-3,a-1,WHITE);	break;
				case 10: DisplayPiece(models_list+MODEL_QUEEN,b-3,a-1,BLACK);	break;
				case 11: DisplayPiece(models_list+MODEL_BISHOP,b-3,a-1,WHITE);	break;
				case 12: DisplayPiece(models_list+MODEL_BISHOP,b-3,a-1,BLACK);	break;	
				default: break;	
			}
		}
	}
}
Example #25
0
void render_update(double last_frame_time)
{
	static int isolevel_offset = 1;
	matrix4f model_inv_mat4;
	matrix3f model_inv_mat3;
	vector3f camera_pos;
	
	IF_FAILED(init);
	
	mat4(modelmat, 1.0f);
	
	last_time = last_frame_time;
	
	// обновляем камеру (позицию и т.п)
	update_camera(last_frame_time);
	
	// поулчаем параметры камеры
	camera_pos = camera_get_position(&camera);
	camera_get_view_matrix(&camera, viewmat);
	camera_get_projection_matrix(&camera, projectionmat);
	
	// обновляем вращение объекта (arcball)
	update_object_orientation();
	mat4_mult2(modelmat, rotmat, modelmat);
	
	// смещаем объект
	matrix4f translatemat;
	mat4_translate(translatemat, -0.5f, -0.5f, -0.5f);
	mat4_mult2(modelmat, modelmat, translatemat);
	
	// вращаем источник света
	if(light_animate) {
		light_rot_angle += light_rot_step;
		if(light_rot_angle > 360.0f) light_rot_angle = 0.0f;
	}
	
	matrix4f light_mat;
	mat4_rotate_axis(light_mat, light_rot_angle, vec3f(0.0f, 1.0f, 0.0f));
	new_light_position = mat4_mult_vec3(light_mat, light_position);
	
	
	// изменяем изо-уровень
	if(isolevel_animate) {
		
		isolevel += isolevel_step * isolevel_offset;
		
		if(isolevel_begin <= isolevel_end) {
			if(isolevel >= isolevel_end)
				isolevel_offset = -1;
			else if(isolevel < isolevel_begin)
				isolevel_offset = 1;
		} else {
			if(isolevel < isolevel_end)
				isolevel_offset = 1;
			else if(isolevel >= isolevel_begin)
				isolevel_offset = -1;
		}
		
	}
	
	mat4_inverse(model_inv_mat4, modelmat);
	mat4_submat(model_inv_mat3, 3, 3, model_inv_mat4);
	
	// обновляем вершинные буферы
	if(isolevel_animate)
		render_update_mc();
	
	shader_program_bind(&program);
	
	// устанавливаем юниформы
	glUniformMatrix4fv(uniform_modelmat, 1, GL_TRUE, (const GLfloat *) modelmat);
	glUniformMatrix4fv(uniform_viewmat, 1, GL_TRUE, (const GLfloat *) viewmat);
	glUniformMatrix4fv(uniform_projectionmat, 1, GL_TRUE, (const GLfloat *) projectionmat);
	glUniformMatrix3fv(uniform_model_inv, 1, GL_TRUE, (const GLfloat *) model_inv_mat3);
	glUniform3f(uniform_light_pos, new_light_position.x, new_light_position.y, new_light_position.z);
	glUniform3f(uniform_viewer_pos, camera_pos.x, camera_pos.y, camera_pos.z);

	glUniform1f(uniform_coef_ambient, coef_ambient);
	glUniform1f(uniform_coef_diffuse, coef_diffuse);
	glUniform1f(uniform_coef_specular, coef_specular);
	glUniform1f(uniform_material_shininess, material_shininess);
	glUniform1f(uniform_coef_gamma, coef_gamma);
	glUniform3f(uniform_material_front_color, material_front_color.x, material_front_color.y, material_front_color.z);
	glUniform3f(uniform_material_back_color, material_back_color.x, material_back_color.y, material_back_color.z);
	glUniform3f(uniform_light_color, light_color.x, light_color.y, light_color.z);
	glUniform3f(uniform_light_spec_color, light_spec_color.x, light_spec_color.y, light_spec_color.z);
	
	shader_program_unbind(&program);

}
Example #26
0
static void update(void) {
	update_camera();
	update_sunset();
}