Esempio n. 1
0
int main(int argc, char*argv[])
{
	EventManager::Initialize();
	Renderer::Initialize();

	World world;

	// If Running on Windows Then Play Background Music
	// PlaySound(TEXT("../Assets/Sounds/Danger-Zone.wav"), NULL, SND_FILENAME | SND_ASYNC | SND_LOOP);

	/*loading screen block*/ {

		LoadingScreen loadingScreen;
		loadingScreen.Draw();

		//	world.LoadScene("../Assets/Scenes/AnimatedSceneWithParticles.scene");
		//	world.LoadScene("../Assets/Scenes/AnimatedScene.scene");
		//	world.LoadScene("../Assets/Scenes/Spline.scene");
		//	world.LoadScene("../Assets/Scenes/StaticScene.scene");
		//	world.LoadScene("../Assets/Scenes/CoordinateSystem.scene");
		//	world.LoadScene("../Assets/Scenes/CollisionDemo.scene");
		//	world.LoadScene("../Assets/Scenes/Animal.scene");
		//	world.LoadScene("../Assets/Scenes/StaticScene.scene");
		//	world.LoadScene("../Assets/Scenes/CoordinateSystem.scene");
		//	world.LoadScene("../Assets/Scenes/Discoball.scene");
		//	world.LoadScene("../Assets/Scenes/Player.scene");
			world.LoadScene();
	}

	double fps = 1.0f / FPS;
	double dtStep = 1.0f / PHYSICS_FPS;
	
	double dtAcc = 0;

#ifdef DEBUG_FRAME_RATE
	long seconds = 0;
	double currentTime = 0.0;
	long remainingMsAcc = 0;
	long sleepCtr = 0;
#endif

	// Reset the polled values in the EventManager because scene loading is long.
	EventManager::Update();

	do
	{
		double start = glfwGetTime();

		// Update Event Manager - Frame time / input / events processing 
		EventManager::Update();

		float dt = EventManager::GetFrameTime();

		// Apply fixed delta time steps to each world update,
		// and drawing can be done if at least 1 world update was done.
		dtAcc += dt;
		bool draw = false;
		while (dtAcc >= dtStep) {
			dtAcc -= dtStep;
			world.Update(dtStep);
			draw = true;
		}

		if (draw) {
			world.Draw();
		}

#ifndef DEBUG_FRAME_RATE
		// Each frame should be "fps" seconds long.
		// If updating and rendering took less than fps seconds long then sleep for the remainder.
		int remainingMs = (start + fps - glfwGetTime()) * 1000;
		if (remainingMs > 0) {
			SLEEP_FUNC(remainingMs);
		}
#else
		long remainingMs = (start + fps - glfwGetTime()) * 1000;
		remainingMsAcc += remainingMs;

		currentTime += dt;
		if (currentTime - seconds >= 1) {
			seconds++;

			double avgRemaingMs = remainingMsAcc / (double)sleepCtr;
			cout << "avg remaining ms " << avgRemaingMs << endl;

			remainingMsAcc = 0;
			sleepCtr = 0;
		}

		if (remainingMs < 0) {
			cout << "OVER FRAME TIME BY " << abs(remainingMs) << " ms" << endl;
		}

		if (remainingMs > 0) {
			sleepCtr++;
			SLEEP_FUNC(remainingMs);
		}
#endif
	}
	while(EventManager::ExitRequested() == false);

	Renderer::Shutdown();
	EventManager::Shutdown();

	return 0;
}
int OrthographicGridPathfinder::getGridWidth()
{
    GameStateManager *gsm = game->getGSM();
    World *world = gsm->getWorld();
    return world->getWorldWidth()/numColumns;
}
void GuidedGraspPlanningTask::start()
{
  //get the details of the planning task itself
  if (!mDBMgr->GetPlanningTaskRecord(mRecord.taskId, &mPlanningTask)) {
    DBGA("Failed to get planning record for task");
    mStatus = ERROR;
    return;
  }

  World *world = graspItGUI->getIVmgr()->getWorld();

  //check if the currently selected hand is the same as the one we need
  //if not, load the hand we need
  if (world->getCurrentHand() && 
      GraspitDBGrasp::getHandDBName(world->getCurrentHand()) == QString(mPlanningTask.handName.c_str())) {
    DBGA("Grasp Planning Task: using currently loaded hand");
    mHand = world->getCurrentHand();
  } else {
    QString handPath = GraspitDBGrasp::getHandGraspitPath(QString(mPlanningTask.handName.c_str()));
    handPath = QString(getenv("GRASPIT")) + handPath;
    DBGA("Grasp Planning Task: loading hand from " << handPath.latin1());	      
    mHand = static_cast<Hand*>(world->importRobot(handPath));
    if ( !mHand ) {
      DBGA("Failed to load hand");
      mStatus = ERROR;
      return;
    }
  }
  //check for virtual contacts
  if (mHand->getNumVirtualContacts()==0) {
    DBGA("Specified hand does not have virtual contacts defined");
    mStatus = ERROR;
    return;
  }
  
  //load the object
  GraspitDBModel *model = static_cast<GraspitDBModel*>(mPlanningTask.model);
  if (model->load(world) != SUCCESS) {
    DBGA("Grasp Planning Task: failed to load model");
    mStatus = ERROR;
    return;
  }
  mObject = model->getGraspableBody();
  mObject->addToIvc();
  world->addBody(mObject);
  
  //initialize the planner
  GraspPlanningState seed(mHand);
  seed.setObject(mObject);
  seed.setPositionType(SPACE_AXIS_ANGLE);
  seed.setPostureType(POSE_EIGEN);
  seed.setRefTran(mObject->getTran());
  seed.reset();
  
  mPlanner = new GuidedPlanner(mHand);
  mPlanner->setModelState(&seed);	
  mPlanner->setContactType(CONTACT_PRESET);

  if (mPlanningTask.taskTime >= 0) mPlanner->setMaxTime(mPlanningTask.taskTime);
  else mPlanner->setMaxTime(-1);
  
  QObject::connect(mPlanner, SIGNAL(update()), this, SLOT(plannerUpdate()));
  QObject::connect(mPlanner, SIGNAL(complete()), this, SLOT(plannerComplete()));

  if (!mPlanner->resetPlanner()) {
    DBGA("Grasp Planning Task: failed to reset planner");
    mStatus = ERROR;
    return;
  }
  mLastSolution = 0;
  mPlanner->startPlanner();
  mStatus = RUNNING;
}
Esempio n. 4
0
void IrrDriver::renderFixed(float dt)
{
    World *world = World::getWorld(); // Never NULL.

    m_video_driver->beginScene(/*backBuffer clear*/ true, /*zBuffer*/ true,
                               world->getClearColor());

    irr_driver->getVideoDriver()->enableMaterial2D();

    RaceGUIBase *rg = world->getRaceGUI();
    if (rg) rg->update(dt);


    for(unsigned int i=0; i<Camera::getNumCameras(); i++)
    {
        Camera *camera = Camera::getCamera(i);

        std::ostringstream oss;
        oss << "drawAll() for kart " << i;
        PROFILER_PUSH_CPU_MARKER(oss.str().c_str(), (i+1)*60,
                                 0x00, 0x00);
        camera->activate();
        rg->preRenderCallback(camera);   // adjusts start referee

        m_renderpass = ~0;
        m_scene_manager->drawAll();

        PROFILER_POP_CPU_MARKER();

        // Note that drawAll must be called before rendering
        // the bullet debug view, since otherwise the camera
        // is not set up properly. This is only used for
        // the bullet debug view.
        if (UserConfigParams::m_artist_debug_mode)
            World::getWorld()->getPhysics()->draw();
    }   // for i<world->getNumKarts()

    // Set the viewport back to the full screen for race gui
    m_video_driver->setViewPort(core::recti(0, 0,
                                            UserConfigParams::m_width,
                                            UserConfigParams::m_height));

    for(unsigned int i=0; i<Camera::getNumCameras(); i++)
    {
        Camera *camera = Camera::getCamera(i);
        std::ostringstream oss;
        oss << "renderPlayerView() for kart " << i;

        PROFILER_PUSH_CPU_MARKER(oss.str().c_str(), 0x00, 0x00, (i+1)*60);
        rg->renderPlayerView(camera, dt);
        PROFILER_POP_CPU_MARKER();

    }  // for i<getNumKarts

    // Either render the gui, or the global elements of the race gui.
    GUIEngine::render(dt);

    // Render the profiler
    if(UserConfigParams::m_profiler_enabled)
    {
        PROFILER_DRAW();
    }

#ifdef DEBUG
    drawDebugMeshes();
#endif

    m_video_driver->endScene();
}
Esempio n. 5
0
//-----------------------------------------------------------------------------
void SoccerWorld::onCheckGoalTriggered(bool first_goal)
{
    if (isRaceOver())
        return;

    if (m_can_score_points)
    {
        m_team_goals[first_goal ? 0 : 1]++;

        World *world = World::getWorld();
        world->setPhase(WorldStatus::GOAL_PHASE);
        m_goal_sound->play();
        if(m_lastKartToHitBall != -1)
        {
            if(first_goal)
            {
                m_redScorers.push_back(m_lastKartToHitBall);
                if(race_manager->hasTimeTarget())
                    m_redScoreTimes.push_back(race_manager->getTimeTarget() - world->getTime());
                else
                    m_redScoreTimes.push_back(world->getTime());
            }
            else
            {
                m_blueScorers.push_back(m_lastKartToHitBall);
                if(race_manager->hasTimeTarget())
                    m_blueScoreTimes.push_back(race_manager->getTimeTarget() - world->getTime());
                else
                    m_blueScoreTimes.push_back(world->getTime());
            }
        }
    }

    // Reset original positions for the soccer balls
    TrackObjectManager* tom = getTrack()->getTrackObjectManager();
    assert(tom);

    PtrVector<TrackObject>& objects = tom->getObjects();
    for(unsigned int i=0; i<objects.size(); i++)
    {
        TrackObject* obj = objects.get(i);
        if(!obj->isSoccerBall())
            continue;

        obj->reset();
        obj->getPhysicalObject()->reset();
    }

    //Resetting the ball triggers the goal check line one more time.
    //This ensures that only one goal is counted, and the second is ignored.
    m_can_score_points = !m_can_score_points;

    //for(int i=0 ; i < getNumKarts() ; i++

    /*if(World::getWorld()->getTrack()->isAutoRescueEnabled() &&
        !getKartAnimation() && fabs(getRoll())>60*DEGREE_TO_RAD &&
                              fabs(getSpeed())<3.0f                )
    {
        new RescueAnimation(this, true);
    }*/

    // TODO: rescue the karts
}   // onCheckGoalTriggered
Esempio n. 6
0
	void Server::broadcastCollectItem(Entities::Pickup* pi, Entities::LivingEntity* e)
	{
		World* w = e->getWorld();
		for (size_t i = 0; i < w->playerids.size(); i++)
			w->getPlayer(w->playerids.at(i))->getClientCon()->sendCollectItem(pi, e);
	}
    void IntersectorShortStack::Process(World const& world)
    {

        // If something has been changed we need to rebuild BVH
        if (!m_bvh || world.has_changed() || world.GetStateChange() != ShapeImpl::kStateChangeNone)
        {
            if (m_bvh)
            {
                m_device->DeleteBuffer(m_gpudata->bvh);
                m_device->DeleteBuffer(m_gpudata->vertices);
            }

            // Check if we can allocate enough stack memory
            Calc::DeviceSpec spec;
            m_device->GetSpec(spec);
            if (spec.max_alloc_size <= kMaxBatchSize * kMaxStackSize * sizeof(int))
            {
                throw ExceptionImpl("fatbvh accelerator can't allocate enough stack memory, try using bvh instead");
            }

            int numshapes = (int)world.shapes_.size();
            int numvertices = 0;
            int numfaces = 0;

            // This buffer tracks mesh start index for next stage as mesh face indices are relative to 0
            std::vector<int> mesh_vertices_start_idx(numshapes);
            std::vector<int> mesh_faces_start_idx(numshapes);

            auto builder = world.options_.GetOption("bvh.builder");
            auto splits = world.options_.GetOption("bvh.sah.use_splits");
            auto maxdepth = world.options_.GetOption("bvh.sah.max_split_depth");
            auto overlap = world.options_.GetOption("bvh.sah.min_overlap");
            auto tcost = world.options_.GetOption("bvh.sah.traversal_cost");
            auto node_budget = world.options_.GetOption("bvh.sah.extra_node_budget");
            auto nbins = world.options_.GetOption("bvh.sah.num_bins");

            bool use_sah = false;
            bool use_splits = false;
            int max_split_depth = maxdepth ? (int)maxdepth->AsFloat() : 10;
            int num_bins = nbins ? (int)nbins->AsFloat() : 64;
            float min_overlap = overlap ? overlap->AsFloat() : 0.05f;
            float traversal_cost = tcost ? tcost->AsFloat() : 10.f;
            float extra_node_budget = node_budget ? node_budget->AsFloat() : 0.5f;

            if (builder && builder->AsString() == "sah")
            {
                use_sah = true;
            }

            if (splits && splits->AsFloat() > 0.f)
            {
                use_splits = true;
            }

            m_bvh.reset(use_splits ?
                new SplitBvh(traversal_cost, num_bins, max_split_depth, min_overlap, extra_node_budget) :
                new Bvh(traversal_cost, num_bins, use_sah)
            );

            // Partition the array into meshes and instances
            std::vector<Shape const*> shapes(world.shapes_);

            auto firstinst = std::partition(shapes.begin(), shapes.end(),
                [&](Shape const* shape)
            {
                return !static_cast<ShapeImpl const*>(shape)->is_instance();
            });

            // Count the number of meshes
            int nummeshes = (int)std::distance(shapes.begin(), firstinst);
            // Count the number of instances
            int numinstances = (int)std::distance(firstinst, shapes.end());

            for (int i = 0; i < nummeshes; ++i)
            {
                Mesh const* mesh = static_cast<Mesh const*>(shapes[i]);

                mesh_faces_start_idx[i] = numfaces;
                mesh_vertices_start_idx[i] = numvertices;

                numfaces += mesh->num_faces();
                numvertices += mesh->num_vertices();
            }

            for (int i = nummeshes; i < nummeshes + numinstances; ++i)
            {
                Instance const* instance = static_cast<Instance const*>(shapes[i]);
                Mesh const* mesh = static_cast<Mesh const*>(instance->GetBaseShape());

                mesh_faces_start_idx[i] = numfaces;
                mesh_vertices_start_idx[i] = numvertices;

                numfaces += mesh->num_faces();
                numvertices += mesh->num_vertices();
            }


            // We can't avoild allocating it here, since bounds aren't stored anywhere
            std::vector<bbox> bounds(numfaces);

            // We handle meshes first collecting their world space bounds
#pragma omp parallel for
            for (int i = 0; i < nummeshes; ++i)
            {
                Mesh const* mesh = static_cast<Mesh const*>(shapes[i]);

                for (int j = 0; j < mesh->num_faces(); ++j)
                {
                    // Here we directly get world space bounds
                    mesh->GetFaceBounds(j, false, bounds[mesh_faces_start_idx[i] + j]);
                }
            }

            // Then we handle instances. Need to flatten them into actual geometry.
#pragma omp parallel for
            for (int i = nummeshes; i < nummeshes + numinstances; ++i)
            {
                Instance const* instance = static_cast<Instance const*>(shapes[i]);
                Mesh const* mesh = static_cast<Mesh const*>(instance->GetBaseShape());

                // Instance is using its own transform for base shape geometry
                // so we need to get object space bounds and transform them manually
                matrix m, minv;
                instance->GetTransform(m, minv);

                for (int j = 0; j < mesh->num_faces(); ++j)
                {
                    bbox tmp;
                    mesh->GetFaceBounds(j, true, tmp);
                    bounds[mesh_faces_start_idx[i] + j] = transform_bbox(tmp, m);
                }
            }

            m_bvh->Build(&bounds[0], numfaces);

#ifdef RR_PROFILE
            m_bvh->PrintStatistics(std::cout);
#endif

            // Check if the tree height is reasonable
            if (m_bvh->GetHeight() >= kMaxStackSize)
            {
                m_bvh.reset(nullptr);
                throw ExceptionImpl("fatbvh accelerator can cause stack overflow for this scene, try using bvh instead");
            }

            FatNodeBvhTranslator translator;
            translator.Process(*m_bvh);

            // Update GPU data

            // Create vertex buffer
            {
                // Vertices
                m_gpudata->vertices = m_device->CreateBuffer(numvertices * sizeof(float3), Calc::BufferType::kRead);

                // Get the pointer to mapped data
                float3* vertexdata = nullptr;
                Calc::Event* e = nullptr;

                m_device->MapBuffer(m_gpudata->vertices, 0, 0, numvertices * sizeof(float3), Calc::MapType::kMapWrite, (void**)&vertexdata, &e);

                e->Wait();
                m_device->DeleteEvent(e);

                // Here we need to put data in world space rather than object space
                // So we need to get the transform from the mesh and multiply each vertex
                matrix m, minv;

#pragma omp parallel for
                for (int i = 0; i < nummeshes; ++i)
                {
                    // Get the mesh
                    Mesh const* mesh = static_cast<Mesh const*>(shapes[i]);
                    // Get vertex buffer of the current mesh
                    float3 const* myvertexdata = mesh->GetVertexData();
                    // Get mesh transform
                    mesh->GetTransform(m, minv);

                    //#pragma omp parallel for
                    // Iterate thru vertices multiply and append them to GPU buffer
                    for (int j = 0; j < mesh->num_vertices(); ++j)
                    {
                        vertexdata[mesh_vertices_start_idx[i] + j] = transform_point(myvertexdata[j], m);
                    }
                }

#pragma omp parallel for
                for (int i = nummeshes; i < nummeshes + numinstances; ++i)
                {
                    Instance const* instance = static_cast<Instance const*>(shapes[i]);
                    // Get the mesh
                    Mesh const* mesh = static_cast<Mesh const*>(instance->GetBaseShape());
                    // Get vertex buffer of the current mesh
                    float3 const* myvertexdata = mesh->GetVertexData();
                    // Get mesh transform
                    instance->GetTransform(m, minv);

                    //#pragma omp parallel for
                    // Iterate thru vertices multiply and append them to GPU buffer
                    for (int j = 0; j < mesh->num_vertices(); ++j)
                    {
                        vertexdata[mesh_vertices_start_idx[i] + j] = transform_point(myvertexdata[j], m);
                    }
                }

                m_device->UnmapBuffer(m_gpudata->vertices, 0, vertexdata, &e);
                e->Wait();
                m_device->DeleteEvent(e);
            }

            // Create face buffer
            {
                
                // This number is different from the number of faces for some BVHs 
                auto numindices = m_bvh->GetNumIndices();
                std::vector<FatNodeBvhTranslator::Face> facedata(numindices);

                // Here the point is to add mesh starting index to actual index contained within the mesh,
                // getting absolute index in the buffer.
                // Besides that we need to permute the faces accorningly to BVH reordering, whihc
                // is contained within bvh.primids_
                int const* reordering = m_bvh->GetIndices();
                for (int i = 0; i < numindices; ++i)
                {
                    int indextolook4 = reordering[i];

                    // We need to find a shape corresponding to current face
                    auto iter = std::upper_bound(mesh_faces_start_idx.cbegin(), mesh_faces_start_idx.cend(), indextolook4);

                    // Find the index of the shape
                    int shapeidx = static_cast<int>(std::distance(mesh_faces_start_idx.cbegin(), iter) - 1);

                    // Get the mesh directly or out of instance
                    Mesh const* mesh = nullptr;
                    if (shapeidx < nummeshes)
                    {
                        mesh = static_cast<Mesh const*>(shapes[shapeidx]);
                    }
                    else
                    {
                        mesh = static_cast<Mesh const*>(static_cast<Instance const*>(shapes[shapeidx])->GetBaseShape());
                    }

                    // Get vertex buffer of the current mesh
                    Mesh::Face const* myfacedata = mesh->GetFaceData();
                    // Find face idx
                    int faceidx = indextolook4 - mesh_faces_start_idx[shapeidx];
                    // Find mesh start idx
                    int mystartidx = mesh_vertices_start_idx[shapeidx];

                    // Copy face data to GPU buffer
                    facedata[i].idx[0] = myfacedata[faceidx].idx[0] + mystartidx;
                    facedata[i].idx[1] = myfacedata[faceidx].idx[1] + mystartidx;
                    facedata[i].idx[2] = myfacedata[faceidx].idx[2] + mystartidx;

                    facedata[i].shapeidx = shapes[shapeidx]->GetId();
                    facedata[i].shape_mask = shapes[shapeidx]->GetMask();
                    facedata[i].id = faceidx;
                }

                translator.InjectIndices(&facedata[0]);
            }

            // Copy translated nodes first
            m_gpudata->bvh = m_device->CreateBuffer(translator.nodes_.size() * sizeof(FatNodeBvhTranslator::Node), Calc::BufferType::kRead, &translator.nodes_[0]);

            // Stack
            m_gpudata->stack = m_device->CreateBuffer(kMaxBatchSize*kMaxStackSize, Calc::BufferType::kWrite);

            // Make sure everything is commited
            m_device->Finish(0);
        }
    }
