Exemplo n.º 1
0
void EntityManagement::init() {
  std::deque<EntityManager*>::iterator managersIt = managers.begin();
  for (; managersIt != managers.end(); ++managersIt) {
    EntityManager* manager = (*managersIt);
    manager->init();
  }
}
void DieWhenPlayerIsNearAI::update(Entity::Id myEntityId,
                             Entity::Id enemyEntityId,
                             EntityManager &entities,
                             double dt)
{
   auto position = entities.component<Position>(myEntityId);
   auto volume = entities.component<Volume>(myEntityId);
   auto enemyPosition = entities.component<Position>(enemyEntityId);

   if (!position.valid() ||
       !enemyPosition.valid() ||
           entities.get(myEntityId).has_component<DeathSentence>())
   {
      return;
   }

   sf::Vector2f v(enemyPosition->position.x - position->position.x,
                  enemyPosition->position.y - position->position.y);

   if(math::magnitude(v) > m_distanceThreshold)
       m_timeClose = 0.0;
   else
       m_timeClose += dt;

   if (m_timeClose >= m_timeThreshold)
   {
       volume->m_boxes.clear();
       volume->m_boxes.push_back(CollisionBox(64, 64)); // Should check animation size
       entities.get(myEntityId).assign<DeathSentence>(400.0); // cant be longer than the animation since the volume is stil there..
   }
}
Exemplo n.º 3
0
TEST(NAME, RemoveComponentEventDispatchesOnDestruction)
{
    World w;
    MockEntityManagerListener mock;
    EntityManager* em = new EntityManager(&w);
    em->event.addListener(&mock, "mock");

    // uninteresting calls
    EXPECT_CALL(mock, onEntitiesReallocatedHelper(testing::_))
        .Times(testing::AtLeast(0));
    EXPECT_CALL(mock, onCreateEntityHelper(testing::_))
        .Times(testing::AtLeast(0));
    EXPECT_CALL(mock, onDestroyEntityHelper(testing::_))
        .Times(testing::AtLeast(0));

    // interesting calls
    EXPECT_CALL(mock, onAddComponentHelper(testing::_, testing::Pointee(TestComponent(336, 743))))
        .Times(1);
    EXPECT_CALL(mock, onRemoveComponentHelper(testing::_, testing::Pointee(TestComponent(336, 743))))
        .Times(1);

    Entity& e = em->createEntity("entity");
    e.addComponent<TestComponent>(336, 743);
    delete em;
}
Exemplo n.º 4
0
TEST(EntityFilter, OptionalOnly) {
    EntityManager entityManager;
    using TestFilter = EntityFilter<
                       Optional<TestComponent<0>>
                       >;
    // Set up filter
    TestFilter filter;
    filter.setEntityManager(&entityManager);
    TestFilter::EntityMap filteredEntities = filter.entities();
    // Add first component
    EntityId entityId = entityManager.generateNewId();
    entityManager.addComponent(
        entityId,
        make_unique<TestComponent<0>>()
    );
    // Check filter
    filteredEntities = filter.entities();
    EXPECT_EQ(1, filteredEntities.count(entityId));
    EXPECT_EQ(1, filteredEntities.size());
    // Check group
    TestFilter::ComponentGroup group = filteredEntities[entityId];
    EXPECT_TRUE(std::get<0>(group) != nullptr);
    // Remove component
    entityManager.removeComponent(
        entityId,
        TestComponent<0>::TYPE_ID
    );
    entityManager.processRemovals();
    // Check filter
    filteredEntities = filter.entities();
    EXPECT_EQ(0, filteredEntities.count(entityId));
    EXPECT_EQ(0, filteredEntities.size());
}
Debris* ThrowableGenerator::CreateThrowable(const String& Throwable)
{
    EntityManager* EntMan = static_cast<EntityManager*>( Entresol::GetSingletonPtr()->GetWorld(0)->GetManager(ManagerBase::MT_EntityManager) );
    ThrowableData* ToBeCreated = GetThrowableData(Throwable);
    if(!ToBeCreated)
        return NULL;
    std::stringstream NameGen;
    (ToBeCreated->ThrowableCount)++;
    NameGen << ToBeCreated->ThrowableName << ToBeCreated->ThrowableCount;

    RigidDebris* Created = EntMan->CreateRigidDebris(ToBeCreated->Mass);
    Created->SetName(NameGen.str());
    Created->GetRigidProxy()->SetLinearMovementFactor(Vector3(1,1,0));
    Created->GetRigidProxy()->SetFriction(ToBeCreated->Friction);
    Created->GetRigidProxy()->SetRestitution(ToBeCreated->Restitution);
    // ©reated->GetRigidProxy()->SetActivationState(Physics::WOAS_DisableDeactivation);
    Created->GetItemProxy()->SetMesh(ToBeCreated->MeshName,ToBeCreated->GroupName);
    Created->SetOrientation(Quaternion(MathTools::GetPi(),Vector3(0,1,0)));

    /*if("Rubber"==Throwable)
    {
        //generate sphere shape
    }else{
        //generate convex hull
        //probably make more if's for cylinders and such
    }// */
    return Created;
}
Exemplo n.º 6
0
TEST(EntityFilter, Single) {
    EntityManager entityManager;
    // Set up filter
    EntityFilter<TestComponent<0>> filter;
    filter.setEntityManager(&entityManager);
    // Add component
    EntityId entityId = entityManager.generateNewId();
    entityManager.addComponent(
        entityId,
        make_unique<TestComponent<0>>()
    );
    // Check filter
    auto filteredEntities = filter.entities();
    EXPECT_EQ(1, filteredEntities.count(entityId));
    EXPECT_EQ(1, filteredEntities.size());
    // Remove component
    entityManager.removeComponent(
        entityId,
        TestComponent<0>::TYPE_ID
    );
    entityManager.processRemovals();
    // Check filter
    filteredEntities = filter.entities();
    EXPECT_EQ(0, filteredEntities.count(entityId));
    EXPECT_EQ(0, filteredEntities.size());
}
Exemplo n.º 7
0
Entity* EntityFactory::createArena()
{
	EntityManager* entityMgr = engine_->entityMgr_;
	Entity* entity = entityMgr->create();

	float arenaHalfX = 150.f;
	float arenaHalfY = 75.f;

	b2BodyDef bd;
	bd.type = b2_staticBody;
	b2Body* body = engine_->sysPhysics_->getWorld()->CreateBody(&bd);

	b2EdgeShape shape;

	b2FixtureDef sd;
	sd.shape = &shape;
	sd.density = 0;
	sd.restitution = 0.4f;
	sd.filter.categoryBits = ComPhysics::CollisionCategory::CATEG_Wall;
	sd.filter.maskBits = ComPhysics::CollisionMask::MASK_Wall;

	// Left vertical
	shape.Set(b2Vec2(-arenaHalfX, -arenaHalfY), b2Vec2(-arenaHalfX, arenaHalfY));
	body->CreateFixture(&sd);
	// Right vertical
	shape.Set(b2Vec2(arenaHalfX, -arenaHalfY), b2Vec2(arenaHalfX, arenaHalfY));
	body->CreateFixture(&sd);
	// Top horizontal
	shape.Set(b2Vec2(-arenaHalfX, arenaHalfY), b2Vec2(arenaHalfX, arenaHalfY));
	body->CreateFixture(&sd);
	// Bottom horizontal
	shape.Set(b2Vec2(-arenaHalfX, -arenaHalfY), b2Vec2(arenaHalfX, -arenaHalfY));
	body->CreateFixture(&sd);

	ComPhysics* comPhysics = entityMgr->assignComponent<ComPhysics>(entity);
	comPhysics->setMainBody(body, entity);

	Ogre::SceneManager* sceneMgr = engine_->sysGraphics_->getSceneManager();
	//Ogre::ManualObject* manual = sceneMgr->createManualObject();
	//manual->begin("white", Ogre::RenderOperation::OT_LINE_STRIP);
	//manual->position(-arenaHalfX, -arenaHalfY, 0);
	//manual->position(arenaHalfX, -arenaHalfY, 0);
	//manual->position(arenaHalfX, arenaHalfY, 0);
	//manual->position(-arenaHalfX, arenaHalfY, 0);
	//manual->index(0);
	//manual->index(1);
	//manual->index(2);
	//manual->index(3);
	//manual->index(0);
	//manual->end();
	Ogre::Entity* meshEntity = sceneMgr->createEntity("ArenaPlane.mesh");
	Ogre::SceneNode* node = engine_->sysGraphics_->getSceneRoot()->createChildSceneNode(
		Ogre::Vector3(0, 0, 0));

	ComGraphics* comGraphics = entityMgr->assignComponent<ComGraphics>(entity);
	comGraphics->sceneNode_ = node;
	comGraphics->attachMovableObject(meshEntity);

	return entity;
}
Exemplo n.º 8
0
 void update(double dt) {
     entityManagerRef->visitEntitiesWithTypeMask(componentMask, [&](Entity<EntityManagerTypes...> &entity){
         auto &aiComponent = entity.template getComponent<EnemyAIComponent>();
         
         if (aiComponent.playerId == -1) {
             int playerMask = 0;
             playerMask |= 1 << getTypeId<PlayerDetailsComponent>();
             playerMask |= 1 << getTypeId<TransformComponent>();
             auto entities = entityManagerRef->getEntityIDsWithTypeMask(playerMask);
             aiComponent.playerId = entities[0];
         }
         
         switch (aiComponent.aiType) {
             case EnemyAIComponent::AIType::DUMB:
                 updateDumbAI(dt, entity);
                 break;
             case EnemyAIComponent::AIType::FLEE:
                 updateDumbAI(dt, entity);
                 break;
             case EnemyAIComponent::AIType::FOLLOW_FIRE:
                 updateDumbAI(dt, entity);
                 break;
                 
             default:
                 break;
         }
     });
 }
