void RagdollDemo::clientMoveAndDisplay() { #ifdef GRAPHICS glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); extern GLDebugDrawer gDebugDrawer; #endif if (m_dynamicsWorld) { double delta_x = brain->get_output(0); delta_x *= MOTOR_SCALE; //printf("delta_x: %f\n", delta_x); btVector3 agent_position = move_kinematic_body(agent, btVector3(delta_x, 0, 0)); agent->setActivationState(ACTIVE_TAG); btVector3 target_a_position = move_kinematic_body(target_a, btVector3(target_a_dx, 0, target_a_dz)); btVector3 target_b_position = move_kinematic_body(target_b, btVector3(target_b_dx, 0, target_b_dz)); target_a->setActivationState(ACTIVE_TAG); target_b->setActivationState(ACTIVE_TAG); if (create_draw_file) { draw_fh << agent_position.getX() << " " << agent_position.getZ() << " "; draw_fh << target_a_position.getX() << " " << target_a_position.getZ() << " "; draw_fh << target_b_position.getX() << " " << target_b_position.getZ() << std::endl; } for (int i = 0; i < NUM_RAYS; i++) { double angle = (-RAY_ANGLE / 2) + (i * (RAY_ANGLE / (NUM_RAYS - 1))); btVector3 ray_offset(RAY_LENGTH * sin(angle), 0, RAY_LENGTH * cos(angle)); btVector3 ray_end = agent_position - ray_offset; int touch = raycast(agent_position, ray_end); btVector3 ray = ray_end - agent_position; double sensor = (1.0 - (ray.length() / RAY_LENGTH)) * 10; ray_sensors[i] = sensor; #ifdef GRAPHICS btVector3 color = touch ? btVector3(0, .8, 0) : btVector3(0, 0, 0); gDebugDrawer.drawLine(agent_position, ray_end, color); #endif } if (!target_a_passed && (target_a_position.getZ() >= AGENT_Z)) { target_a_passed = true; target_a_distance = fabs(agent_position.getX() - target_a_position.getX()); } if (!target_b_passed && (target_b_position.getZ() >= AGENT_Z)) { target_b_passed = true; target_b_distance = fabs(agent_position.getX() - target_b_position.getX()); } if (target_a_passed && target_b_passed) { double fitness = target_a_distance + target_b_distance; std::ofstream fh; fh.open(ERROR_FILENAME); fh << fitness; fh.close(); if (create_draw_file) { draw_fh.close(); } exit(0); } frame_count++; m_dynamicsWorld->stepSimulation(TIME_STEP); brain->step(.01); #ifdef TEST_SPEED printf("%d %f\n", frame_count, agent_position.getX()); #endif //optional but useful: debug drawing m_dynamicsWorld->debugDrawWorld(); } //world exists #ifdef GRAPHICS renderme(); glFlush(); glutSwapBuffers(); #endif }
NxF32 computeConcavityVolume(NxU32 vcount_hull, const NxF32 *vertices_hull, NxU32 tcount_hull, const NxU32 *indices_hull, NxU32 vcount_mesh, const NxF32 *vertices_mesh, NxU32 tcount_mesh, const NxU32 *indices_mesh) { NxF32 total_volume = 0; #if SHOW_DEBUG NVSHARE::gRenderDebug->pushRenderState(); NVSHARE::gRenderDebug->setCurrentDisplayTime(150.0f); #endif iRayCast *cast_hull = createRayCast(vertices_hull,tcount_hull,indices_hull); iRayCast *cast_mesh = createRayCast(vertices_mesh,tcount_mesh,indices_mesh); const NxU32 *indices = indices_mesh; #if 0 static NxU32 index = 0; NxU32 i = index++; indices = &indices[i*3]; #else for (NxU32 i=0; i<tcount_mesh; i++) #endif { NxU32 i1 = indices[0]; NxU32 i2 = indices[1]; NxU32 i3 = indices[2]; const NxF32 *p1 = &vertices_mesh[i1*3]; const NxF32 *p2 = &vertices_mesh[i2*3]; const NxF32 *p3 = &vertices_mesh[i3*3]; NxF32 normal[3]; NxF32 d = fm_computePlane(p3,p2,p1,normal); NxF32 vertices[6*3]; vertices[0] = p1[0]; vertices[1] = p1[1]; vertices[2] = p1[2]; vertices[3] = p2[0]; vertices[4] = p2[1]; vertices[5] = p2[2]; vertices[6] = p3[0]; vertices[7] = p3[1]; vertices[8] = p3[2]; NxF32 midPoint[3]; midPoint[0] = (p1[0]+p2[0]+p3[0])/3; midPoint[1] = (p1[1]+p2[1]+p3[1])/3; midPoint[2] = (p1[2]+p2[2]+p3[2])/3; fm_lerp(midPoint,p1,&vertices[0],0.9999f); fm_lerp(midPoint,p2,&vertices[3],0.9999f); fm_lerp(midPoint,p3,&vertices[6],0.9999f); NxF32 *_p1 = &vertices[3*3]; NxF32 *_p2 = &vertices[4*3]; NxF32 *_p3 = &vertices[5*3]; NxU32 hitCount = 0; if ( raycast(&vertices[0],normal, _p1,cast_hull,cast_mesh) ) hitCount++; if ( raycast(&vertices[3],normal, _p2,cast_hull,cast_mesh) ) hitCount++; if ( raycast(&vertices[6],normal, _p3,cast_hull,cast_mesh) ) hitCount++; // form triangle mesh! if ( hitCount == 3 ) { NxU32 tcount = 0; NxU32 tindices[8*3]; addTri(tindices,2,1,0,tcount); addTri(tindices,3,4,5,tcount); addTri(tindices,0,3,2,tcount); addTri(tindices,2,3,5,tcount); addTri(tindices,1,3,0,tcount); addTri(tindices,4,3,1,tcount); addTri(tindices,5,4,1,tcount); addTri(tindices,2,5,1,tcount); NxF32 volume = fm_computeMeshVolume(vertices,tcount,tindices); total_volume+=volume; #if SHOW_DEBUG NVSHARE::gRenderDebug->setCurrentColor(0x0000FF,0xFFFFFF); NVSHARE::gRenderDebug->addToCurrentState(NVSHARE::DebugRenderState::SolidWireShaded); for (NxU32 i=0; i<tcount; i++) { NxU32 i1 = tindices[i*3+0]; NxU32 i2 = tindices[i*3+1]; NxU32 i3 = tindices[i*3+2]; const NxF32 *p1 = &vertices[i1*3]; const NxF32 *p2 = &vertices[i2*3]; const NxF32 *p3 = &vertices[i3*3]; NVSHARE::gRenderDebug->DebugTri(p1,p2,p3); } #endif } indices+=3; } #if SHOW_DEBUG NVSHARE::gRenderDebug->popRenderState(); #endif releaseRayCast(cast_hull); releaseRayCast(cast_mesh); return total_volume; }
void game::run() { //MissileDesc projectile(*this); towerDesc towr(this); std::string txt; std::string txt2 = "Life:"; std::string txt3 = "Money:"; std::string main = "Cam Pos"; std::string txt4 = "Game Over"; std::list<SceneObject *> troll; endgame = false; mouseUp = false; float dir = 0.0f; float spot_dir = 45.0f; float aspect_time = 0.0f; towerCount = 0; cost = 0; life = 20; money = 10; quit = false; cameraRestricted = false; selected_tower = ""; std::stringstream ss2 (std::stringstream::in | std::stringstream::out); std::stringstream ss3 (std::stringstream::in | std::stringstream::out); /*GUI app; int retval = app.main(args); if (retval == 0) { return retval; }*/ Quaternionf camera_orientation(55.0f, 0.0f, 0.0f, angle_degrees, order_YXZ); clan::OpenGLWindowDescription opengl_desc; opengl_desc.set_version(3, 2, false); clan::OpenGLTarget::set_description(opengl_desc); //Scene test; //clan::SceneCamera camera(test); //DisplayWindowDescription innerwindow("Hello World", Size(640, 480), true); //innerwindow.set_allow_resize(true); //innerwindow.set_fullscreen(true); clan::DisplayWindowDescription win_desc; win_desc.set_allow_resize(true); win_desc.set_title("Main"); win_desc.set_size(clan::Size( 1100, 900 ), false); DisplayWindow window(win_desc); //DisplayWindow window("main", 1200, 900, false, true); //window.maximize(); //DisplayWindow window(innerwindow); Rect viewport = window.get_viewport(); GraphicContext gc = window.get_gc(); ResourceManager resources; SceneCache::set(resources, std::shared_ptr<SceneCache>(new AppSceneCache())); ResourceManager sound_resources = XMLResourceManager::create(XMLResourceDocument("../Resources/resources.xml")); sound_resources_=&sound_resources; std::string shader_path = "../Resources/Scene3D"; Scene scene(gc, resources, shader_path); sceneHolder = &scene; SceneCamera camera(scene); scene.set_camera(camera); scene.set_viewport(gc.get_size()); camera.set_orientation(camera_orientation); camera.set_position(Vec3f(0.0f, 40.0f, down)); Canvas canvas(window); image_hp = Image(canvas, "../Resources/Images/heart.png"); image_hp.set_alignment(origin_center); image_hp.set_scale(0.07, 0.07); image_coin = Image(canvas, "../Resources/Images/coin.png"); image_coin.set_alignment(origin_center); image_coin.set_scale(0.3, 0.3); GUIWindowManagerDirect direct(window, canvas); GUIManager maingui(direct, "../Resources"); GUIComponent *win_comp = new GUIComponent(&maingui, win_desc, ""); radial_menu = new RadialMenu(win_comp); radial_menu->func_selected.set(this, &game::on_radial_menu_itemselected); //GameComponent game_component(viewport, &maingui); /*Rect toolbar_rect = Rect((viewport.get_width() - 448) / 2, viewport.bottom - 56, (viewport.get_width() - 448) / 2 + 448, viewport.bottom); Toolbar toolbar(toolbar_rect, &game_component); // GameComponent is the "desktop" that the toolbar sits on, as an owner toolbar.add_item(Sprite(canvas, "../Resources/Images/spell1.png"), Sprite(canvas, "../Resources/Images/spell1_selected.png"), Sprite(canvas, "../Resources/Images/spell1_clicked.png")); toolbar.add_item(Sprite(canvas, "../Resources/Images/spell2.png"), Sprite(canvas, "../Resources/Images/spell2_selected.png"), Sprite(canvas, "../Resources/Images/spell2_clicked.png")); toolbar.add_item(Sprite(canvas, "../Resources/Images/spell3.png"), Sprite(canvas, "../Resources/Images/spell3_selected.png"), Sprite(canvas, "../Resources/Images/spell3_clicked.png")); toolbar.add_item(Sprite(canvas, "../Resources/Images/spell4.png"), Sprite(canvas, "../Resources/Images/spell4_selected.png"), Sprite(canvas, "../Resources/Images/spell4_clicked.png")); toolbar.add_item(Sprite(canvas, "../Resources/Images/spell5.png"), Sprite(canvas, "../Resources/Images/spell5_selected.png"), Sprite(canvas, "../Resources/Images/spell5_clicked.png")); toolbar.add_item(Sprite(canvas, "../Resources/Images/spell6.png"), Sprite(canvas, "../Resources/Images/spell6_selected.png"), Sprite(canvas, "../Resources/Images/spell6_clicked.png")); toolbar.add_item(Sprite(canvas, "../Resources/Images/spell7.png"), Sprite(canvas, "../Resources/Images/spell7_selected.png"), Sprite(canvas, "../Resources/Images/spell7_clicked.png")); */ InputDevice keyboard = window.get_ic().get_keyboard(); InputDevice mouse = window.get_ic().get_mouse(); clan::Font font(canvas, "Tahoma", 30); // The clan prefix is required on linux due to a namespace conflict SceneModel plane(gc, scene, "plane"); SceneModel box(gc, scene, "box"); SceneModel tower(gc, scene, "tower"); SceneModel gate(gc,scene,"gate"); SceneObject object(scene, plane, Vec3f(0.0f, 0.0f, 0.0f)); object.rotate(180.0f, 0.0f, 0.0f); scene.show_skybox_stars(false); /*SceneObject box0(scene, tower, Vec3f(20.0f, 5.0f, 0.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ)); SceneObject box1(scene, tower, Vec3f(-20.0f, 5.0f, 0.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ)); SceneObject box2(scene, tower, Vec3f(0.0f, 5.0f, 20.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ)); SceneObject box3(scene, tower, Vec3f(0.0f, 5.0f, -20.0f), Quaternionf(0.0f, 0.0f, 0.0f, angle_degrees, order_YXZ)); SceneObject tower[10];*/ SceneObject theGate(scene, gate, Vec3f(-75.0f,5.0f,60.0f), Quaternionf(0.0f,0.0f,0.0f,angle_degrees,order_YXZ)); theGate.set_scale(Vec3f(1.0f,2.0f,2.0f)); std::vector<SceneLight> omni_lights; for (int i = 0; i < 4; i++) { SceneLight omni(scene); omni.set_type(SceneLight::type_omni); omni.set_color(Vec3f(0.05f)); omni.set_position(Quaternionf(45.0f, 45.0f + i * 90.0f, 0.0f, angle_degrees, order_YXZ).rotate_vector(Vec3f(0.0f, 0.0f, -100.0f))); omni.set_attenuation_end(200.0f); omni.set_ambient_illumination(0.025f); omni_lights.push_back(omni); } SceneLight spot(scene); spot.set_type(SceneLight::type_spot); spot.set_orientation(Quaternionf(45.0f, 45.0f, 0.0f, angle_degrees, order_YXZ)); spot.set_position(spot.get_orientation().rotate_vector(Vec3f(-55.0f, 90.0f, -550.0f))); //spot.set_position(Vec3f(-250, 100, -430)); spot.set_color(Vec3f(1.0f, 1.0f, 0.8f)); spot.set_falloff(45.0f); spot.set_hotspot(15.0f); spot.set_attenuation_start(150.0f); spot.set_attenuation_end(1500.0f); spot.set_shadow_caster(true); spot.set_rectangle_shape(false); //spot.set_ambient_illumination(true); spot.set_aspect_ratio(1.0f); /*SceneLight spot(scene); spot.set_type(SceneLight::type_spot); spot.set_orientation(Quaternionf(30.0f, 30.0f, 0.0f, angle_degrees, order_YXZ)); spot.set_position(spot.get_orientation().rotate_vector(Vec3f(0.0f, 0.0f, -100.0f))); spot.set_color(Vec3f(1.0f, 1.0f, 0.8f)); spot.set_falloff(45.0f); spot.set_hotspot(15.0f); spot.set_attenuation_start(20.0f); spot.set_attenuation_end(200.0f); spot.set_shadow_caster(true); spot.set_rectangle_shape(false); spot.set_aspect_ratio(1.0f);*/ /*SceneLight spot2(scene); spot2.set_type(SceneLight::type_spot); spot2.set_position(Vec3f(0.0f, 100.0f, 0.0f)); spot2.set_color(Vec3f(1.0f, 1.0f, 1.0f) * 3.0f); spot2.set_falloff(35.0f); spot2.set_hotspot(30.0f); spot2.set_attenuation_start(20.0f); spot2.set_attenuation_end(130.0f); spot2.set_shadow_caster(true); spot2.set_rectangle_shape(false); spot2.set_ambient_illumination(0.025f);*/ wm.NodeArray[0].setPos(75.0f,1.25f,0.0f); wm.NodeArray[1].setPos(-60.0f,1.25f,0.0f); wm.NodeArray[2].setPos(-55.0f,1.25f,-65.0f); wm.NodeArray[3].setPos(60.0f,1.25f,-60.0f); wm.NodeArray[4].setPos(55.0f,1.25f,65.0f); wm.NodeArray[5].setPos(-80.0f,1.25f,60.0f); Physics3DShape box_shape = Physics3DShape::box(Vec3f(5.0f)); Physics3DShape plane_shape = Physics3DShape::box(Vec3f(75.0f, 1.0f, 75.0f)); Physics3DShape sphere_shape = Physics3DShape::sphere(2.0f); Physics3DObject phys_plane(physics_world, plane_shape, Vec3f(0.0f, -0.5f, 0.0f)); /*Physics3DObject phys_box0(physics_world, box_shape, Vec3f(20.0f, 5.0f, 0.0f), box0.get_orientation()); Physics3DObject phys_box1(physics_world, box_shape, Vec3f(-20.0f, 5.0f, 0.0f), box1.get_orientation()); Physics3DObject phys_box2(physics_world, box_shape, Vec3f(0.0f, 5.0f, 20.0f), box2.get_orientation()); Physics3DObject phys_box3(physics_world, box_shape, Vec3f(0.0f, 5.0f, -20.0f), box3.get_orientation()); Physics3DObject phys_box[10];*/ Physics3DSweepTest sweep_test(physics_world); Physics3DRayTest raycast(physics_world); Slot slot_keyboard_key_down = (window.get_ic().get_keyboard()).sig_key_down() .connect(this,&game::on_key_down); Slot slot_keyboard_key_up = (window.get_ic().get_keyboard()).sig_key_up() .connect(this,&game::on_key_up); Slot slot_mouse_moved = (window.get_ic().get_mouse()).sig_pointer_move() .connect(this,&game::on_pointer_move); Slot slot_mouse_down = (window.get_ic().get_mouse()).sig_key_down() .connect(this,&game::on_pointer_down); Slot slot_mouse_up = (window.get_ic().get_mouse()).sig_key_up() .connect(this,&game::on_pointer_up); //________________________________________________________________ // S O U N D S total_channels=3; current_channel=1; SoundBuffer music = SoundBuffer::resource("Music1",sound_resources); music.set_volume(0.3f); sound_session1.play(); sound_session2.play(); sound_session3.play(); total_samples = 6; samples.resize(total_samples); samples[0] = SoundBuffer::resource("Explosion1",sound_resources); samples[1] = SoundBuffer::resource("Explosion2",sound_resources); samples[2] = SoundBuffer::resource("Hurt1",sound_resources); samples[3] = SoundBuffer::resource("Hurt2",sound_resources); samples[4] = SoundBuffer::resource("Powerup1",sound_resources); samples[5] = SoundBuffer::resource("Shoot1",sound_resources); for(int i = 0; i<total_samples; i++) { samples[i].set_volume(0.3f); } SoundBuffer_Session music_session = music.prepare(); music_session_ = &music_session; music_session.set_looping(true); music_session.play(); is_music_muted = false; /********Enemies(Jasper)************************/ SceneObject enemyobj[30]; wm.spawnCreeps(); for(int i = 0; i < 30; i ++) { enemyobj[i] = SceneObject(scene, box); enemyobj[i].set_scale(Vec3f(0.25f)); wm.enemyArray[i].setEnemyObject(&enemyobj[i]); } /***************************************/ ElapsedTimer elapsed_timer; while (!quit) { float time_elapsed = elapsed_timer.seconds_elapsed(); /*spot_dir = std::fmod(spot_dir + time_elapsed * 30.0f, 90.0f); aspect_time = std::fmod(aspect_time + time_elapsed * 0.2f, 2.0f); spot2.set_aspect_ratio(clamp(aspect_time >= 1.0f ? 2.0f - aspect_time : aspect_time, 0.1f, 1.0f)); spot2.set_orientation(Quaternionf(65.0f + (spot_dir >= 45.0f ? 90.0f - spot_dir : spot_dir), 60.0f, dir * 4.0f, angle_degrees, order_YXZ)); */ // Draw with the canvas: /*canvas.clear(Colorf::cadetblue); canvas.draw_line(0, 110, 640, 110, Colorf::yellow); font.draw_text(canvas, 100, 100, "Hello World!", Colorf::lightseagreen); // Draw any remaining queued-up drawing commands oQAn canvas: canvas.flush();*/ if (!endgame) { if (mouse.get_x() <= 0 && !cameraRestricted) { mouse.set_position(0, mouse.get_y()); camera.set_position(camera.get_position()+Vec3f(-mouse_move_speed, 0.0f, 0.0f)); /*canvas.clear(); font.draw_text(canvas, 100, 100, "x=0", Colorf::lightseagreen); canvas.flush();*/ //window.flip(); } if (mouse.get_y() <= 0 && !cameraRestricted) { mouse.set_position(mouse.get_x(), 0); camera.set_position(camera.get_position()+Vec3f(0.0f, 0.0f, mouse_move_speed)); /*canvas.clear(); font.draw_text(canvas, 100, 100, "y=0", Colorf::lightseagreen); canvas.flush();*/ //window.flip(); } if (mouse.get_x() >= window.get_gc().get_width()-1 && !cameraRestricted) { mouse.set_position(window.get_gc().get_width()-1, mouse.get_y()); camera.set_position(camera.get_position()+Vec3f(mouse_move_speed, 0.0f, 0.0f)); /*canvas.clear(); font.draw_text(canvas, 100, 100, "x=windowRight", Colorf::lightseagreen); canvas.flush();*/ //window.flip(); } if (mouse.get_y() >= window.get_gc().get_height()-1 && !cameraRestricted) { mouse.set_position(mouse.get_x(), window.get_gc().get_height()-1); camera.set_position(camera.get_position()+Vec3f(0.0f, 0.0f, -mouse_move_speed)); /*canvas.clear(); font.draw_text(canvas, 100, 100, "y=windowBottom", Colorf::lightseagreen); canvas.flush();*/ //window.flip(); } if (mouseUp) { if (selected_tower == "Tower 1") { towr.set_type(towr.t_bullet); cost = 10; } else if (selected_tower == "Tower 2") { towr.set_type(towr.t_energy); cost = 15; } else if (selected_tower == "Tower 3") { towr.set_type(towr.t_rocket); cost = 20; } scene.unproject(mouse_pos, start, end); end *= 151; test = start + end; if (raycast.test(start, test)) { if (towerCount < 10 && money >= cost) { towr.set_pos(Vec3f(raycast.get_hit_position().x, 5.0f, raycast.get_hit_position().z)); towr.create(scene, tower, physics_world); money -= cost; towerCount++; cost = 0; } } mouseUp = false; //float x = mouse.get_x() - scene.world_to_projection().get_origin_x(); //tower[0] = SceneObject(scene, box, Vec3f(camera.get_position().x, 5.0f, camera.get_position().z)); //tower[0].set_position(Vec3f(0.0f, 5.0f, 0.0f)); //window.flip(); //canvas.clear(Colorf::cadetblue); /*canvas.draw_line(0, 110, 640, 110, Colorf::yellow); font.draw_text(canvas, 100, 100, "Hello World!", Colorf::lightseagreen); // Draw any remaining queued-up drawing commands oQAn canvas: canvas.flush(); // Present the frame buffer content to the user: window.flip();*/ } if (mouse.get_keycode(0)) { //maingui.process_messages(0); //test.update(); //show_radial_menu(mouse.get_position()); } /*if (mouse.get_keycode(1)) { scene.unproject(mouse.get_position(), start, end); end *= 151; Vec3f test = start + end; if (raycast.test(start, test)) { Physics3DObject hit = raycast.get_hit_object(); font.draw_text(canvas, 400, 100, "hit", Colorf::lightseagreen); //hit.set_position(Vec3f(0.0f, -10.0f, 0.0f)); std::stringstream ss3 (std::stringstream::in | std::stringstream::out); ss3 << hit.get_position().y; txt3 = ss3.str(); font.draw_text(canvas, 550, 100, txt3, Colorf::lightseagreen); } //projectile.set_pos(Vec3f(raycast.get_hit_position().x, 5.0f, raycast.get_hit_position().z)); //projectile.fire(scene, box, physics_world); //canvas.clear(Colorf::white); //window.flip(); }*/ if (keyboard.get_keycode(keycode_control)) { if (window.is_fullscreen()) { //innerwindow.set_fullscreen(false); window.set_size(640, 480, true); window.restore(); } else window.set_size(640, 480, false); } if (camera.get_position().x <= left) { camera.set_position(Vec3f(left, camera.get_position().y, camera.get_position().z)); } if (camera.get_position().x >= right) { camera.set_position(Vec3f(right, camera.get_position().y, camera.get_position().z)); } if (camera.get_position().z >= top) { camera.set_position(Vec3f(camera.get_position().x, camera.get_position().y, top)); } if (camera.get_position().z <= down) { camera.set_position(Vec3f(camera.get_position().x, camera.get_position().y, down)); } /*if(objects_for_deletion.size()>0) { std::list<Gameobject *>::iterator it; for(it=objects_for_deletion.begin(); it!= objects_for_deletion.end(); ++it) { delete (*it); //towerCount--; } objects_for_deletion.clear(); }*/ if(towerObjects.size()>0) { std::vector<Gameobject *>::iterator it; int counter = 0; for(it=towerObjects.begin(); it!= towerObjects.end(); ++it) { towerObjects.at(counter)->update(time_elapsed, wm.enemyArray, 30); counter++; } } if(missileObjects.size()>0) { std::list<Gameobject *>::iterator it; for(it=missileObjects.begin(); it!= missileObjects.end();) { //if (!(*it)->checkActive()) (*it)->update(time_elapsed, wm.enemyArray); if ((*it)->checkActive()) { delete(*it); it = missileObjects.erase(it); } else it++; } } /*******Enemies(Updates)************************/ wm.Update(1); //time_lasttime = time_elapsed; if(wm.life > 0) { // Put a screen here life -= wm.life; wm.life = 0; } if (wm.currLevel == 3) { endgame = true; } /***********************************************/ //scene.update(gc, time_elapsed); txt3 = ":"; ss3.str(""); ss3.clear(); ss3 << money; txt3 += ss3.str(); font.draw_text(canvas, 550, 50, txt3, Colorf::lightseagreen); if (life < 0) { endgame = true; } scene.render(gc); /*canvas.clear(clan::Colorf(0.0f,0.0f,0.0f)); std::stringstream ss (std::stringstream::in | std::stringstream::out); ss << game_time.get_time_elapsed(); std::string troll = ss.str(); font.draw_text(canvas, 100, 100, troll, Colorf::lightseagreen);*/ //canvas.clear(clan::Colorf(0.0f,0.0f,0.0f)); std::stringstream ss (std::stringstream::in | std::stringstream::out); ss << scene.world_to_projection().get_origin_x(); txt = ss.str(); txt2 = ":"; ss2.str(""); ss2.clear(); ss2 << life; txt2 += ss2.str(); font.draw_text(canvas, 150, 50, txt2, Colorf::lightseagreen); //maingui.process_messages(0); /*font.draw_text(canvas, 0, 100, main, Colorf::lightseagreen); font.draw_text(canvas, 150, 100, txt, Colorf::lightseagreen); font.draw_text(canvas, 250, 100, txt2, Colorf::lightseagreen); canvas.draw_line(0, 110, 640, 110, Colorf::yellow);*/ maingui.render_windows(); image_hp.draw(canvas, 100, 45); image_coin.draw(canvas, 500, 45); window.flip(); // Read messages from the windowing system message queue, if any are available: KeepAlive::process(); } else { //maingui.render_windows(); canvas.clear(Colorf::black); font.draw_text(canvas, 450, 400, txt4, Colorf::lightseagreen); window.flip(); // Read messages from the windowing system message queue, if any are available: KeepAlive::process(); } } }
void Game::draw(GLUTRenderingContext * g) { AABBf selectionUIVisual = selectedArea; selectionUIVisual.validate(); g->setColor(0x88ff88); selectionUIVisual.glDraw(false); if (doingOperation) { g->setColor(0xaaaaff); g->drawLine(operationPoint, mousePosition); } delauny->draw(g_screen); // return; // draw selected obstacle indicator if (selectedObstacles.size() > 0) { g->setColor(0xaaffaa); for (int i = 0; i < selectedObstacles.size(); ++i) { Shape * s = selectedObstacles[i]->getShape(); g->drawCircle(s->getCenter(), s->getRadius(), false); s->draw(g, true); } g->drawCircle(selectedOrigin, .1f, true); } g->setColor(0x00aaff); g->printf(mousePosition, "%.2f, %.2f", mousePosition.x, mousePosition.y); g->drawCircle(mousePosition, .1f, false); // int layerColors[] = { 0x0088aa, 0x66aa88, 0x88aa22, 0x123456 }; // int layerColorsCount = sizeof(layerColors) / sizeof(layerColors[0]); // objectMap.draw(g, layerColors, layerColorsCount); // testing cone stuff RaycastHit rh; V2f hit, norm; float dist = 0, maxDist = 0; Obstacle * o; g->drawCircle(userRay.start, .05f, true); // TEST <-- TODO V2f delta = mousePosition - userRay.start; if (!delta.isZero()) { dist = delta.magnitude(); delta /= dist; } maxDist = dist; //TemplateSet<int> cellList; //staticObstaclesMap->raycastCellList(mouseClick, delta, dist, cellList); //for (int i = 0; i < cellList.size(); ++i) { staticObstaclesMap->cells[cellList[i]]->glDraw(true); } if (raycast(userRay, rh, userRayDistance, false, o, -1)) { g->setColor(0); drawRaycastHit(rh, 1); g->printf(rh.point, "%.2f, ", rh.distance); } g->drawLine(userRay.start, userRay.start + userRay.direction * userRayDistance);//userRay.glDraw(); for (int i = 0; i < obstacles.size(); ++i) { Obstacle * obs = obstacles[i]; g->setColor(0x333333); obs->getShape()->draw(g, false); obs->getShape()->getClosestRaycastHit(mousePosition, rh); g->setColor(0x888888); drawRaycastHit(rh, .2f); } }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * TRACE ALGORITHM * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ ngl::Colour Renderer::trace(ngl::Vec3 _from, ngl::Vec3 _direction, int depth) { // create vector that will store intersection values for parameter t in the primary ray // a primary ray has a form like R = O + t * D where O is the origin vector, and D direction. std::vector<double> intersections; geo::Ray cam_ray(_from,_direction); // iterate over objects in the scene and find intersections for(unsigned int i = 0; i < m_scene->m_objects.size(); i++) { // each Shape subclass (Sphere, Plane...) has its own method for calculating intersections intersections.push_back( m_scene->m_objects.at(i)->getIntersection(cam_ray)); } // find closest object int closest_index = getIndexClosest(intersections); // if no intersections are found RETURN black = if(closest_index == -1) {return ngl::Colour(0,0,0,1);} // calculate pHit (position of the new intersection) and nHit (normal at hit point) ngl::Vec3 pHit = _from + intersections.at(closest_index) * _direction; ngl::Vec3 nHit = m_scene->m_objects.at(closest_index)->getNormalAt(pHit); // calculate if we are inside or outside bool inside = false; if(_direction.dot(nHit) > 0) { nHit = -nHit; inside = true; } float bias = 0.01; // calculate if point is obscured or shadowed bool isObscured = raycast(pHit + nHit * bias, closest_index); // // // // // // // // // // // // // // put all contributions together // // // // // // // // // // // // // // // is the object reflective or refractive??? if ((m_scene->m_objects.at(closest_index)->getMaterial()->isReflective() || m_scene->m_objects.at(closest_index)->getMaterial()->isRefractive()) && depth < m_max_depth) { ngl::Colour crfr(0,0,0,1); ngl::Colour crfl(0,0,0,1); // check whether it is REFLECTIVE if (m_scene->m_objects.at(closest_index)->getMaterial()->isReflective()) { // calculate reflection dir float bias = 0.01; ngl::Vec3 refl_dir = _direction - nHit * 2 * _direction.dot(nHit); refl_dir.normalize(); // fire ray along reflection direction from hit point crfl = trace(pHit + bias*nHit, refl_dir, depth+1); } // check whether it is REFRACTIVE if (m_scene->m_objects.at(closest_index)->getMaterial()->isRefractive()) { // calculate refrection dir (transmission ray) float ior = m_scene->m_objects.at(closest_index)->getMaterial()->getIOR(); float eta = inside; float bias = 0.01; float cosi = -nHit.dot(_direction); if (eta == true) // we are inside { eta = ior; } else // we are outside { eta = 1 / ior; } float k = 1 - eta * eta * (1 - cosi * cosi); ngl::Vec3 refr_dir = _direction * eta + nHit * (eta * cosi - sqrt(k)); refr_dir.normalize(); crfr = trace(pHit - nHit * bias, refr_dir, depth+1); } ngl::Colour surfaceColor = m_scene->m_objects.at(closest_index)->getColour(pHit); float cosineFactor = std::max(-nHit.dot(cam_ray.getDirection()),(float)0); float attenuation; ngl::Colour Ka(1,0,0.4,1); ngl::Colour Kd; ngl::Colour Ks; float ambient_intensity = 0.05; ngl::Colour ambient_contrib = Ka * surfaceColor * ambient_intensity; ngl::Colour diffuse_contrib(0,0,0,1); ngl::Colour specular_contrib(0,0,0,1); for(unsigned int m = 0; m < m_scene->m_lights.size(); m++) { ngl::Vec3 v_distance = m_scene->m_lights.at(m)->m_pos - pHit; float distance = v_distance.length(); float radius = 8; attenuation = 1 - pow(distance/radius,2); Kd = m_scene->m_lights.at(m)->m_diff_col; Ks = m_scene->m_lights.at(m)->m_spec_col; ngl::Vec3 L = m_scene->m_lights.at(m)->m_pos - pHit; L.normalize(); ngl::Vec3 N = nHit; ngl::Vec3 R = 2 * (L.dot(N) * N) - L; R.normalize(); diffuse_contrib += (surfaceColor * (Kd * pow(std::max(L.dot(N),(float)0),2) * m_scene->m_lights.at(m)->m_diff_int))*attenuation; specular_contrib += ((Ks * pow(std::max(R.dot(-_direction),(float)0),900)*400 * m_scene->m_lights.at(m)->m_spec_int))*attenuation; } specular_contrib.clamp(0,0.8); ngl::Colour s01 = crfl * m_scene->m_objects.at(closest_index)->getMaterial()->getReflIntensity(); ngl::Colour s02 = crfr * m_scene->m_objects.at(closest_index)->getMaterial()->getTransparency(); ngl::Colour s03 = s01 + s02; ngl::Colour diffuseColor = m_scene->m_objects.at(closest_index)->getColour(pHit) * cosineFactor * m_scene->m_objects.at(closest_index)->getMaterial()->getDiffuseIntensity(); // Do PHONG MODEL calculations stuff. By now I keep it VERY VERY simple ngl::Colour outRadiance = diffuseColor + s03 + specular_contrib + ambient_contrib; outRadiance.clamp(0,1); return isObscured ? outRadiance * 0.7f : outRadiance; } // if it is not REFLECTIVE nor REFRACTIVE else { ngl::Colour surfaceColor = m_scene->m_objects.at(closest_index)->getColour(pHit); float attenuation; ngl::Colour Ka(1,0,0.4,1); ngl::Colour Kd; ngl::Colour Ks; float ambient_intensity = 0.05; ngl::Colour ambient_contrib = Ka * surfaceColor * ambient_intensity; ngl::Colour diffuse_contrib(0,0,0,1); ngl::Colour specular_contrib(0,0,0,1); for(unsigned int m = 0; m < m_scene->m_lights.size(); m++) { ngl::Vec3 v_distance = m_scene->m_lights.at(m)->m_pos - pHit; float distance = v_distance.length(); float radius = 8; attenuation = 1 - pow(distance/radius,2); Kd = m_scene->m_lights.at(m)->m_diff_col; Ks = m_scene->m_lights.at(m)->m_spec_col; ngl::Vec3 L = m_scene->m_lights.at(m)->m_pos - pHit; L.normalize(); ngl::Vec3 N = nHit; ngl::Vec3 R = 2 * (L.dot(N) * N) - L; R.normalize(); float spec_hardness = m_scene->m_objects.at(closest_index)->getMaterial()->m_spec_hardness; diffuse_contrib += (surfaceColor * (Kd * pow(std::max(L.dot(N),(float)0),2) * m_scene->m_lights.at(m)->m_diff_int))*attenuation; specular_contrib += ((Ks * pow(std::max(R.dot(-_direction),(float)0),spec_hardness) * m_scene->m_lights.at(m)->m_spec_int))*attenuation; } diffuse_contrib.clamp(0,1); specular_contrib.clamp(0,1); ngl::Colour outRadiance = diffuse_contrib + specular_contrib + ambient_contrib; outRadiance.clamp(0,1); return isObscured ? outRadiance * 0.7f : outRadiance; } }
bool CollisionTools::raycast(const Ogre::Ray &ray, Ogre::Vector3 &result,int &FaceIndex,Ogre::Entity* &target,float &closest_distance, const Ogre::uint32 queryMask) { return raycast(ray, result,FaceIndex, (Ogre::MovableObject*&)target, closest_distance, queryMask); }
bool Physics::raycast( Ray *ray, RenderMesh *geom, Vector3 *hitPos ) { if( !raycast( ray, &geom->getBounds() ) ) { return false; } return false; }
//Determines the color of the passed in ray Solid::Intercept* raycast(Ray* r, int depth) { //Returns background color if maximum recursion depth was hit if (depth == 0) { Solid::Intercept* result = new Solid::Intercept(); result->mat.color[0] = 0.1; result->mat.color[1] = 0.1; result->mat.color[2] = 0.1; result->normal = new Vector3(); result->point = new Vector3(); result->t = std::numeric_limits<float>::infinity(); return result; } //Find object intersection Solid::Intercept* result = sceneHit(r); if (result->t != std::numeric_limits<float>::infinity()) { //Ambient lighting for (int i = 0; i < 3; i++) { result->mat.color[i] = result->mat.ambientColor[i] * ambientLight[i]; } //Direct Lighting Ray* lightRay = new Ray(); *(lightRay->start) = *(result->point); *(lightRay->direction) = light->subtract(result->point); if (sceneHit(lightRay)->t == std::numeric_limits<float>::infinity()) { lightRay->direction->normalize(); r->direction->normalize(); Vector3 h = (lightRay->direction)->subtract(r->direction); h.normalize(); for (int i = 0; i < 3; i++) { //Diffuse Lighting float dot = (lightRay->direction)->dot(result->normal)/* / (lightRay->direction->mag() * result->normal->mag())*/; result->mat.color[i] = result->mat.color[i] + lightColor[i] * result->mat.diffuseColor[i] * max(0, dot); //Specular Lighting float hnorm = pow(h.dot(result->normal), result->mat.specExponent); result->mat.color[i] = result->mat.color[i] + lightColor[i] * result->mat.specularColor[i] * hnorm; } } //Reflected Light if (result->mat.specularColor[0] > 0 || result->mat.specularColor[1] > 0 || result->mat.specularColor[0] > 2) { Ray* reflectRay = new Ray(); *(reflectRay->start) = *(result->point); *(reflectRay->direction) = *(r->direction); float dn = r->direction->dot(result->normal); *(reflectRay->direction) = reflectRay->direction->subtract(&(result->normal->multiply(2 * dn))); //ewwwwwwwwwwwwww Solid::Intercept* reflectHit = raycast(reflectRay, depth - 1); for (int i = 0; i < 3; i++) { result->mat.color[i] = result->mat.color[i] + result->mat.specularColor[i] * reflectHit->mat.color[i]; } delete reflectRay; delete reflectHit; } //Refraction if (result->mat.alpha > 0) { Ray* refractedRay = new Ray(); //Find point refracted through object *(refractedRay->start) = *(result->point); *(refractedRay->direction) = r->direction->refract(result->normal, 1.0, result->mat.refractIndex); refractedRay->direction->normalize(); Solid::Intercept* refractHit = sceneHit(refractedRay); //Find exit ray from object *(refractedRay->start) = *(refractHit->point); *(refractedRay->direction) = refractedRay->direction->refract(&(refractHit->normal->multiply(-1)), result->mat.refractIndex, 1.0); refractedRay->direction->normalize(); if (refractedRay->direction->x != 0 && refractedRay->direction->y != 0 && refractedRay->direction->z != 0) { refractHit = raycast(refractedRay, depth - 1); for (int i = 0; i < 3; i++) { result->mat.color[i] = (1 - result->mat.alpha) * result->mat.color[i] + result->mat.alpha * result->mat.diffuseColor[i] * refractHit->mat.color[i]; } } delete refractedRay; delete refractHit; } delete lightRay; return result; } else { result->mat.color[0] = 0.1; result->mat.color[1] = 0.1; result->mat.color[2] = 0.1; return result; } }
// create and display volume rendered image void createlocalimage(int rank) { int i=0, j=0; float u, v; float du, dv; ray3f ray, tray; vector3f incri, incrj; color4f color; // initialize framebuffer memset(colorbuf, 0, sizeof(color4f)*viewport.w*viewport.h); // initiliaze deltas for ray stepping du = (viewvolume.right - viewvolume.left)/viewport.w; dv = (viewvolume.top - viewvolume.bottom)/viewport.h; deltasample = fmin(du, dv); // buffers index int fbindex = 0; // cast rays for each pixel in window int istrt = (int) (aabb.wincoord.y - 0.5f); int istop = (int) (aabb.wincoord.y + aabb.wincoord.h + 1.0f); int jstrt = (int) (aabb.wincoord.x - 0.5f); int jstop = (int) (aabb.wincoord.x + aabb.wincoord.w + 1.0f); #ifdef IVR_DEBUG fprintf(stderr, "rank=%d, istrt=%d, istop=%d, jstrt=%d, jstop=%d\n", rank, istrt, istop, jstrt, jstop); #endif // DEBUG /* istrt = (int) (0); istop = (int) (viewport.h); jstrt = (int) (0); jstop = (int) (viewport.w); */ // END DEBUG // initial ray direction v = viewvolume.bottom + istrt * dv + dv/2.0f; u = viewvolume.left + jstrt * du - du/2.0f; ray.dir.u = u; ray.dir.v = v; ray.dir.n = -camera.e.n; buildray(du, dv, &incri, &incrj, &ray); #pragma omp parallel for private(j, color, fbindex, tray) firstprivate(ray) for (i=istrt; i < istop; i++) { tray.orig.x = ray.orig.x; tray.orig.y = ray.orig.y; tray.orig.z= ray.orig.z; tray.dir.x = ray.dir.x + incri.x*(i-istrt); tray.dir.y = ray.dir.y + incri.y*(i-istrt); tray.dir.z = ray.dir.z + incri.z*(i-istrt); for (j=jstrt; j < jstop; j++) { // default color is black color.r = color.g = color.b = color.a = 0.0f; // increment for next ray; SIMD this tray.dir.x += incrj.x; tray.dir.y += incrj.y; tray.dir.z += incrj.z; raycast(tray, &color); // increment color buffer pointer fbindex = i * viewport.w + j; colorbuf[fbindex].r = color.r; colorbuf[fbindex].g = color.g; colorbuf[fbindex].b = color.b; colorbuf[fbindex].a = color.a; } } #ifdef LOCAL // Load array to 0 0 0 to set the raster origition to (0, 0, 0) GLfloat rp[3]; rp[0] = 0.0f; rp[1] = 0.0f; rp[2] = 0.0f; // Set the raster origition and pass the array of colours to drawPixels // use colors directly, don't need to copy. glRasterPos3fv(rp); glDrawPixels(winwidth, winheight, GL_RGBA, GL_FLOAT, (GLvoid *)colorbuf); fprintf(stderr,"w=%d, h=%d\n", winwidth, winheight); #endif return; }