Esempio n. 8
0
int main(int argc, char *argv[])
{
    using namespace Sord;

    int num = 1;

    if (argc > 1) {
        num = atoi(argv[1]);
    }

    World world;

    world.add_prefix("rdf", RDF(""));
    world.add_prefix("maths", MATHS(""));
    world.add_prefix("spatial", SPATIAL(""));
    world.add_prefix("tracking", TRACKING(""));
    world.add_prefix("vom", VOM(""));
    world.add_prefix("mea", MEA(""));
    world.add_prefix("xsd", XSD(""));

    Model model(world, "http://test.arvida.de/");

    std::cout << "Producing " << num << " poses" << std::endl;

    MIDDLEWARENEWSBRIEF_PROFILER_TIME_TYPE start, finish, elapsed;

    start = MIDDLEWARENEWSBRIEF_PROFILER_GET_TIME;

    for (int i = 0; i < num; ++i)
    {
        const std::string uuid_url = "http://test.arvida.de/UUID" + std::to_string(i);

        model.add_statement(
            URI(world, uuid_url),
            URI(world, RDF("type")),
            URI(world, SPATIAL("SpatialRelationship")));

        {
            Node n1 = Node::blank_id(world);

            model.add_statement(
                URI(world, uuid_url),
                URI(world, SPATIAL("sourceCoordinateSystem")),
                n1
            );

            model.add_statement(
                n1,
                URI(world, RDF("type")),
                URI(world, MATHS("LeftHandedCartesianCoordinateSystem3D")));
        }


        {
            Node n1 = Node::blank_id(world);

            model.add_statement(
                URI(world, uuid_url),
                URI(world, SPATIAL("targetCoordinateSystem")),
                n1
            );

            model.add_statement(
                n1,
                URI(world, RDF("type")),
                URI(world, MATHS("RightHandedCartesianCoordinateSystem2D"))
            );
        }

        URI xsd_double(world, XSD("double"));

        {

            // translation
            Node n1 = Node::blank_id(world);
            Node n2 = Node::blank_id(world);

            model.add_statement(
                URI(world, uuid_url),
                URI(world, SPATIAL("translation")),
                n1
            );

            model.add_statement(
                n1,
                URI(world, RDF("type")),
                URI(world, SPATIAL("Translation3D"))
            );

            model.add_statement(
                n1,
                URI(world, VOM("quantityValue")),
                n2
            );

            model.add_statement(
                n2,
                URI(world, RDF("type")),
                URI(world, MATHS("Vector3D"))
            );



            model.add_statement(
                n2,
                URI(world, MATHS("x")),
                double_node(world, 1)
            );

            model.add_statement(
                n2,
                URI(world, MATHS("y")),
                double_node(world, 2)
            );

            model.add_statement(
                n2,
                URI(world, MATHS("z")),
                double_node(world, 3)
            );

        }

        {
            // rotation

            Node n1 = Node::blank_id(world);
            Node n2 = Node::blank_id(world);

            model.add_statement(
                URI(world, uuid_url),
                URI(world, SPATIAL("rotation")),
                n1);

            model.add_statement(
                n1,
                URI(world, RDF("type")),
                URI(world, SPATIAL("Rotation3D"))
            );

            model.add_statement(
                n1,
                URI(world, VOM("quantityValue")),
                n2);

            model.add_statement(
                n2,
                URI(world, RDF("type")),
                URI(world, MATHS("Quaternion"))
            );

            model.add_statement(
                n2,
                URI(world, RDF("type")),
                URI(world, MATHS("Vector4D"))
            );

            model.add_statement(
                n2,
                URI(world, MATHS("x")),
                double_node(world, 1));


            model.add_statement(n2,
                URI(world, MATHS("y")),
                double_node(world, 1)
            );


            model.add_statement(
                n2,
                URI(world, MATHS("z")),
                double_node(world, 1)
            );

            model.add_statement(
                n2,
                URI(world, MATHS("w")),
                double_node(world, 1)
            );
        }

    }

    finish = MIDDLEWARENEWSBRIEF_PROFILER_GET_TIME;

    elapsed = MIDDLEWARENEWSBRIEF_PROFILER_DIFF(finish, start);
    printf("\n\nElapsed %s for model construction: %i (%f per pose)\n\n\n",
           MIDDLEWARENEWSBRIEF_PROFILER_TIME_UNITS,
           elapsed, double(elapsed)/num);

    std::cout << "Writing poses to file pose_sordmm.ttl" << std::endl;

    start = MIDDLEWARENEWSBRIEF_PROFILER_GET_TIME;

    model.write_to_file("pose_sordmm.ttl", SERD_TURTLE,
        (SerdStyle)(SERD_STYLE_ABBREVIATED | SERD_STYLE_CURIED | SERD_STYLE_RESOLVED));

    finish = MIDDLEWARENEWSBRIEF_PROFILER_GET_TIME;

    elapsed = MIDDLEWARENEWSBRIEF_PROFILER_DIFF(finish, start);
    printf("\n\nElapsed %s for model output: %i (%f per pose)\n\n\n",
           MIDDLEWARENEWSBRIEF_PROFILER_TIME_UNITS,
           elapsed, double(elapsed)/num);

    /* keep gcc -Wall happy */
    return(0);
}
Esempio n. 9
0
    void WorldTest::simulationTestUncached() {
        World* world = new World(Vector3(200000, 200000, 200000));
        world->setUseCollisionCaching(false);
        Vector3 boxDimensions(10, 10, 10);
        Proxy* box1 = world->createProxy(new Box(boxDimensions));
        //Proxy* childBox = world->createProxy(new Box(boxDimensions));
        //childBox->translate(5, 5, 5);
        //box->addChild(childBox);

        world->addProxy(box1);

        Proxy* box2 = world->createProxy(new Box(boxDimensions));
        box2->translate(0, -20, 0);
        world->addProxy(box2);

        Proxy* box3 = world->createProxy(new Box(boxDimensions)); //always colliding with box2
        box3->translate(5, -25, 0);
        world->addProxy(box3);

        
        Proxy* moveBox = world->createProxy(new Box(Vector3(10, 50, 10)));
        moveBox->translate(20, -25, 0); //starting in no-collision state
        world->addProxy(moveBox);

        //WorldCollisions coll;
        
        world->prepareSimulation();
//std::cout << "-----------Starting simulation test-----------"<<std::endl;
//std::cout << "doing pre-move collisionCheck"<<std::endl;
        //test and ensure 1 BPC and rigid C
        WorldCollisions coll0 = world->calculateAllCollisions();
        CPPUNIT_ASSERT_EQUAL(1,
                (int)coll0.getBroadPhaseCollisions()->getResults().size());
        CPPUNIT_ASSERT_EQUAL(1, (int)coll0.getRigidBoundingVolumeCollisions().size());

        //Step 1 -> move moveBox to collidy with box3
//std::cout <<std::endl<< "doing step 1 - move in to collide with box3"<<std::endl;
        moveBox->translate(-6, 0, 0);

        //ensure 2 BPC/RC
        WorldCollisions coll1  = world->calculateAllCollisions();
        CPPUNIT_ASSERT_EQUAL(2,
                (int)coll1.getBroadPhaseCollisions()->getResults().size());
        CPPUNIT_ASSERT_EQUAL(2, (int)coll1.getRigidBoundingVolumeCollisions().size());

        //Step 2-> move to collide with all boxes
//std::cout <<std::endl<<"doing step 2 - move further to collide with all"<<std::endl;
        moveBox->translate(-5, 0, 0);
        //ensure 4 collisions
        WorldCollisions coll2  = world->calculateAllCollisions();
        CPPUNIT_ASSERT_EQUAL(4,
                (int)coll2.getBroadPhaseCollisions()->getResults().size());
        CPPUNIT_ASSERT_EQUAL(4, (int)coll2.getRigidBoundingVolumeCollisions().size());

        //Step 3-> move out again
//std::cout << std::endl<<"doing step 3 - moving out"<<std::endl;
        moveBox->translate(11, 0, 0);
        //ensure 1 collisions
        WorldCollisions coll3  = world->calculateAllCollisions();
        CPPUNIT_ASSERT_EQUAL(1,
                (int)coll3.getBroadPhaseCollisions()->getResults().size());
        CPPUNIT_ASSERT_EQUAL(1, (int)coll3.getRigidBoundingVolumeCollisions().size());

        //Step 4-> move in again
//std::cout << std::endl<<"doing step 4 - moving back in"<<std::endl;
        moveBox->translate(-11, 0, 0);
        //ensure 4 collisions
        WorldCollisions coll4  = world->calculateAllCollisions();
        CPPUNIT_ASSERT_EQUAL(4,
                (int)coll4.getBroadPhaseCollisions()->getResults().size());
        CPPUNIT_ASSERT_EQUAL(4, (int)coll4.getRigidBoundingVolumeCollisions().size());

        delete world;
    }