void InputHandler_StageDebug::WriteEntityTreeToFile( boost::shared_ptr<CStage> pStage )
{
	using namespace gregorian;

	char dest_filename[512], time_str[64];

	ulong current_time_ms = GlobalTimer().GetTimeMS();

	if( 500 < (current_time_ms - m_EntityTreeFileLastOutputTime) )	// don't output more than once in half a second
	{
		EntityManager* pEntSet = pStage->GetEntitySet();

		sprintf( time_str, "%.3f", (double)current_time_ms / 1000.0 );

		string stage_script_name = pStage->GetScriptName();
		replace_chars( stage_script_name, '/', '-' );
		replace_chars( stage_script_name, '\\', '-' );

		// create the directory for entity tree files (YYYYMMDD)
		filesystem::path entity_tree_directory = "./debug/entity_trees-" + to_iso_string(day_clock::local_day());
		boost::filesystem::create_directories( entity_tree_directory );

		sprintf( dest_filename, "entity_tree-%s[%s].txt", stage_script_name.c_str(), time_str );

		filesystem::path dest_filepath = entity_tree_directory / dest_filename;

		// save the entity tree to disk
		pEntSet->WriteEntityTreeToFile(dest_filepath.string());

		m_EntityTreeFileLastOutputTime = current_time_ms;
	}
}
Exemplo n.º 10
0
TEST(EntityFilter, Record) {
    EntityManager entityManager;
    using TestFilter = EntityFilter<
                       TestComponent<0>
                       >;
    // Set up filter
    TestFilter filter(true);
    filter.setEntityManager(&entityManager);
    TestFilter::EntityMap filteredEntities = filter.entities();
    // Add first component
    EntityId entityId = entityManager.generateNewId();
    entityManager.addComponent(
        entityId,
        make_unique<TestComponent<0>>()
    );
    // Check added entities
    EXPECT_EQ(1, filter.addedEntities().count(entityId));
    // Remove component
    entityManager.removeComponent(
        entityId,
        TestComponent<0>::TYPE_ID
    );
    entityManager.processRemovals();
    // Check removed entities
    EXPECT_EQ(1, filter.removedEntities().count(entityId));
}
void VerletPhysicsSystem::update( EntityManager &entities, EventManager &events, TimeDelta dt )
{
  ComponentHandle<VerletBody> body;
  for( auto __unused e : entities.entities_with_components( body ) )
  {
    auto &b = *body.get();
    auto current = b.position;
    auto velocity = (b.position - b.previous_position) * static_cast<float>((dt / previous_dt)) + b.acceleration * static_cast<float>(dt * dt);
    // Friction as viscous drag.
    velocity *= (1.0 - b.drag);

    /*
    // Friction as a fixed-ish force.
    // Perhaps do some kind of ground test and apply when things are on ground.
    auto l2 = glm::length2(velocity);
    if (l2 > 0.0f) {
      auto len = std::sqrt(l2);
      auto friction = (velocity / len) * std::min(b.friction, len);
      velocity -= friction;
    }
    */

    b.position += velocity;
    b.previous_position = current;

    // We reset the acceleration so other systems/effects can simply add forces each frame.
    // TODO: consider alternative approaches to this.
    b.acceleration = vec3(0);
    previous_dt = dt;
  }

  // solve constraints
  ComponentHandle<VerletDistanceConstraint> constraint;
  const auto constraint_iterations = 2;
  for( auto __unused e : entities.entities_with_components( constraint ) )
  {
    if( (! constraint->a.valid()) || (! constraint->b.valid()) ) {
      // would be cooler if the bodies knew about all constraints on them so this couldn't happen.
      constraint.remove();
      continue;
    }

    for( int i = 0; i < constraint_iterations; i += 1 ) {
      auto &a = *constraint->a.get();
      auto &b = *constraint->b.get();

      auto center = (a.position + b.position) / 2.0f;
      auto delta = a.position - b.position;
      auto len = glm::length( delta );
      if( len < std::numeric_limits<float>::epsilon() ) {
        delta = randVec3();
        len = 1.0f;
      }
      delta *= constraint->distance / (len * 2.0f); // get half delta
      a.position = center + delta;
      b.position = center - delta;
    }
  }
}
Exemplo n.º 12
0
int createEntity(EntityManager& entityManager) {
	int id = entityManager.createEntity();
	std::cout << "Entity ID: " << id << std::endl;
	// std::unique_ptr<PositionComponent> position{new PositionComponent{sf::Vector2f{0, 0}}};
	// entityManager.addComponent(id, std::move(position));
	entityManager.addComponent(id, new PositionComponent{sf::Vector2f{(float) id, 4432}});
	return id;
}
Exemplo n.º 13
0
int _tmain(int argc, _TCHAR* argv[])
{
	EntityManager* pManager = new EntityManager;

	Entity* pCharacter = pManager->CreateEntity(0);


	return 0;
}
Exemplo n.º 14
0
GameEntity EntityFactory::CreateTextField(std::wstring text, std::string spritefont_id, DirectX::XMFLOAT2 position, DirectX::XMFLOAT4 color)
{
    EntityManager* pEntity = EntityManager::Instance();
    ResourceManager* pResource = ResourceManager::Instance();

    GameEntity textfield = pEntity->Create("Text");
    pEntity->AddComponent<UITextComponent>(textfield, text, spritefont_id, position, color);

    return textfield;
}
Exemplo n.º 15
0
Entity* EntityFactory::createShip(const ShipConfig& config)
{
	EntityManager* entityMgr = engine_->entityMgr_;
	Entity* entity = entityMgr->create();

	float boxHalfX = 0.7f;

	b2BodyDef bd;
	bd.type = b2_dynamicBody;
	bd.position.Set(config.posX_, config.posY_);
	b2Body* body = engine_->sysPhysics_->getWorld()->CreateBody(&bd);

	b2PolygonShape shape;
	shape.SetAsBox(boxHalfX, boxHalfX);

	b2FixtureDef sd;
	sd.shape = &shape;
	sd.density = 1.f;
	sd.filter.categoryBits = config.collisionCateg_;
	sd.filter.maskBits = config.collisionMask_;

	body->CreateFixture(&sd);

	ComPhysics* comPhysics = entityMgr->assignComponent<ComPhysics>(entity);
	comPhysics->setMainBody(body, entity);


	Ogre::SceneManager* sceneMgr = engine_->sysGraphics_->getSceneManager();
	
	//Ogre::ManualObject* manual = sceneMgr->createManualObject();
	//manual->begin("green", Ogre::RenderOperation::OT_LINE_STRIP);
	//manual->position(-boxHalfX, -boxHalfX, 0);
	//manual->position(boxHalfX, -boxHalfX, 0);
	//manual->position(boxHalfX, boxHalfX, 0);
	//manual->position(-boxHalfX, boxHalfX, 0);
	//manual->position(-boxHalfX, -boxHalfX, 0);
	//manual->end();
	Ogre::Entity* meshEntity = sceneMgr->createEntity("Ship.mesh");
	Ogre::SceneNode* node = engine_->sysGraphics_->getSceneRoot()->createChildSceneNode(
		Ogre::Vector3(config.posX_, config.posY_, 0));

	ComGraphics* comGraphics = entityMgr->assignComponent<ComGraphics>(entity);
	comGraphics->sceneNode_ = node;
	comGraphics->attachMovableObject(meshEntity);


	if (config.hasAI_)
	{
		ComAI* comAI = entityMgr->assignComponent<ComAI>(entity);
		comAI->entity_ = entity;
		comAI->type_ = config.AIType_;
	}

	return entity;
}
Exemplo n.º 16
0
void TriggerSystem::Update(double pDeltaTime)
{
	if (mCreateNextLevel)
	{
		mCurrentLevel++;
		//if we have enough maps
		if (mMapNames.size() - 1 >= mCurrentLevel)
		{
			LevelManager::GetInstance()->GenerateWorld(mMapNames[mCurrentLevel]);
		}
		mCreateNextLevel = false;
	}



	EntityManager* tEntMan = tEntMan->GetInstance();
	ComponentTable* tCompTable = tCompTable->GetInstance();

	int tMaxEnt = tEntMan->GetLastEntity();

	mNumOfBallsActive = 0;
	mNumOfGoalBlocksActive = 0;

	//check how many balls we have active and goals cause why not
	for (int i = 0; i < tMaxEnt; i++)
	{
		if (tCompTable->HasComponent(i, LabelType))
		{
			Label tLabel = GetComponent<LabelComponent>(i)->mLabel;

			if (tLabel == Label::Ball)
			{
				mNumOfBallsActive++;
			}
			else if (tLabel == Label::GoalBlock)
			{
				mNumOfGoalBlocksActive++;
			}
		}
	}

	//if no goal blocks, we go to next map, even if we can do this by event, we might explode or something that doesn't trigger, not sure how we want it
	if (mNumOfGoalBlocksActive == 0 && mNumOfBallsActive != 0)
	{
		//DEBUG
#ifdef _DEBUG
		cout << "WARNING - MAP HAS NO GOAL LEFT, EITHER WRONG IN MAP OR SOME REALLY WIERD BUG" << endl;
#endif
		//END DEBUG
	}

	


}
Exemplo n.º 17
0
Arquivo: Main.cpp Projeto: leod/game
 void createTestWorld() {
     entities.create(
             makeTeapot(netSystem.makeNetEntityId(), vec3(0, 0, 0),
                        vec3(0, 0, 0)));
     entities.create(
             makeTeapot(netSystem.makeNetEntityId(), vec3(-3, 0, 0),
                        vec3(0, 0, 0)));
     entities.create(
             makeTeapot(netSystem.makeNetEntityId(), vec3(3, 0, 0),
                        vec3(0, 0, 0)));
 }