Esempio n. 10
0
//-----------------------------------------------------------------------------
void InputManager::handleStaticAction(int key, int value)
{
    static bool control_is_pressed = false;
    World *world = World::getWorld();

    // When no players... a cutscene
    if (race_manager->getNumPlayers() == 0 && world != NULL && value > 0 &&
        (key == KEY_SPACE || key == KEY_RETURN))
    {
        world->onFirePressed(NULL);
    }

    switch (key)
    {
#ifdef DEBUG
        // Special debug options for profile mode: switch the 
        // camera to show a different kart.
        case KEY_KEY_1:
        case KEY_KEY_2:
        case KEY_KEY_3:
        case KEY_KEY_4:
        case KEY_KEY_5:
        case KEY_KEY_6:
        case KEY_KEY_7:
        case KEY_KEY_8:
        case KEY_KEY_9:
        {
            if(!ProfileWorld::isProfileMode() || !world) break;
            int kart_id = key - KEY_KEY_1;
            if(kart_id<0 || kart_id>=(int)world->getNumKarts()) break;
            for(unsigned int i=0; i<world->getNumKarts(); i++)
            {
                if(world->getKart(i)->getCamera())
                {
                    world->getKart(i)->getCamera()
                                     ->changeOwner(world->getKart(kart_id));

                }
            }
            break;
        }
#endif
        case KEY_CONTROL:
        case KEY_RCONTROL:
        case KEY_LCONTROL:
        case KEY_RMENU:
        case KEY_LMENU:
        case KEY_LWIN:
            control_is_pressed = value!=0;
            break;

        case KEY_KEY_I:
        {
            if (!world || !UserConfigParams::m_artist_debug_mode) break;
            
            AbstractKart* kart = world->getLocalPlayerKart(0);
            if (kart == NULL) break;
            
            kart->flyUp();
            break;
        }
        case KEY_KEY_K:
        {
            if (!world || !UserConfigParams::m_artist_debug_mode) break;
            
            AbstractKart* kart = world->getLocalPlayerKart(0);
            if (kart == NULL) break;
            
            kart->flyDown();
            break;
        }
        case KEY_PRINT:
            if (value != 0)
                irr_driver->requestScreenshot();
            break;
            
        case KEY_F1:
            if (UserConfigParams::m_artist_debug_mode && world)
            {
                AbstractKart* kart = world->getLocalPlayerKart(0);
                kart->setPowerup(PowerupManager::POWERUP_BUBBLEGUM, 10000);
#ifdef FORCE_RESCUE_ON_FIRST_KART
                // Can be useful for debugging places where the AI gets into
                // a rescue loop: rescue, drive, crash, rescue to same place
                world->getKart(0)->forceRescue();
#endif
                // FIXME: remove after testing the animated plunger
                world->getLocalPlayerKart(0)->blockViewWithPlunger();
            }
            break;
        case KEY_F2:
            if (UserConfigParams::m_artist_debug_mode && world)
            {
                AbstractKart* kart = world->getLocalPlayerKart(0);
                kart->setPowerup(PowerupManager::POWERUP_PLUNGER, 10000);
            }
            break;
        case KEY_F3:
            if (UserConfigParams::m_artist_debug_mode && world)
            {
                AbstractKart* kart = world->getLocalPlayerKart(0);
                kart->setPowerup(PowerupManager::POWERUP_CAKE, 10000);
            }
            break;
        case KEY_F4:
            if (UserConfigParams::m_artist_debug_mode && world)
            {
                AbstractKart* kart = world->getLocalPlayerKart(0);
                kart->setPowerup(PowerupManager::POWERUP_SWITCH, 10000);
            }
            break;
        case KEY_F5:
            if (UserConfigParams::m_artist_debug_mode && world)
            {
                AbstractKart* kart = world->getLocalPlayerKart(0);
                kart->setPowerup(PowerupManager::POWERUP_BOWLING, 10000);
            }
            break;
        case KEY_F6:
            if (UserConfigParams::m_artist_debug_mode && world)
            {
                AbstractKart* kart = world->getLocalPlayerKart(0);
                kart->setPowerup(PowerupManager::POWERUP_BUBBLEGUM, 10000);
            }
            break;
        case KEY_F7:
            if (UserConfigParams::m_artist_debug_mode && world)
            {
                AbstractKart* kart = world->getLocalPlayerKart(0);
                kart->setPowerup(PowerupManager::POWERUP_ZIPPER, 10000);
            }
            break;
        
        case KEY_F8:
            if (UserConfigParams::m_artist_debug_mode && value && world)
            {
                if (control_is_pressed)
                {
                    RaceGUIBase* gui = world->getRaceGUI();
                    if (gui != NULL) gui->m_enabled = !gui->m_enabled;
                    
                    const int count = World::getWorld()->getNumKarts();
                    for (int n=0; n<count; n++)
                    {
                        World::getWorld()->getKart(n)->getNode()
                            ->setVisible(gui->m_enabled);
                    }
                }
                else
                {
                    AbstractKart* kart = world->getLocalPlayerKart(0);
                    kart->setEnergy(100.0f);
                }
            }
            break;
            
        case KEY_F9:
            if (UserConfigParams::m_artist_debug_mode && world)
            {
                AbstractKart* kart = world->getLocalPlayerKart(0);
                if(control_is_pressed && race_manager->getMinorMode()!=
                                          RaceManager::MINOR_MODE_3_STRIKES)
                    kart->setPowerup(PowerupManager::POWERUP_RUBBERBALL,
                                     10000);
                else
                    kart->setPowerup(PowerupManager::POWERUP_SWATTER, 10000);
            }
            break;
            
        case KEY_F10:
            if(world && value)
            {
                if(control_is_pressed && ReplayRecorder::get())
                    ReplayRecorder::get()->Save();
                else
                    history->Save();
            }
            break;
            
        case KEY_F11:
            if (UserConfigParams::m_artist_debug_mode && value && 
                control_is_pressed && world)
            {
                world->getPhysics()->nextDebugMode();
            }
            break;

        case KEY_F12:
            if(value)
                UserConfigParams::m_display_fps = 
                    !UserConfigParams::m_display_fps;
            break;
            
        case KEY_KEY_P:
            if (UserConfigParams::m_artist_debug_mode && value && 
                control_is_pressed)
                UserConfigParams::m_profiler_enabled = 
                                         !UserConfigParams::m_profiler_enabled;
            break;
        default:
            break;
    } // switch

}
Esempio n. 11
0
/*! Will also load the hand, even though the hand is not explicitly used. It is needed for
  the grasp allocator, plus it might be needed for retrieving DOF values, for example if
  the grasp is stored in the database as eigengrasp values.
*/
void GraspClusteringTask::start()
{
  //get the details of the planning task itself
  if (!mDBMgr->GetPlanningTaskRecord(mRecord.taskId, &mPlanningTask)) {
    DBGA("Failed to get planning record for task");
    mStatus = FAILED;
    return;
  }

  World *world = graspitCore->getWorld();
  Hand *hand;

  //check if the currently selected hand is the same as the one we need
  //if not, load the hand
  if (world->getCurrentHand() && world->getCurrentHand()->getDBName() == QString(mPlanningTask.handName.c_str())) {
    DBGA("Grasp Planning Task: using currently loaded hand");
    hand = world->getCurrentHand();
  } else {
    QString handPath = mDBMgr->getHandGraspitPath(QString(mPlanningTask.handName.c_str()));
    handPath = QString(getenv("GRASPIT")) + handPath;
    DBGA("Grasp Planning Task: loading hand from " << handPath.latin1());
    hand = static_cast<Hand *>(world->importRobot(handPath));
    if (!hand) {
      DBGA("Failed to load hand");
      mStatus = FAILED;
      return;
    }
  }
  mDBMgr->SetGraspAllocator(new GraspitDBGraspAllocator(hand));

  //load all the grasps
  std::vector<db_planner::Grasp *> graspList;
  if (!mDBMgr->GetGrasps(*(mPlanningTask.model), mPlanningTask.handName, &graspList)) {
    DBGA("Load grasps failed");
    mStatus = FAILED;
    while (!graspList.empty()) {
      delete graspList.back();
      graspList.pop_back();
    }
    return;
  }

  //sort grasps by energy (hard-coded in, maybe later we'll allow other sorting)
  std::sort(graspList.begin(), graspList.end(), db_planner::Grasp::CompareEnergy);

  //if all goes well, we are done
  mStatus = DONE;
  int clusters = 0;
  DBGA("Clustering " << graspList.size() << " grasps");

  while (!graspList.empty()) {
    //pop the front (best grasp)
    db_planner::Grasp *repGrasp = graspList.front();
    graspList.erase(graspList.begin());

    //compliant_copy grasps are ignored by clustering tasks
    if (repGrasp->CompliantCopy()) {
      delete repGrasp;
      continue;
    }

    //mark it as cluster center in the database
    if (!mDBMgr->SetGraspClusterRep(repGrasp, true)) {
      DBGA("Failed to mark cluster rep in database");
      mStatus = FAILED;
      delete repGrasp;
      break;
    }
    clusters++;

    //find other grasps in its cluster
    int cloud = 0;
    std::vector<db_planner::Grasp *>::iterator it = graspList.begin();
    while (it != graspList.end()) {

      //compliant_copy grasps are ignored by clustering tasks
      if (!(*it)->CompliantCopy() &&
          clusterGrasps(static_cast<GraspitDBGrasp *>(repGrasp), static_cast<GraspitDBGrasp *>(*it))) {
        (*it)->SetClusterRep(false);
        //mark it as non-center in the database
        if (!mDBMgr->SetGraspClusterRep(*it, false)) {
          DBGA("Failed to mark non-cluster rep in database");
          mStatus = FAILED;
          break;
        }
        cloud++;
        delete *it;
        it = graspList.erase(it);
      } else {
        it++;
      }

    }
    DBGA("  Marked cluster of size " << cloud);
    delete repGrasp;
    if (mStatus == FAILED) { break; }
  }
  while (!graspList.empty()) {
    delete graspList.back();
    graspList.pop_back();
  }
  DBGA("Successfully marked " << clusters << " clusters");
}
Esempio n. 12
0
bool Socket::Flush()
{
    int b=0;
    int w=0;
    int status = Z_OK;
    int length = 0;
    int i = 0;
    World* world = World::GetPtr();

    if (!_outBuffer.length())
        {
            return true;
        }
//prepend buffer to prompt
    _totalSent += _outBuffer.length();
    if ((_mobile!=NULL)&&(_con==ConnectionType::Game))
        {
            _outBuffer+="\r\n"+world->BuildPrompt(_mobile->GetPrompt(), _mobile)+TELNET_IAC+TELNET_GA;
        }

    if (!_compressing)
        {
            //we are not compressing outbound data.
            while (_outBuffer.length() > 0)
                {
                    b = _outBuffer.length();
                    // any write failures ?
                    if (_control!=-1)
                        {
                            if ((w = send(_control, _outBuffer.c_str(), b, 0)) == -1)
                                {
                                    return false;
                                }
                        }
                    // move the buffer down
                    _outBuffer.erase(0, w);
                }
        } //end sending raw data
    else
        {
            //we are compressing, wheee!
            unsigned char* buff= new unsigned char[_outBuffer.length()];

            zstream.avail_in = _outBuffer.length();
            zstream.next_in = (unsigned char*)const_cast<char*>(_outBuffer.c_str());
            zstream.next_out = buff;

            while (zstream.avail_in)
                {
                    zstream.avail_out = _outBuffer.length() -(zstream.next_out-buff);
                    if (zstream.avail_out)
                        {
                            status = deflate(&zstream, Z_SYNC_FLUSH);
                            if (status != Z_OK)
                                {
                                    delete []buff;
                                    return false;
                                }
                        }
                }
            length = zstream.next_out-buff;
            if (length)
                {
                    _compressedSent += length;
                    b = 0;
                    for (i = 0; i < length; i +=b)
                        {
                            w = Min<int>(length-i, 4096);
                            b = send(_control, buff+i, w, 0);
                        }
                }
            _outBuffer.clear();
            delete [] buff;
        }

    return true;
}
Esempio n. 13
0
/** Draws the mini map and the position of all karts on it.
 */
void RaceGUI::drawGlobalMiniMap()
{
#ifndef SERVER_ONLY
    // draw a map when arena has a navigation mesh.
    Track *track = Track::getCurrentTrack();
    if ( (track->isArena() || track->isSoccer()) && !(track->hasNavMesh()) )
        return;

    int upper_y = irr_driver->getActualScreenSize().Height - m_map_bottom - m_map_height;
    int lower_y = irr_driver->getActualScreenSize().Height - m_map_bottom;

    core::rect<s32> dest(m_map_left, upper_y,
                         m_map_left + m_map_width, lower_y);

    track->drawMiniMap(dest);

    World *world = World::getWorld();
    for(unsigned int i=0; i<world->getNumKarts(); i++)
    {
        const AbstractKart *kart = world->getKart(i);
        const SpareTireAI* sta =
            dynamic_cast<const SpareTireAI*>(kart->getController());
        // don't draw eliminated kart
        if(kart->isEliminated() && !(sta && sta->isMoving())) continue;
        const Vec3& xyz = kart->getXYZ();
        Vec3 draw_at;
        track->mapPoint2MiniMap(xyz, &draw_at);
        draw_at *= UserConfigParams::m_scale_rtts_factor;

        video::ITexture* icon = sta ?
            irr_driver->getTexture(FileManager::GUI, "heart.png") :
            kart->getKartProperties()->getMinimapIcon();

        // int marker_height = m_marker->getSize().Height;
        core::rect<s32> source(core::position2di(0, 0), icon->getSize());
        int marker_half_size = (kart->getController()->isLocalPlayerController()
                                ? m_minimap_player_size
                                : m_minimap_ai_size                        )>>1;
        core::rect<s32> position(m_map_left+(int)(draw_at.getX()-marker_half_size),
                                 lower_y   -(int)(draw_at.getY()+marker_half_size),
                                 m_map_left+(int)(draw_at.getX()+marker_half_size),
                                 lower_y   -(int)(draw_at.getY()-marker_half_size));
        draw2DImage(icon, position, source, NULL, NULL, true);
    }   // for i<getNumKarts

    SoccerWorld *sw = dynamic_cast<SoccerWorld*>(World::getWorld());
    if (sw)
    {
        Vec3 draw_at;
        track->mapPoint2MiniMap(sw->getBallPosition(), &draw_at);
        draw_at *= UserConfigParams::m_scale_rtts_factor;
        video::ITexture* icon =
            irr_driver->getTexture(FileManager::GUI, "soccer_ball_normal.png");

        core::rect<s32> source(core::position2di(0, 0), icon->getSize());
        core::rect<s32> position(m_map_left+(int)(draw_at.getX()-(m_minimap_player_size/2.5f)),
                                 lower_y   -(int)(draw_at.getY()+(m_minimap_player_size/2.5f)),
                                 m_map_left+(int)(draw_at.getX()+(m_minimap_player_size/2.5f)),
                                 lower_y   -(int)(draw_at.getY()-(m_minimap_player_size/2.5f)));
        draw2DImage(icon, position, source, NULL, NULL, true);
    }
#endif
}   // drawGlobalMiniMap
Esempio n. 14
0
int main()
{
    // Initialize globals
    initGlobals();

    // Window
    window.setSize(sf::Vector2u(window_width, window_height));
    window.setPosition(sf::Vector2i(200, 200));
    window.setFramerateLimit(FRAMES_PER_SECOND);
    //window.setVerticalSyncEnabled(true);
    window.setKeyRepeatEnabled(false);

    // Camera view
    sf::View windowView;

    // Menu
    initializeMenu();

    // UI
    ui.init();

    // Minimap
//    Minimap minimap;

    // Create & Set contactlistener
    BoxContactListener boxContactListener;
    physicsWorld.SetContactListener(&boxContactListener);

    // Build world
    //gameWorld.generateWorld(physicsWorld);

    // ------------------------------- MAIN LOOP -------------------------------
    while(window.isOpen())
    {
        // ------------------------------- Input & Views -------------------------------
        sf::Event event;
        gameEvents.processEvents(window, event);

        // Update view in case of window resize
        window_width = window.getSize().x;
        window_height = window.getSize().y;
        windowView.setSize(window_width, window_height);

//        if(minimap.updateViewThroughMinimap)
//        {
//            windowView.setCenter(minimap.newViewCenter.x, minimap.newViewCenter.y);
//        }

        if(player.hasNewFocus)
        {
            windowView.setCenter(player.getNewFocus().x, player.getNewFocus().y);
        }

        // Update normal view with inputs
        windowView = updateView(windowView);

        if(gameWorld.completionStarted && gameWorld.completionTimer.timeReached())
        {
            windowView.setCenter(window_width/2, window_height/2);
            global_levelComplete = false;
        }

        // Clear window
        window.clear(sf::Color(255, 255, 255, 255));

        if(global_isMenu)
        {
            ui.setSize(window_width, window_height);
            window.setView(ui.getView());

            menu_logo_bottom->setPosition(window_width - textures["menu_logo_bottom"].getSize().x, window_height - textures["menu_logo_bottom"].getSize().y);

            menu.update(gameEvents);
            menu.draw(window);

            // Instructions
            if(show_instructions)
            {
                showInstructions();

                if(show_instructions_controls)
                {
                    showControls();
                }

                if(show_instructions_gameplay)
                {
                    showGameplay();
                }
            }
        }
        else
        {
            window.setView(windowView);

            // ------------------------------- Updates -------------------------------

            // Player
            player.update(physicsWorld, gameEvents, gameWorld);

            if(!global_isPaused)
            {
                // Physics
                physicsWorld.Step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);

                // World
                gameWorld.update(gameEvents, physicsWorld, player);

                // UI
                ui.update(gameWorld, player);
            }


            // Calculate viewable area
            int viewShiftX = window.getSize().x/2 - window.getView().getCenter().x;
            int viewShiftY = window.getSize().y/2 - window.getView().getCenter().y;
            int windowMinX = -100 - viewShiftX;
            int windowMaxX = windowMinX + window_width + 200;
            int windowMinY = -100 - viewShiftY;
            int windowMaxY = windowMinY + window_height + 200;

            // ------------------------------- Drawing -------------------------------

            window.setView(ui.getView());
            // Background
            sf::Vertex rectangle[] =
            {
                sf::Vertex(sf::Vector2f(0.0f, 0.0f), sf::Color(0, 100, 130, 255)),
                sf::Vertex(sf::Vector2f(window_width, 0.0f), sf::Color(0, 100,130, 255)),
                sf::Vertex(sf::Vector2f(window_width, window_height), sf::Color(0, 200, 230, 255)),
                sf::Vertex(sf::Vector2f(0.0f, window_height), sf::Color(0, 200, 230, 255))
            };
            window.draw(rectangle, 4, sf::Quads);

            window.setView(windowView);

            // World & Player
            gameWorld.draw(window, b2Vec2(windowMinX, windowMinY), b2Vec2(windowMaxX, windowMaxY), false);
            player.draw(window);

            // HUD !!CLASS!!
            ui.setSize(window_width, window_height);
            window.setView(ui.getView());

            if(!gameWorld.completionTimer.timeReached() && gameWorld.completionStarted)
            {
                sf::Text temp("You have won", font_default, 40);

                int midX = window_width / 2.0f - 100;
                int midY = window_height / 2.0f - 40;

                temp.setPosition(midX, midY);
                temp.setColor(sf::Color::White);

                window.draw(temp);
            }

            if(global_isPaused)
            {
                sf::RectangleShape rect;
                rect.setSize(sf::Vector2f(window_width, window_height));
                rect.setPosition(0,0);
                rect.setFillColor(sf::Color(100, 100, 100, 155));

                window.draw(rect);
            }

            ui.draw(window);


    //        sf::RectangleShape border;
    //        border.setPosition(0.0f, window_height - (window_height*minimapSize + MINIMAP_BORDER_SIZE));
    //        border.setSize(sf::Vector2f(window_width*minimapSize + MINIMAP_BORDER_SIZE, window_height*minimapSize + MINIMAP_BORDER_SIZE));
    //        border.setFillColor(sf::Color(0, 0, 200, 255));
    //
    //        window.draw(border);
    //
    //        // ------------------------------- Minimap -------------------------------
    //
    //        minimap.setSize(MAX_WORLD_WIDTH * BOX_SIZE, MAX_WORLD_WIDTH * BOX_SIZE, window_width, window_height);
    //        minimap.calcViewport(minimapSize);
    //        minimap.setCameraPosition(windowView.getCenter().x, windowView.getCenter().y);
    //        window.setView(minimap.getUpdatedView());
    //
    //        minimap.update(gameEvents);
    //
    //        minimap.draw(window);
    //        gameWorld.draw(window, b2Vec2(-10000, -20000), b2Vec2(10000, 10000), true);
    //        player.draw(window);
    //        minimap.drawCameraWindow(window);

            // Default View again
            window.setView(windowView);
        }

        // Display
        window.display();
    }

    return 0;
}
Esempio n. 15
0
	void Server::broadcastEntity(Entities::Entity* e)
	{
		World* w = e->getWorld();
		for (size_t i = 0; i < w->playerids.size(); i++)
			w->getPlayer(w->playerids.at(i))->getClientCon()->sendEntity(e);
	}