Exemplo n.º 18
0
GameEntity EntityFactory::CreatePlayer(DirectX::XMFLOAT3 position)
{
    EntityManager* pEntity = EntityManager::Instance();
	ResourceManager* pResource = ResourceManager::Instance();

    GameEntity player = pEntity->Create("Player");
    pEntity->AddComponent<RenderComponent>(player, pResource->GetMaterial("ship"), pResource->GetMesh("Ship"));
    pEntity->AddComponent<InputComponent>(player, 5.0f);
    pEntity->AddComponent<CollisionComponent>(player, *pResource->GetMesh("Ship"), XMFLOAT3(0, 0, 0), 0.0007f);
    pEntity->AddComponent<AttackComponent>(player, 5.0f);
    TransformComponent* pTrans = pEntity->AddComponent<TransformComponent>(player, position);
    pTrans->transform.SetScale(.001f);
    PhysicsComponent* pPhysics = pEntity->AddComponent<PhysicsComponent>(player, XMVectorZero(), XMVectorZero());
    pPhysics->drag = 0.60f;
    pPhysics->rotationalDrag = 0.30f;

	GameEntity exhaust = pEntity->Create("Exhaust");
	pEntity->AddComponent<RenderComponent>(exhaust, pResource->GetMaterial("thruster"), pResource->GetMesh("Thruster"))->maskOnly = true;
	TransformComponent* eTrans = pEntity->AddComponent<TransformComponent>(exhaust, position);
	eTrans->transform.Translate(0.0f, 0.0f, -0.3f);
	eTrans->transform.Scale(400.0f);

	pTrans->transform.AddChild(&eTrans->transform);

	// Particles
	Particle p(XMFLOAT4(1, 0, 0, 1),
			   XMFLOAT4(1, 1, 0.1f, 0.8f),
			   XMFLOAT4(1, 0.5f, 0.1f, 0.9f),
			   XMFLOAT3(0, 0, -0.9),
			   XMFLOAT3(0, 0, -0.3),
			   XMFLOAT3(0, 0, 0),
			   0.9f,
			   0.4f,
			   0.1f,
			   0.0f,
			   0);

	ParticleGenerator* pGML = new ParticleGenerator(p, XMFLOAT3( 0.0f,  -0.16f, -1.05f), 0.08f, 0.00001, 10);
	ParticleGenerator* pGMU = new ParticleGenerator(p, XMFLOAT3( 0.0f,  +0.04f, -1.05f), 0.08f, 0.00001, 10);
	ParticleGenerator* pGRU = new ParticleGenerator(p, XMFLOAT3(+0.33f, +0.04f, -1.05f), 0.08f, 0.00001, 10);
	ParticleGenerator* pGLU = new ParticleGenerator(p, XMFLOAT3(-0.33f, +0.04f, -1.05f), 0.08f, 0.00001, 10);
	ParticleGenerator* pGRL = new ParticleGenerator(p, XMFLOAT3(+0.35f, -0.16f, -1.05f), 0.08f, 0.00001, 10);
	ParticleGenerator* pGLL = new ParticleGenerator(p, XMFLOAT3(-0.35f, -0.16f, -1.05f), 0.08f, 0.00001, 10);


	ParticleComponent* pParticles = pEntity->AddComponent<ParticleComponent>(player);
	pParticles->AddGenerator(pGML);
	pParticles->AddGenerator(pGMU);
	pParticles->AddGenerator(pGRU);
	pParticles->AddGenerator(pGLU);
	pParticles->AddGenerator(pGRL);
	pParticles->AddGenerator(pGLL);
    return player;
}
Exemplo n.º 19
0
void UpdateShaderDataTransformJob::run()
{
    EntityManager *manager = m_manager->renderNodesManager();
    const QVector<HEntity> handles = manager->activeHandles();

    for (const HEntity &handle : handles) {
        Entity *node = manager->data(handle);
        // Update transform properties in ShaderDatas and Lights
        const QVector<ShaderData *> shaderDatas = node->renderComponents<ShaderData>();
        for (ShaderData *r : shaderDatas)
            r->updateWorldTransform(*node->worldTransform());
    }
}
Exemplo n.º 20
0
Entity* EntityFactory::createBeamGun(const BeamGunConfig& config)
{
	EntityManager* entityMgr = engine_->entityMgr_;
	Entity* entity = entityMgr->create();

	float y = 0.1f;

	b2BodyDef bd;
	bd.type = b2_dynamicBody;
	bd.position.Set(config.posX_, config.posY_);
	b2Body* body = engine_->sysPhysics_->getWorld()->CreateBody(&bd);

	b2PolygonShape shape;
	b2Vec2 vertices[4];
	vertices[0].Set(0, y);
	vertices[1].Set(0, -y);
	vertices[2].Set(config.beamRange_, -y);
	vertices[3].Set(config.beamRange_, y);
	shape.Set(vertices, 4);

	b2FixtureDef sd;
	sd.shape = &shape;
	sd.density = 0;
	sd.filter.categoryBits = ComPhysics::CATEG_PlayerBeam;
	sd.filter.maskBits = ComPhysics::MASK_PlayerBeam;

	body->CreateFixture(&sd);

	ComPhysics* comPhysics = entityMgr->assignComponent<ComPhysics>(entity);
	comPhysics->setMainBody(body, entity);


	Ogre::SceneManager* sceneMgr = engine_->sysGraphics_->getSceneManager();
	Ogre::ManualObject* manual = sceneMgr->createManualObject();
	manual->begin("beam", Ogre::RenderOperation::OT_LINE_STRIP);
	manual->position(0, y, 0);
	manual->position(0, -y, 0);
	manual->position(config.beamRange_, -y, 0);
	manual->position(config.beamRange_, y, 0);
	manual->position(0, y, 0);
	manual->end();
	Ogre::SceneNode* node = engine_->sysGraphics_->getSceneRoot()->createChildSceneNode(
		Ogre::Vector3(config.posX_, config.posY_, 0));
	node->attachObject(manual);

	ComGraphics* comGraphics = entityMgr->assignComponent<ComGraphics>(entity);
	comGraphics->sceneNode_ = node;

	return entity;
}
Exemplo n.º 21
0
EntityManager *EntityManager::create() {
    static bool inited = false;
    CCAssert(inited == false, "---EntityManager has benn inited already !");
    
    inited = true;
    
    EntityManager *em = new EntityManager();
    if (em && em->init()) {
        em->autorelease();
        return em;
    }
    CC_SAFE_DELETE(em);
    return NULL;
}
Exemplo n.º 22
0
int main(int /*argc*/, char** /*argv*/)
{
	std::cout << "--------------------------" << std::endl;
	std::cout << "EXPLODING BOMBS EXAMPLE!" << std::endl;
	std::cout << "--------------------------" << std::endl;
	std::cout << "This example displays the interaction between multiple entities via uncoupled components." << std::endl;
	std::cout << "--------------------------" << std::endl;
	std::cout << "CREATING ENTITIES" << std::endl;
	std::cout << "--------------------------" << std::endl;
	EntityManager mgr;
	auto boxA = make_box("BoxA", mgr);
	auto boxB = make_box("BoxB", mgr);
	auto bombA = make_bomb("BombA", mgr);
	auto bombB = make_bomb("BombB", mgr);

	std::cout << "--------------------------" << std::endl;
	std::cout << "SETTING PROPERTIES" << std::endl;
	std::cout << "--------------------------" << std::endl;
	std::cout << "Position of " << bombA->get_name() << " is " << bombA->get<Vec2i>(PROPERTY_POSITION).get().x << ", " << bombA->get<Vec2i>(PROPERTY_POSITION).get().y << std::endl;
	bombB->get<Vec2i>(PROPERTY_POSITION) = Vec2i(2,0);
	boxA->get<Vec2i>(PROPERTY_POSITION) = Vec2i(2,1);
	boxB->get<Vec2i>(PROPERTY_POSITION) = Vec2i(5,0);

	boxA->get<int>(PROPERTY_HEALTH) = 150;
	boxB->get<int>(PROPERTY_HEALTH) = 150;
	std::cout << "Health of " << bombA->get_name() << " is " << bombA->get<int>(PROPERTY_HEALTH) << std::endl;
	std::cout << "Health of " << bombB->get_name() << " is " << bombB->get<int>(PROPERTY_HEALTH) << std::endl;

	std::cout << "--------------------------" << std::endl;
	std::cout << "START EXPLOSION" << std::endl;
	std::cout << "--------------------------" << std::endl;
	bombA->get<int>(PROPERTY_HEALTH) = 0;

	std::cout << "--------------------------" << std::endl;
	std::cout << "UPDATE ENTITY MANAGER STATE" << std::endl;
	std::cout << "--------------------------" << std::endl;
	mgr.update();

	std::cout << "--------------------------" << std::endl;
	std::cout << "ENTITIES IN ENTITY MANAGER" << std::endl;
	std::cout << "--------------------------" << std::endl;
	for(auto entity : mgr.get_entities())
	{
		std::cout << entity->get_name() << std::endl;
	}
	std::cout << "--------------------------" << std::endl;
	system("pause");
	return 0;
}
Exemplo n.º 23
0
GameEntity EntityFactory::CreateDirectionalLight(DirectX::XMFLOAT4 color, DirectX::XMFLOAT3 direction, float specularExponent)
{
    EntityManager* pEntity = EntityManager::Instance();

    GameEntity dirLight = pEntity->Create("DirectionalLight");
    pEntity->AddComponent<DirectionalLightComponent>
    (
        dirLight,
        color,
        direction,
        specularExponent
    );

    return dirLight;
}
Exemplo n.º 24
0
GameEntity EntityFactory::CreatePointLight(DirectX::XMFLOAT4 color, DirectX::XMFLOAT3 position, float specularExponent)
{
    EntityManager* pEntity = EntityManager::Instance();

    GameEntity pointLight = pEntity->Create("PointLight");
    pEntity->AddComponent<PointLightComponent>
    (
        pointLight,
        color,
        position,
        specularExponent
    );

    return pointLight;
}
Exemplo n.º 25
0
GameEntity EntityFactory::CreateButton(DirectX::XMFLOAT2 center, float width, float height, std::string event, std::wstring text, std::string spritefont_id, DirectX::XMFLOAT2 position, DirectX::XMFLOAT4 color)
{
    EntityManager* pEntity = EntityManager::Instance();
    ResourceManager* pResource = ResourceManager::Instance();

    float halfWidth = static_cast<float>(pResource->GetWindowWidth()) / 2.0f;
    float halfHeight = static_cast<float>(pResource->GetWindowHeight()) / 2.0f;

    GameEntity button = pEntity->Create("Button");
    pEntity->AddComponent<ButtonComponent>(button, true, event);
    pEntity->AddComponent<AABBComponent>(button, XMFLOAT2{center.x + halfWidth, center.y + halfHeight}, width / 2.0f, height / 2.0f);
    pEntity->AddComponent<UITextComponent>(button, text, spritefont_id, position, color);

    return button;
}
Exemplo n.º 26
0
GameEntity EntityFactory::CreateAsteroid(DirectX::XMFLOAT3 position, DirectX::XMFLOAT3 velocity, DirectX::XMFLOAT3 acceleration, DirectX::XMFLOAT3 rotation, float scale, int id)
{
    EntityManager* pEntity = EntityManager::Instance();
    ResourceManager* pResource = ResourceManager::Instance();

    GameEntity asteroid = pEntity->Create("Asteroid");
    pEntity->AddComponent<CollisionComponent>(asteroid, 0.95f*scale, position);
    pEntity->AddComponent<AsteroidRenderComponent>(asteroid, id);
    pEntity->AddComponent<RenderComponent>(asteroid, pResource->GetMaterial("asteroid"), pResource->GetMesh("Sphere"));
    pEntity->AddComponent<PhysicsComponent>(asteroid, velocity, acceleration);
    TransformComponent* pTransform = pEntity->AddComponent<TransformComponent>(asteroid, position);
    pTransform->transform.SetRotation(rotation);
    pTransform->transform.SetScale(scale);

    return asteroid;
}
Exemplo n.º 27
0
Arquivo: Main.cpp Projeto: leod/game
    void onPlayerInputWish(ClientId clientId, PlayerInput const& playerInput) {
        auto client = clients.get(clientId);

        auto entity = client->entity;
        if (entity) {
            auto input = entity->component<PlayerInputComponent>();
            auto physics = entity->component<PhysicsComponent>();
            ASSERT(input);
            ASSERT(physics);

            input->onPlayerInput(playerInput);

            if (playerInput.shoot) {
                auto origin = physics->getPosition() +
                              physics->getOrientation() * 0.65f;
                auto orientation =
                    vec3(playerInput.orientation.x, 0,
                         playerInput.orientation.y);
                auto components =
                    makeProjectile(netSystem.makeNetEntityId(),
                                   clientId,
                                   origin,
                                   orientation);
                entities.create(std::move(components));
            }

#ifdef USE_PREDICTION
            vec3 newPosition = physics->getPosition();
            sendEvent<PlayerPositionOrder>(client->peer, newPosition);
#endif
        }
    }