Esempio n. 16
0
		//Overloaded Create 
		void JointFixed::Create(World &world, JointGroup &jointGroup)
		{
			if(this->_id) dJointDestroy(this->_id);
			_id = dJointCreateFixed(world.Id(), jointGroup.Id());
		}
Esempio n. 17
0
	void Server::broadcastPickupSpawn(Entities::Pickup* p)
	{
		World* w  = p->getWorld();
		for (size_t i = 0; i < w->playerids.size(); i++)
			w->getPlayer(w->playerids.at(i))->getClientCon()->sendPickupSpawn(p);
	}
Esempio n. 18
0
		void JointFixed::Create(World &world)
		{
			if(this->_id) dJointDestroy(this->_id);
			_id = dJointCreateFixed(world.Id(), 0);
		}
bool TMXMapImporter::buildWorldFromInfo(Game *game)
{
	TextureManager *worldTextureManager = game->getGraphics()->getWorldTextureManager();
	if (mapType == MapType::ORTHOGONAL_MAP)
	{
		World *world = game->getGSM()->getWorld();
		int largestLayerWidth = 0;
		int largestLayerHeight = 0;

		// LET'S FIRST FIGURE OUT THE WORLD WIDTH AND HEIGHT

		// FIRST THE IMAGE LAYERS
		map<string, ImageLayerInfo>::const_iterator iliIt = imageLayerInfos.begin();
		while (iliIt != imageLayerInfos.end())
		{
			string key = iliIt->first;
			ImageLayerInfo ili = imageLayerInfos[key];
			if (ili.imagewidth > largestLayerWidth)
				largestLayerWidth = ili.imagewidth;
			if (ili.imageheight > largestLayerHeight)
				largestLayerHeight = ili.imageheight;

			iliIt++;
		}
		// AND THE TILED LAYERS
		map<string, TiledLayerInfo>::const_iterator tliIt = tiledLayerInfos.begin();
		while (tliIt != tiledLayerInfos.end())
		{
			string key = tliIt->first;
			TiledLayerInfo tli = tiledLayerInfos[key];
			int layerWidth = tli.width * tli.tileSetInfo->tilewidth;
			if (layerWidth > largestLayerWidth)
				largestLayerWidth = layerWidth;
			int layerHeight = tli.height * tli.tileSetInfo->tileheight;
			if (layerHeight > largestLayerHeight)
				largestLayerHeight = layerHeight;
			tliIt++;
		}
		unsigned int idOffset = worldTextureManager->getWStringTable()->getNumWStringsInTable();

		// FIRST LOAD ALL THE TILE SETS
		map<string, TileSetInfo>::const_iterator tsiIt = tileSetInfos.begin();
		while (tsiIt != tileSetInfos.end())
		{
			string key = tsiIt->first;
			TileSetInfo tsi = tileSetInfos[key];
			wstring sourceImageW(tsi.sourceImage.begin(), tsi.sourceImage.end());
			bool success = worldTextureManager->loadTileSetFromTexture(game, dir, sourceImageW, tsi.tilewidth, tsi.tileheight);
			if (!success) return false;
			tsiIt++;
		}

		// NOW LOAD THE IMAGE LAYERS, IF THERE ARE ANY
		iliIt = imageLayerInfos.begin();
		while (iliIt != imageLayerInfos.end())
		{
			string key = iliIt->first;
			ImageLayerInfo ili = imageLayerInfos[key];
			
			TiledLayer *imageLayerToAdd = new TiledLayer(	1,
				1,
				ili.imagewidth,
				ili.imageheight,
				0,
				ili.collidable,
				largestLayerWidth,
				largestLayerHeight, NULL);
			world->addLayer(imageLayerToAdd);

			Tile *imageTile = new Tile();
			imageTile->collidable = ili.collidable;
			wstring imageSourceW(ili.imageSource.begin(), ili.imageSource.end());
			imageTile->textureID = worldTextureManager->loadTexture(dir + imageSourceW);
			imageLayerToAdd->addTile(imageTile);
	
			iliIt++;
		}

		// AND NOW LOAD THE TILED LAYERS, WHICH REFERENCE THE TILE SETS
		tliIt = tiledLayerInfos.begin();
		while (tliIt != tiledLayerInfos.end())
		{
			// @TODO WE'LL NEED TO CUSTOMIZE THIS
			bool collidableLayer = false;
			string key = tliIt->first;
			TiledLayerInfo tli = tiledLayerInfos[key];
			TiledLayer *tiledLayerToAdd = new TiledLayer(	tli.width,
															tli.height,
															tli.tileSetInfo->tilewidth,
															tli.tileSetInfo->tileheight,
															0,
															tli.collidable,
															largestLayerWidth,
															largestLayerHeight,
															tli.tileSetInfo->tilePropertyTable);
			world->addLayer(tiledLayerToAdd);

			// WE HAVE TO ADD ALL THE TILES
			int row = 0;
			int col = 0;
			int uncollidableIndex = tli.tileSetInfo->firstgid;
			for (unsigned int i = 0; i < tli.gids.size(); i++)
			{
				Tile *tileToAdd = new Tile();
				tileToAdd->textureID = tli.gids[i] + idOffset - 1;
				if (tli.gids[i] == uncollidableIndex)
					tileToAdd->collidable = false;
				else
					tileToAdd->collidable = tli.collidable;
				tiledLayerToAdd->addTile(tileToAdd);
			}
			tliIt++;
		}

		// AND MAKE THE WORLD DIMENSIONS THE
		// SIZE OF THE LARGEST LAYER
		world->setWorldWidth(largestLayerWidth);
		world->setWorldHeight(largestLayerHeight);
	}
	return true;
}
void WorldController::random()
{
    int id = Tf::random(9999) + 1;
    World world = World::get(id);
    renderJson(world.toVariantMap());
}
Esempio n. 21
0
	void TeamDeathMatch::initialize(World& world, Game& game)
	{
		eventListener = std::make_unique<TeamDeathMatchPlayerEventListener>(world.getMessageQueue(), game.getSettings(), friendlyFire);
	}