Exemplo n.º 28
0
EntityPtr make_box(const std::string &name, EntityManager &mgr)
{
	auto box = mgr.add_entity(name);
	box->addComponent(std::make_shared<Transform>(*box.get()));
	box->addComponent(std::make_shared<Health>(*box.get(), mgr));
	return box;
}
 void checkOffscreenPositions() {
     entityManagerRef->visitEntitiesWithTypeMask(componentMask, [](Entity<EntityManagerTypes...> &entity){
         auto &transformComponent = entity.template getComponent<TransformComponent>();
         auto &aabbComponent = entity.template getComponent<AABBComponent>();
         auto &diesWhenOffscreenComponent = entity.template getComponent<DiesWhenOffscreenComponent>();
         
         auto halfWidth = aabbComponent.width / 2.0;
         auto halfHeight = aabbComponent.height / 2.0;
         
         auto isOffscreen = (transformComponent.x - halfWidth > SCREEN_WIDTH ||
                             transformComponent.x + halfWidth < 0 ||
                             transformComponent.y - halfHeight > SCREEN_HEIGHT ||
                             transformComponent.y + halfHeight < 0);
         
         if (isOffscreen && diesWhenOffscreenComponent.cameOnscreen) {
             // only kill if we're offscreen and have been onscreen at some point
             printf("Killing entity %zu because it went offscreen\n", entity.getId()); 
             entity.kill();
         } else if (!isOffscreen && !diesWhenOffscreenComponent.cameOnscreen) {
             diesWhenOffscreenComponent.cameOnscreen = true;
         } else if (transformComponent.x > 10000 ||
                    transformComponent.x < -1000 ||
                    transformComponent.y > 10000 ||
                    transformComponent.y < -1000) {
             // just some failsafe stuff here
             entity.kill();
         }
     });
 }
Exemplo n.º 30
0
 void updateFleeAI(double dt, Entity<EntityManagerTypes...> &entity) {
     auto &transform = entity.template getComponent<TransformComponent>();
     auto &aiComponent = entity.template getComponent<EnemyAIComponent>();
     auto &playerEntity = entityManagerRef->getEntity(aiComponent.playerId);
     auto &playerTransform = playerEntity.template getComponent<TransformComponent>();
     
     
 }