Esempio n. 22
0
		void FullLife::onApply(Player& player, World& world, Int32 duration) const
		{
			player.setFullLife();
			world.getMessageQueue().add(player, "Full life");
		}
Esempio n. 23
0
void IrrDriver::renderGLSL(float dt)
{
    BoundingBoxes.clear();
    World *world = World::getWorld(); // Never NULL.

    Track *track = world->getTrack();

    for (unsigned i = 0; i < PowerupManager::POWERUP_MAX; i++)
    {
        scene::IMesh *mesh = powerup_manager->m_all_meshes[i];
        if (!mesh)
            continue;
        for (unsigned j = 0; j < mesh->getMeshBufferCount(); j++)
        {
            scene::IMeshBuffer *mb = mesh->getMeshBuffer(j);
            if (!mb)
                continue;
            for (unsigned k = 0; k < 4; k++)
            {
                video::ITexture *tex = mb->getMaterial().getTexture(k);
                if (!tex)
                    continue;
                compressTexture(tex, true);
            }
        }
    }


    // Overrides
    video::SOverrideMaterial &overridemat = m_video_driver->getOverrideMaterial();
    overridemat.EnablePasses = scene::ESNRP_SOLID | scene::ESNRP_TRANSPARENT;
    overridemat.EnableFlags = 0;

    if (m_wireframe)
    {
        overridemat.Material.Wireframe = 1;
        overridemat.EnableFlags |= video::EMF_WIREFRAME;
    }
    if (m_mipviz)
    {
        overridemat.Material.MaterialType = m_shaders->getShader(ES_MIPVIZ);
        overridemat.EnableFlags |= video::EMF_MATERIAL_TYPE;
        overridemat.EnablePasses = scene::ESNRP_SOLID;
    }

    // Get a list of all glowing things. The driver's list contains the static ones,
    // here we add items, as they may disappear each frame.
    std::vector<GlowData> glows = m_glowing;

    ItemManager * const items = ItemManager::get();
    const u32 itemcount = items->getNumberOfItems();
    u32 i;

    for (i = 0; i < itemcount; i++)
    {
        Item * const item = items->getItem(i);
        if (!item) continue;
        const Item::ItemType type = item->getType();

        if (type != Item::ITEM_NITRO_BIG && type != Item::ITEM_NITRO_SMALL &&
            type != Item::ITEM_BONUS_BOX && type != Item::ITEM_BANANA && type != Item::ITEM_BUBBLEGUM)
            continue;

        LODNode * const lod = (LODNode *) item->getSceneNode();
        if (!lod->isVisible()) continue;

        const int level = lod->getLevel();
        if (level < 0) continue;

        scene::ISceneNode * const node = lod->getAllNodes()[level];
        node->updateAbsolutePosition();

        GlowData dat;
        dat.node = node;

        dat.r = 1.0f;
        dat.g = 1.0f;
        dat.b = 1.0f;

        const video::SColorf &c = ItemManager::getGlowColor(type);
        dat.r = c.getRed();
        dat.g = c.getGreen();
        dat.b = c.getBlue();

        glows.push_back(dat);
    }

    // Start the RTT for post-processing.
    // We do this before beginScene() because we want to capture the glClear()
    // because of tracks that do not have skyboxes (generally add-on tracks)
    m_post_processing->begin();

    RaceGUIBase *rg = world->getRaceGUI();
    if (rg) rg->update(dt);

    if (!UserConfigParams::m_dynamic_lights)
    {
        SColor clearColor(0, 150, 150, 150);
        if (World::getWorld() != NULL)
            clearColor = World::getWorld()->getClearColor();

        glClear(GL_COLOR_BUFFER_BIT);
        glDepthMask(GL_TRUE);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glClearColor(clearColor.getRed() / 255.f, clearColor.getGreen() / 255.f,
            clearColor.getBlue() / 255.f, clearColor.getAlpha() / 255.f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    }

    for(unsigned int cam = 0; cam < Camera::getNumCameras(); cam++)
    {
        Camera * const camera = Camera::getCamera(cam);
        scene::ICameraSceneNode * const camnode = camera->getCameraSceneNode();

        std::ostringstream oss;
        oss << "drawAll() for kart " << cam;
        PROFILER_PUSH_CPU_MARKER(oss.str().c_str(), (cam+1)*60,
                                 0x00, 0x00);
        if (!UserConfigParams::m_dynamic_lights)
            camera->activate();
        rg->preRenderCallback(camera);   // adjusts start referee
        m_scene_manager->setActiveCamera(camnode);

        const core::recti &viewport = camera->getViewport();

        if (World::getWorld() && World::getWorld()->getTrack()->hasShadows() && !SphericalHarmonicsTextures.empty())
            irr_driver->getSceneManager()->setAmbientLight(SColor(0, 0, 0, 0));

        // TODO: put this outside of the rendering loop
        generateDiffuseCoefficients();
        if (!UserConfigParams::m_dynamic_lights)
            glEnable(GL_FRAMEBUFFER_SRGB);

        PROFILER_PUSH_CPU_MARKER("Update Light Info", 0xFF, 0x0, 0x0);
        unsigned plc = UpdateLightsInfo(camnode, dt);
        PROFILER_POP_CPU_MARKER();
        PROFILER_PUSH_CPU_MARKER("Compute camera matrix", 0x0, 0xFF, 0x0);
        computeCameraMatrix(camnode, viewport.LowerRightCorner.X - viewport.UpperLeftCorner.X, viewport.LowerRightCorner.Y - viewport.UpperLeftCorner.Y);
        PROFILER_POP_CPU_MARKER();
        renderScene(camnode, plc, glows, dt, track->hasShadows(), false);

        // Render bounding boxes
        if (irr_driver->getBoundingBoxesViz())
        {
            glUseProgram(UtilShader::ColoredLine::Program);
            glBindVertexArray(UtilShader::ColoredLine::vao);
            glBindBuffer(GL_ARRAY_BUFFER, UtilShader::ColoredLine::vbo);
            UtilShader::ColoredLine::setUniforms(SColor(255, 255, 0, 0));
            const float *tmp = BoundingBoxes.data();
            for (unsigned int i = 0; i < BoundingBoxes.size(); i += 1024 * 6)
            {
                unsigned count = MIN2((int)BoundingBoxes.size() - i, 1024 * 6);
                glBufferSubData(GL_ARRAY_BUFFER, 0, count * sizeof(float), &tmp[i]);

                glDrawArrays(GL_LINES, 0, count / 3);
            }
        }

        // Debug physic
        // Note that drawAll must be called before rendering
        // the bullet debug view, since otherwise the camera
        // is not set up properly. This is only used for
        // the bullet debug view.
        if (UserConfigParams::m_artist_debug_mode)
            World::getWorld()->getPhysics()->draw();
        if (world != NULL && world->getPhysics() != NULL)
        {
            IrrDebugDrawer* debug_drawer = world->getPhysics()->getDebugDrawer();
            if (debug_drawer != NULL && debug_drawer->debugEnabled())
            {
                const std::map<video::SColor, std::vector<float> >& lines = debug_drawer->getLines();
                std::map<video::SColor, std::vector<float> >::const_iterator it;


                glUseProgram(UtilShader::ColoredLine::Program);
                glBindVertexArray(UtilShader::ColoredLine::vao);
                glBindBuffer(GL_ARRAY_BUFFER, UtilShader::ColoredLine::vbo);
                for (it = lines.begin(); it != lines.end(); it++)
                {
                    UtilShader::ColoredLine::setUniforms(it->first);
                    const std::vector<float> &vertex = it->second;
                    const float *tmp = vertex.data();
                    for (unsigned int i = 0; i < vertex.size(); i += 1024 * 6)
                    {
                        unsigned count = MIN2((int)vertex.size() - i, 1024 * 6);
                        glBufferSubData(GL_ARRAY_BUFFER, 0, count * sizeof(float), &tmp[i]);

                        glDrawArrays(GL_LINES, 0, count / 3);
                    }
                }
                glUseProgram(0);
                glBindVertexArray(0);
            }
        }

        // Render the post-processed scene
        if (UserConfigParams::m_dynamic_lights)
        {
            bool isRace = StateManager::get()->getGameState() == GUIEngine::GAME;
            FrameBuffer *fbo = m_post_processing->render(camnode, isRace);

            if (irr_driver->getNormals())
                irr_driver->getFBO(FBO_NORMAL_AND_DEPTHS).BlitToDefault(viewport.UpperLeftCorner.X, viewport.UpperLeftCorner.Y, viewport.LowerRightCorner.X, viewport.LowerRightCorner.Y);
            else if (irr_driver->getSSAOViz())
            {
                glBindFramebuffer(GL_FRAMEBUFFER, 0);
                glViewport(viewport.UpperLeftCorner.X, viewport.UpperLeftCorner.Y, viewport.LowerRightCorner.X, viewport.LowerRightCorner.Y);
                m_post_processing->renderPassThrough(m_rtts->getFBO(FBO_HALF1_R).getRTT()[0]);
            }
            else if (irr_driver->getRSM())
            {
                glBindFramebuffer(GL_FRAMEBUFFER, 0);
                glViewport(viewport.UpperLeftCorner.X, viewport.UpperLeftCorner.Y, viewport.LowerRightCorner.X, viewport.LowerRightCorner.Y);
                m_post_processing->renderPassThrough(m_rtts->getRSM().getRTT()[0]);
            }
            else if (irr_driver->getShadowViz())
            {
                renderShadowsDebug();
            }
            else
            {
                glEnable(GL_FRAMEBUFFER_SRGB);
                glBindFramebuffer(GL_FRAMEBUFFER, 0);
                if (UserConfigParams::m_dynamic_lights)
                    camera->activate();
                m_post_processing->renderPassThrough(fbo->getRTT()[0]);
                glDisable(GL_FRAMEBUFFER_SRGB);
            }
        }

        PROFILER_POP_CPU_MARKER();
    }   // for i<world->getNumKarts()

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

    // Set the viewport back to the full screen for race gui
    m_video_driver->setViewPort(core::recti(0, 0,
                                            UserConfigParams::m_width,
                                            UserConfigParams::m_height));

    for(unsigned int i=0; i<Camera::getNumCameras(); i++)
    {
        Camera *camera = Camera::getCamera(i);
        std::ostringstream oss;
        oss << "renderPlayerView() for kart " << i;

        PROFILER_PUSH_CPU_MARKER(oss.str().c_str(), 0x00, 0x00, (i+1)*60);
        rg->renderPlayerView(camera, dt);

        PROFILER_POP_CPU_MARKER();
    }  // for i<getNumKarts

    {
        ScopedGPUTimer Timer(getGPUTimer(Q_GUI));
        PROFILER_PUSH_CPU_MARKER("GUIEngine", 0x75, 0x75, 0x75);
        // Either render the gui, or the global elements of the race gui.
        GUIEngine::render(dt);
        PROFILER_POP_CPU_MARKER();
    }

    // Render the profiler
    if(UserConfigParams::m_profiler_enabled)
    {
        PROFILER_DRAW();
    }


#ifdef DEBUG
    drawDebugMeshes();
#endif


    PROFILER_PUSH_CPU_MARKER("EndSccene", 0x45, 0x75, 0x45);
    m_video_driver->endScene();
    PROFILER_POP_CPU_MARKER();

    getPostProcessing()->update(dt);
}
Esempio n. 24
0
	void Server::broadcastAnimation(Entities::LivingEntity* e, char ani)
	{
		World* w = e->getWorld();
		for (size_t i = 0; i < w->playerids.size(); i++)
			w->getPlayer(w->playerids.at(i))->getClientCon()->sendAnimation(e, ani);
	}
Esempio n. 25
0
/** Moves a kart to its rescue position.
 *  \param kart The kart that was rescued.
 */
void SoccerWorld::moveKartAfterRescue(AbstractKart* kart)
{
    // find closest point to drop kart on
    World *world = World::getWorld();
    const int start_spots_amount = world->getTrack()->getNumberOfStartPositions();
    assert(start_spots_amount > 0);

    float largest_accumulated_distance_found = -1;
    int furthest_id_found = -1;

    const float kart_x = kart->getXYZ().getX();
    const float kart_z = kart->getXYZ().getZ();

    for(int n=0; n<start_spots_amount; n++)
    {
        // no need for the overhead to compute exact distance with sqrt(),
        // so using the 'manhattan' heuristic which will do fine enough.
        const btTransform &s = world->getTrack()->getStartTransform(n);
        const Vec3 &v=s.getOrigin();
        float accumulatedDistance = .0f;
        bool spawnPointClear = true;

        for(unsigned int k=0; k<getCurrentNumKarts(); k++)
        {
            const AbstractKart *currentKart = World::getWorld()->getKart(k);
            const float currentKart_x = currentKart->getXYZ().getX();
            const float currentKartk_z = currentKart->getXYZ().getZ();

            if(kart_x!=currentKart_x && kart_z !=currentKartk_z)
            {
                float absDistance = fabs(currentKart_x - v.getX()) +
                                         fabs(currentKartk_z - v.getZ());
                if(absDistance < CLEAR_SPAWN_RANGE)
                {
                    spawnPointClear = false;
                    break;
                }
                accumulatedDistance += absDistance;
            }
        }

        if(largest_accumulated_distance_found < accumulatedDistance && spawnPointClear)
        {
            furthest_id_found = n;
            largest_accumulated_distance_found = accumulatedDistance;
        }
    }

    assert(furthest_id_found != -1);
    const btTransform &s = world->getTrack()->getStartTransform(furthest_id_found);
    const Vec3 &xyz = s.getOrigin();
    kart->setXYZ(xyz);
    kart->setRotation(s.getRotation());

    //position kart from same height as in World::resetAllKarts
    btTransform pos;
    pos.setOrigin(kart->getXYZ()+btVector3(0, 0.5f*kart->getKartHeight(), 0.0f));
    pos.setRotation( btQuaternion(btVector3(0.0f, 1.0f, 0.0f), 0 /* angle */) );

    kart->getBody()->setCenterOfMassTransform(pos);

    //project kart to surface of track
    bool kart_over_ground = m_track->findGround(kart);

    if (kart_over_ground)
    {
        //add vertical offset so that the kart starts off above the track
        float vertical_offset = kart->getKartProperties()->getVertRescueOffset() *
                                kart->getKartHeight();
        kart->getBody()->translate(btVector3(0, vertical_offset, 0));
    }
    else
    {
        Log::warn("[SoccerWorld]", " Invalid position after rescue for kart %s on track %s.",
                kart->getIdent().c_str(), m_track->getIdent().c_str());
    }
}   // moveKartAfterRescue
Esempio n. 26
0
	void Server::broadcastNamedEntitySpawn(Entities::LivingEntity* e)
	{
		World* w = e->getWorld();
		for (size_t i = 0; i < w->playerids.size(); i++)
			w->getPlayer(w->playerids.at(i))->getClientCon()->sendNamedEntitySpawn(e);
	}
int OrthographicGridPathfinder::getGridHeight()
{
    GameStateManager *gsm = game->getGSM();
    World *world = gsm->getWorld();
    return world->getWorldHeight()/numRows;
}
Esempio n. 28
0
	void Server::broadcastEntityEquipment(Entities::LivingEntity* e, char slot)
	{
		World* w = e->getWorld();
		for (size_t i = 0; i < w->playerids.size(); i++)
			w->getPlayer(w->playerids.at(i))->getClientCon()->sendEntityEquipment(e, slot);
	}
Esempio n. 29
0
	Console::Console(World& world, const Nz::Vector2f& size, Nz::LuaInstance& instance) :
	m_defaultFont(Nz::Font::GetDefault()),
	m_instance(instance),
	m_size(size),
	m_opened(false),
	m_characterSize(24)
	{
		Nz::MaterialRef backgroundMaterial = Nz::Material::New();
		backgroundMaterial->Enable(Nz::RendererParameter_Blend, true);
		backgroundMaterial->Enable(Nz::RendererParameter_DepthBuffer, false);
		backgroundMaterial->SetDstBlend(Nz::BlendFunc_InvSrcAlpha);
		backgroundMaterial->SetSrcBlend(Nz::BlendFunc_SrcAlpha);

		// History bakckground
		m_historyBackgroundSprite = Nz::Sprite::New();
		m_historyBackgroundSprite->SetColor(Nz::Color(80, 80, 160, 128));
		m_historyBackgroundSprite->SetMaterial(backgroundMaterial);

		m_historyBackground = world.CreateEntity();
		m_historyBackground->Enable(m_opened);
		m_historyBackground->AddComponent<Ndk::GraphicsComponent>().Attach(m_historyBackgroundSprite, -1);
		m_historyBackground->AddComponent<Ndk::NodeComponent>().SetParent(this);

		// History
		m_historyDrawer.SetCharacterSize(m_characterSize);
		m_historyDrawer.SetColor(Nz::Color(200, 200, 200));
		m_historyDrawer.SetFont(m_defaultFont);

		m_historyTextSprite = Nz::TextSprite::New();

		m_history = world.CreateEntity();
		m_history->Enable(m_opened);
		m_history->AddComponent<Ndk::GraphicsComponent>().Attach(m_historyTextSprite);

		Ndk::NodeComponent& historyNode = m_history->AddComponent<Ndk::NodeComponent>();
		historyNode.SetParent(this);

		// Input background
		m_inputBackgroundSprite = Nz::Sprite::New();
		m_inputBackgroundSprite->SetColor(Nz::Color(255, 255, 255, 200));
		m_inputBackgroundSprite->SetMaterial(backgroundMaterial);

		m_inputBackground = world.CreateEntity();
		m_inputBackground->Enable(m_opened);
		m_inputBackground->AddComponent<Ndk::GraphicsComponent>().Attach(m_inputBackgroundSprite, -1);
		m_inputBackground->AddComponent<Ndk::NodeComponent>().SetParent(this);

		// Input
		m_inputDrawer.SetColor(Nz::Color::Black);
		m_inputDrawer.SetCharacterSize(m_characterSize);
		m_inputDrawer.SetFont(m_defaultFont);
		m_inputDrawer.SetText(s_inputPrefix);

		m_inputTextSprite = Nz::TextSprite::New();
		m_inputTextSprite->Update(m_inputDrawer);

		m_input = world.CreateEntity();
		m_input->Enable(m_opened);
		m_input->AddComponent<Ndk::GraphicsComponent>().Attach(m_inputTextSprite);

		Ndk::NodeComponent& inputNode = m_input->AddComponent<Ndk::NodeComponent>();
		inputNode.SetParent(this);
		
		Layout();
	}
Esempio n. 30
0
		void MapView::Draw(){
			World *world = client->GetWorld();
			if(!world)
				return;
			
			Player *player = world->GetLocalPlayer();
			if(client->IsFollowing()){
				player = world->GetPlayer(client->followingPlayerId);
			}
			if(!player)
				return;
			
			if(largeMap)
				if(zoomState < .0001f)
					return;
			
			GameMap *map = world->GetMap();
			Vector2 mapSize = MakeVector2(map->Width(), map->Height());
			
			Vector3 pos = player->GetPosition();;
			if(player->GetTeamId() >= 2){
				pos = client->followPos;
			}
			Vector2 center = {pos.x, pos.y};
			float cfgMapSize = cg_minimapSize;
			if(cfgMapSize < 32) cfgMapSize = 32;
			if(cfgMapSize > 256) cfgMapSize = 256;
			Vector2 mapWndSize = {cfgMapSize, cfgMapSize};
			float scale = actualScale;
			
			center = Mix(center,
						 mapSize * .5f,
						 zoomState);
			
			Vector2 zoomedSize = {512, 512};
			if(renderer->ScreenWidth() < 512.f ||
			   renderer->ScreenHeight() < 512.f)
				zoomedSize = MakeVector2(256, 256);
			if(largeMap){
				float per = zoomState;
				per = 1.f - per;
				per *= per;
				per = 1.f - per;
				per = Mix(.7f, 1.f, per);
				zoomedSize = Mix(MakeVector2(0, 0),
								 zoomedSize,
								 per);
				mapWndSize = zoomedSize;
			}
			
			Vector2 inRange = mapWndSize * .5f * scale;
			AABB2 inRect(center - inRange, center + inRange);
			if(largeMap){
				inRect.min = MakeVector2(0, 0);
				inRect.max = mapSize;
			}else{
				if(inRect.GetMinX() < 0.f)
					inRect = inRect.Translated(-inRect.GetMinX(), 0.f);
				if(inRect.GetMinY() < 0.f)
					inRect = inRect.Translated(0, -inRect.GetMinY());
				if(inRect.GetMaxX() > mapSize.x)
					inRect = inRect.Translated(mapSize.x - inRect.GetMaxX(), 0.f);
				if(inRect.GetMaxY() > mapSize.y)
					inRect = inRect.Translated(0, mapSize.y - inRect.GetMaxY());
			}
			
			
			AABB2 outRect(renderer->ScreenWidth() - mapWndSize.x - 16.f, 16.f,
						  mapWndSize.x,
						  mapWndSize.y);
			if(largeMap){
				outRect.min = MakeVector2((renderer->ScreenWidth() - zoomedSize.x) * .5f,
										  (renderer->ScreenHeight() - zoomedSize.y) * .5f);
				outRect.max =MakeVector2((renderer->ScreenWidth() + zoomedSize.x) * .5f,
										 (renderer->ScreenHeight() + zoomedSize.y) * .5f);
			}
			
			float alpha = 1.f;
			if(largeMap){
				alpha = zoomState;
			}
			
			// fades bg
			if(largeMap) {
				Handle<IImage> bg = renderer->RegisterImage("Gfx/MapBg.png");
				Vector2 scrSize = {renderer->ScreenWidth(),
				renderer->ScreenHeight()};
				float size = std::max(scrSize.x, scrSize.y);
				renderer->SetColorAlphaPremultiplied(MakeVector4(0, 0, 0,alpha * .5f));
				renderer->DrawImage(bg,
									AABB2((scrSize.x - size) * .5f,
										  (scrSize.y - size) * .5f,
										  size, size));
			}
			
			// draw border
			Handle<IImage> border;
			float borderWidth;
			AABB2 borderRect = outRect;
			if(largeMap) {
				border = renderer->RegisterImage("Gfx/MapBorder.png");
				borderWidth = 3.f * outRect.GetHeight() / zoomedSize.y;
			}else{
				border = renderer->RegisterImage("Gfx/MinimapBorder.png");
				borderWidth = 2.f;
			}
			borderRect = borderRect.Inflate(borderWidth - 8.f);
			
			renderer->SetColorAlphaPremultiplied(MakeVector4(alpha,alpha,alpha,alpha));
			renderer->DrawImage(border,
								AABB2(borderRect.GetMinX()-16,
									  borderRect.GetMinY()-16,
									  16, 16),
								AABB2(0, 0, 16, 16));
			renderer->DrawImage(border,
								AABB2(borderRect.GetMaxX(),
									  borderRect.GetMinY()-16,
									  16, 16),
								AABB2(16, 0, 16, 16));
			renderer->DrawImage(border,
								AABB2(borderRect.GetMinX()-16,
									  borderRect.GetMaxY(),
									  16, 16),
								AABB2(0, 16, 16, 16));
			renderer->DrawImage(border,
								AABB2(borderRect.GetMaxX(),
									  borderRect.GetMaxY(),
									  16, 16),
								AABB2(16, 16, 16, 16));
			renderer->DrawImage(border,
								AABB2(borderRect.GetMinX(),
									  borderRect.GetMinY()-16,
									  borderRect.GetWidth(), 16),
								AABB2(16, 0, 0, 16));
			renderer->DrawImage(border,
								AABB2(borderRect.GetMinX(),
									  borderRect.GetMaxY(),
									  borderRect.GetWidth(), 16),
								AABB2(16, 16, 0, 16));
			renderer->DrawImage(border,
								AABB2(borderRect.GetMinX()-16,
									  borderRect.GetMinY(),
									  16, borderRect.GetHeight()),
								AABB2(0, 16, 16, 0));
			renderer->DrawImage(border,
								AABB2(borderRect.GetMaxX(),
									  borderRect.GetMinY(),
									  16, borderRect.GetHeight()),
								AABB2(16, 16, 16, 0));
			
			// draw map
			renderer->SetColorAlphaPremultiplied(MakeVector4(alpha,alpha,alpha,alpha));
			renderer->DrawFlatGameMap(outRect, inRect);
			
			this->inRect = inRect;
			this->outRect = outRect;
			
			// draw grid
			float gridSize = map->Width()/8.0f;

			renderer->SetColorAlphaPremultiplied(MakeVector4(0,0,0,0.8f*alpha));
			Handle<IImage> dashLine = renderer->RegisterImage("Gfx/DashLine.tga");
			for(float x = gridSize; x < map->Width(); x += gridSize){
				float wx = (x - inRect.GetMinX()) / inRect.GetWidth();
				if(wx < 0.f || wx >= 1.f)
					continue;
				wx = (wx * outRect.GetWidth()) + outRect.GetMinX();
				wx = roundf(wx);
				renderer->DrawImage(dashLine,
									MakeVector2(wx, outRect.GetMinY()),
									AABB2(0, 0, 1.f, outRect.GetHeight()));
			}
			for(float y = gridSize; y < map->Height(); y += gridSize){
				float wy = (y - inRect.GetMinY()) / inRect.GetHeight();
				if(wy < 0.f || wy >= 1.f)
					continue;
				wy = (wy * outRect.GetHeight()) + outRect.GetMinY();
				wy = roundf(wy);
				renderer->DrawImage(dashLine,
									MakeVector2(outRect.GetMinX(), wy),
									AABB2(0, 0, outRect.GetWidth(), 1.f));
			}
			
			// draw grid label
			renderer->SetColorAlphaPremultiplied(MakeVector4(1,1,1,1)*(0.8f*alpha));
			Handle<IImage> mapFont = renderer->RegisterImage("Gfx/Fonts/MapFont.tga");
			for(int i = 0; i < map->Width()/8; i++){
				float startX = (float)i * gridSize;
				float endX = startX + gridSize;
				if(startX > inRect.GetMaxX() ||
				   endX < inRect.GetMinX())
					continue;
				float fade = std::min((std::min(endX, inRect.GetMaxX()) -
									   std::max(startX, inRect.GetMinX())) /
									  (endX - startX) * 2.f, 1.f);
				renderer->SetColorAlphaPremultiplied(MakeVector4(1,1,1,1)*(fade * .8f * alpha));
				
				float center = std::max(startX, inRect.GetMinX());
				center = .5f * (center + std::min(endX, inRect.GetMaxX()));
				
				float wx = (center - inRect.GetMinX()) / inRect.GetWidth();
				wx = (wx * outRect.GetWidth()) + outRect.GetMinX();
				wx = roundf(wx);
				// TODO : change map gfx to support more characters
				float fntX = static_cast<float>((i & 3) * 8);
				float fntY = static_cast<float>((i >> 2) * 8);
				renderer->DrawImage(mapFont,
									MakeVector2(wx - 4.f, outRect.GetMinY() + 4),
									AABB2(fntX, fntY, 8, 8));
			}
			for(int i = 0; i < map->Height()/(gridSize/8); i++){
				float startY = (float)i * gridSize;
				float endY = startY + gridSize;
				if(startY > inRect.GetMaxY() ||
				   endY < inRect.GetMinY())
					continue;
				float fade = std::min((std::min(endY, inRect.GetMaxY()) -
									   std::max(startY, inRect.GetMinY())) /
									  (endY - startY) * 2.f, 1.f);
				renderer->SetColorAlphaPremultiplied(MakeVector4(1,1,1,1)*(fade * .8f * alpha));
				
				float center = std::max(startY, inRect.GetMinY());
				center = .5f * (center + std::min(endY, inRect.GetMaxY()));
				
				float wy = (center - inRect.GetMinY()) / inRect.GetHeight();
				wy = (wy * outRect.GetHeight()) + outRect.GetMinY();
				wy = roundf(wy);
				
				int fntX = (i & 3) * 8;
				int fntY = (i >> 2) * 8 + 16;
				renderer->DrawImage(mapFont,
									MakeVector2(outRect.GetMinX() + 4, wy - 4.f),
									AABB2(fntX, fntY, 8, 8));
			}			
			//draw objects
			
			std::string iconmode = cg_Minimap_Player_Icon;//import variable from configuration file
			std::string colormode = cg_Minimap_Player_Color;//import variable from configuration file
			
			Handle<IImage> playerSMG = renderer->RegisterImage("Gfx/Map/SMG.png");
			Handle<IImage> playerRifle = renderer->RegisterImage("Gfx/Map/Rifle.png");
			Handle<IImage> playerShotgun = renderer->RegisterImage("Gfx/Map/Shotgun.png");
			Handle<IImage> playerIcon = renderer->RegisterImage("Gfx/Map/Player.png");
			
			{
				
				IntVector3 teamColor =
				world->GetLocalPlayer()->GetTeamId() >= 2 ?
				IntVector3::Make(200, 200, 200) :
				world->GetTeam(world->GetLocalPlayer()->GetTeamId()).color;
				Vector4 teamColorF = ModifyColor(teamColor);
				teamColorF *= alpha;
				
				// draw local player's view
				{
					Player *p = player;
					Handle<IImage> viewIcon = renderer->RegisterImage("Gfx/Map/View.png");
					if(p->IsAlive()) {
						Vector3 front = p->GetFront2D();
						float ang = atan2(front.x, -front.y);
						if(player->GetTeamId() >= 2){
							ang = client->followYaw - static_cast<float>(M_PI) * .5f;
						}
						
						renderer->SetColorAlphaPremultiplied(teamColorF * 0.9f);
						
						DrawIcon(player->GetTeamId() >= 2 ?
								 client->followPos :
								 p->GetPosition(), viewIcon, ang);
					}
				}
				
				// draw player's icon
				for(size_t i = 0; i < world->GetNumPlayerSlots(); i++){
					Player * p = world->GetPlayer(i);
					if(p == nullptr ||
					   p->GetTeamId() != world->GetLocalPlayer()->GetTeamId() ||
					   !p->IsAlive())
						continue;
					
					Vector3 front = p->GetFront2D();
					float ang = atan2(front.x, -front.y);
					if(player->GetTeamId() >= 2){
						ang = client->followYaw - static_cast<float>(M_PI) * .5f;
					}
					
					//use a spec color for each player
					if ( colormode=="1"){
						IntVector3 Colorplayer=IntVector3::Make(palette[i][0],palette[i][1],palette[i][2]);
						Vector4 ColorplayerF = ModifyColor(Colorplayer);
						ColorplayerF *=1.0f;
						renderer->SetColorAlphaPremultiplied(ColorplayerF);
					}	
					else {
						renderer->SetColorAlphaPremultiplied(teamColorF);
					}
					
					//use a different icon in minimap according to weapon of player
					if( iconmode=="1"){
						std::string weapon=world->GetPlayer(i)->GetWeapon()->GetName();
						if (weapon=="SMG"){							
							DrawIcon(player->GetTeamId() >= 2 ?
									client->followPos :
									p->GetPosition(),playerSMG , ang);
						}
						
						else if (weapon=="Rifle"){
							DrawIcon(player->GetTeamId() >= 2 ?
									client->followPos :
									p->GetPosition(), playerRifle, ang);
						}
						
						else if (weapon=="Shotgun"){
							DrawIcon(player->GetTeamId() >= 2 ?
									client->followPos :
									p->GetPosition(), playerShotgun, ang);
						}
					}
					else{//draw normal color	
						DrawIcon(player->GetTeamId() >= 2 ?
								client->followPos :
								p->GetPosition(), playerIcon, ang);
					}
				}
			}
			
			IGameMode* mode = world->GetMode();
			if( mode && IGameMode::m_CTF == mode->ModeType() ) {
				CTFGameMode *ctf = static_cast<CTFGameMode *>(mode);
				Handle<IImage> intelIcon = renderer->RegisterImage("Gfx/Map/Intel.png");
				Handle<IImage> baseIcon = renderer->RegisterImage("Gfx/Map/CommandPost.png");
				for(int tId = 0; tId < 2; tId++){
					CTFGameMode::Team& team = ctf->GetTeam(tId);
					IntVector3 teamColor = world->GetTeam(tId).color;
					Vector4 teamColorF = ModifyColor(teamColor);
					teamColorF *= alpha;
					
					// draw base
					renderer->SetColorAlphaPremultiplied(teamColorF);
					DrawIcon(team.basePos, baseIcon, 0.f);
					
					
					// draw flag
					if(!ctf->GetTeam(1-tId).hasIntel){
						renderer->SetColorAlphaPremultiplied(teamColorF);
						DrawIcon(team.flagPos, intelIcon, 0.f);
					}else if(world->GetLocalPlayer()->GetTeamId() == 1-tId){
						// local player's team is carrying
						size_t cId = ctf->GetTeam(1-tId).carrier;
						
						// in some game modes, carrier becomes invalid
						if(cId < world->GetNumPlayerSlots()){
							Player * carrier= world->GetPlayer(cId);
							if(carrier && carrier->GetTeamId() ==
							   world->GetLocalPlayer()->GetTeamId()){
								
								Vector4 col = teamColorF;
								col *= fabsf(sinf(world->GetTime() * 4.f));
								renderer->SetColorAlphaPremultiplied(col);
								DrawIcon(carrier->GetPosition(), intelIcon, 0.f);
							}
						}
					}
				}
			} else if( mode && IGameMode::m_TC == mode->ModeType() ) {
				TCGameMode *tc = static_cast<TCGameMode *>(mode);
				Handle<IImage> icon = renderer->RegisterImage("Gfx/Map/CommandPost.png");
				int cnt = tc->GetNumTerritories();
				for(int i = 0; i < cnt; i++){
					TCGameMode::Territory *t = tc->GetTerritory(i);
					IntVector3 teamColor = {128,128,128};
					if(t->ownerTeamId < 2){
						teamColor = world->GetTeam(t->ownerTeamId).color;
					}
					Vector4 teamColorF = ModifyColor(teamColor);
					teamColorF *= alpha;
					
					// draw base
					renderer->SetColorAlphaPremultiplied(teamColorF);
					DrawIcon(t->pos, icon, 0.f);
					
				}
			}
		}