Example #1
0
heXoCam::heXoCam(Context *context, MasterControl *masterControl):
    Object(context),
    yaw_{0.0f},
    pitch_{0.0f},
    yawDelta_{0.0f},
    pitchDelta_{0.0f},
    forceMultiplier{1.0f}
{
    masterControl_ = masterControl;
    SubscribeToEvent(E_SCENEUPDATE, URHO3D_HANDLER(heXoCam, HandleSceneUpdate));

    rootNode_ = masterControl_->world.scene->CreateChild("Camera");
    Node* leftEye = rootNode_->CreateChild("Left Eye");
    leftEye->SetPosition(Vector3::LEFT);
    stereoCam_.first_ = leftEye->CreateComponent<Camera>();
    Node* rightEye = rootNode_->CreateChild("Right Eye");
    rightEye->SetPosition(Vector3::RIGHT);
    stereoCam_.second_ = rightEye->CreateComponent<Camera>();

    camera_ = rootNode_->CreateComponent<Camera>();
    camera_->SetFarClip(128.0f);
    rootNode_->SetPosition(Vector3(0.0f, 42.0f, -23.0f));
    rootNode_->SetRotation(Quaternion(65.0f, 0.0f, 0.0f));
    rigidBody_ = rootNode_->CreateComponent<RigidBody>();
    rigidBody_->SetAngularDamping(10.0f);
    CollisionShape* collisionShape = rootNode_->CreateComponent<CollisionShape>();
    collisionShape->SetSphere(0.1f);
    rigidBody_->SetMass(1.0f);

    SetupViewport();
}
Example #2
0
	bool ObjectPlacer::KeyHandler::handle(const sf::Event::KeyEvent& e, bool down) {
		if (!down) {
			return true;
		}
		if (e.code == sf::Keyboard::Numpad0) {
			m_placer->Save();
		}
		if (e.code == sf::Keyboard::Add) {
			sf::Vector2f p;
			if (m_placer->GetCurrentNode()) {
				p = m_placer->GetCurrentNode()->GetGlobalPosition();
			} else {
				p = m_placer->GetScene()->GetGame()->GetMousePosition();
			}
			m_placer->Remove();
			m_placer->Next();
			m_placer->New(roundf(p.x), roundf(p.y));
		}
		if (e.code == sf::Keyboard::Subtract) {
			sf::Vector2f p;
			if (m_placer->GetCurrentNode()) {
				p = m_placer->GetCurrentNode()->GetGlobalPosition();
			} else {
				p = m_placer->GetScene()->GetGame()->GetMousePosition();
			}
			m_placer->Remove();
			m_placer->Prev();
			m_placer->New(roundf(p.x), roundf(p.y));
		}
		Node* obj = m_placer->GetCurrentNode();
		if (obj) {
			auto p = obj->GetPosition();
			if (e.code == sf::Keyboard::Down) {
				obj->SetPosition(p.x, p.y + 1);
			}
			if (e.code == sf::Keyboard::Up) {
				obj->SetPosition(p.x, p.y - 1);
			}
			if (e.code == sf::Keyboard::Left) {
				obj->SetPosition(p.x - 1, p.y);
			}
			if (e.code == sf::Keyboard::Right) {
				obj->SetPosition(p.x + 1, p.y);
			}
			if (e.code == sf::Keyboard::Multiply) {
				obj->SetRotation(obj->GetRotation() + 15);
			}
			if (e.code == sf::Keyboard::Divide) {
				obj->SetRotation(obj->GetRotation() - 15);
			}
			if (e.code == sf::Keyboard::Comma) {
				obj->SetRotation(0);
			}
		}
		return true;
	}
Example #3
0
void AnimationState::ApplyTrackFullWeight(AnimationStateTrack& stateTrack)
{
    const AnimationTrack* track = stateTrack.track_;
    Node* node = stateTrack.node_;
    
    if (track->keyFrames_.Empty() || !node)
        return;
    
    unsigned& frame = stateTrack.keyFrame_;
    track->GetKeyFrameIndex(time_, frame);
    
    // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
    unsigned nextFrame = frame + 1;
    bool interpolate = true;
    if (nextFrame >= track->keyFrames_.Size())
    {
        if (!looped_)
        {
            nextFrame = frame;
            interpolate = false;
        }
        else
            nextFrame = 0;
    }
    
    const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
    unsigned char channelMask = track->channelMask_;
    
    if (!interpolate)
    {
        // No interpolation, full weight
        if (channelMask & CHANNEL_POSITION)
            node->SetPosition(keyFrame->position_);
        if (channelMask & CHANNEL_ROTATION)
            node->SetRotation(keyFrame->rotation_);
        if (channelMask & CHANNEL_SCALE)
            node->SetScale(keyFrame->scale_);
    }
    else
    {
        const AnimationKeyFrame* nextKeyFrame = &track->keyFrames_[nextFrame];
        float timeInterval = nextKeyFrame->time_ - keyFrame->time_;
        if (timeInterval < 0.0f)
            timeInterval += animation_->GetLength();
        float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
        
        // Interpolation, full weight
        if (channelMask & CHANNEL_POSITION)
            node->SetPosition(keyFrame->position_.Lerp(nextKeyFrame->position_, t));
        if (channelMask & CHANNEL_ROTATION)
            node->SetRotation(keyFrame->rotation_.Slerp(nextKeyFrame->rotation_, t));
        if (channelMask & CHANNEL_SCALE)
            node->SetScale(keyFrame->scale_.Lerp(nextKeyFrame->scale_, t));
    }
}
void SceneReplication::CreateScene()
{
    scene_ = new Scene(context_);

    // Create scene content on the server only
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // Create octree and physics world with default settings. Create them as local so that they are not needlessly replicated
    // when a client connects
    scene_->CreateComponent<Octree>(LOCAL);
    scene_->CreateComponent<PhysicsWorld>(LOCAL);

    // All static scene content and the camera are also created as local, so that they are unaffected by scene replication and are
    // not removed from the client upon connection. Create a Zone component first for ambient lighting & fog control.
    Node* zoneNode = scene_->CreateChild("Zone", LOCAL);
    Zone* zone = zoneNode->CreateComponent<Zone>();
    zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
    zone->SetAmbientColor(Color(0.1f, 0.1f, 0.1f));
    zone->SetFogStart(100.0f);
    zone->SetFogEnd(300.0f);

    // Create a directional light without shadows
    Node* lightNode = scene_->CreateChild("DirectionalLight", LOCAL);
    lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
    Light* light = lightNode->CreateComponent<Light>();
    light->SetLightType(LIGHT_DIRECTIONAL);
    light->SetColor(Color(0.2f, 0.2f, 0.2f));
    light->SetSpecularIntensity(1.0f);

    // Create a "floor" consisting of several tiles. Make the tiles physical but leave small cracks between them
    for (int y = -20; y <= 20; ++y)
    {
        for (int x = -20; x <= 20; ++x)
        {
            Node* floorNode = scene_->CreateChild("FloorTile", LOCAL);
            floorNode->SetPosition(Vector3(x * 20.2f, -0.5f, y * 20.2f));
            floorNode->SetScale(Vector3(20.0f, 1.0f, 20.0f));
            StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
            floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
            floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));

            RigidBody* body = floorNode->CreateComponent<RigidBody>();
            body->SetFriction(1.0f);
            CollisionShape* shape = floorNode->CreateComponent<CollisionShape>();
            shape->SetBox(Vector3::ONE);
        }
    }

    // Create the camera. Limit far clip distance to match the fog
    // The camera needs to be created into a local node so that each client can retain its own camera, that is unaffected by
    // network messages. Furthermore, because the client removes all replicated scene nodes when connecting to a server scene,
    // the screen would become blank if the camera node was replicated (as only the locally created camera is assigned to a
    // viewport in SetupViewports() below)
    cameraNode_ = scene_->CreateChild("Camera", LOCAL);
    Camera* camera = cameraNode_->CreateComponent<Camera>();
    camera->SetFarClip(300.0f);

    // Set an initial position for the camera scene node above the plane
    cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
}
Example #5
0
Node* SceneReplication::CreateControllableObject()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    
    // Create the scene node & visual representation. This will be a replicated object
    Node* ballNode = scene_->CreateChild("Ball");
    ballNode->SetPosition(Vector3(Random(40.0f) - 20.0f, 5.0f, Random(40.0f) - 20.0f));
    ballNode->SetScale(0.5f);
    StaticModel* ballObject = ballNode->CreateComponent<StaticModel>();
    ballObject->SetModel(cache->GetResource<Model>("Models/Sphere.mdl"));
    ballObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
    
    // Create the physics components
    RigidBody* body = ballNode->CreateComponent<RigidBody>();
    body->SetMass(1.0f);
    body->SetFriction(1.0f);
    // In addition to friction, use motion damping so that the ball can not accelerate limitlessly
    body->SetLinearDamping(0.5f);
    body->SetAngularDamping(0.5f);
    CollisionShape* shape = ballNode->CreateComponent<CollisionShape>();
    shape->SetSphere(1.0f);
    
    // Create a random colored point light at the ball so that can see better where is going
    Light* light = ballNode->CreateComponent<Light>();
    light->SetRange(3.0f);
    light->SetColor(Color(0.5f + (Rand() & 1) * 0.5f, 0.5f + (Rand() & 1) * 0.5f, 0.5f + (Rand() & 1) * 0.5f));
    
    return ballNode;
}
Example #6
0
void Ragdolls::SpawnObject()
{
    ResourceCache* cache = GetContext()->m_ResourceCache.get();

    Node* boxNode = scene_->CreateChild("Sphere");
    boxNode->SetPosition(cameraNode_->GetPosition());
    boxNode->SetRotation(cameraNode_->GetRotation());
    boxNode->SetScale(0.25f);
    StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
    boxObject->SetModel(cache->GetResource<Model>("Models/Sphere.mdl"));
    boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
    boxObject->SetCastShadows(true);

    RigidBody* body = boxNode->CreateComponent<RigidBody>();
    body->SetMass(1.0f);
    body->SetRollingFriction(0.15f);
    CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
    shape->SetSphere(1.0f);

    const float OBJECT_VELOCITY = 10.0f;

    // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
    // to overcome gravity better
    body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);
}
Example #7
0
void RogueSkill4::Update(float timeStep)
{
	if (!enabled_)
	{
		return;
	}

	if (node_->HasComponent<Dead>())
	{
		return;
	}

	attackElapsedTime_ += timeStep;

	if (attackElapsedTime_ >= attackInterval_)
	{
		attackElapsedTime_ = 0.0f;

		Node* arrow = arrow_->Clone(LOCAL);

		arrow->SetEnabled(true);

		arrow->SetPosition(node_->GetPosition());

		arrow->LookAt(dest_);

		arrow->AddComponent(new KinematicMoveTo(context_, main_, dest_, arrowSpeed_), 0, LOCAL);

		arrow->AddComponent(new SoundSource3D(context_), 0, LOCAL);
		arrow->GetComponent<SoundSource3D>()->SetGain(0.1f);
		arrow->GetComponent<SoundSource3D>()->Play(main_->cache_->GetResource<Sound>("Sounds/shoot.ogg"));

		SubscribeToEvent(arrow, E_NODECOLLISIONSTART, HANDLER(RogueSkill4, HandleNodeCollisionStart));

		VariantMap vm;
		vm[AnimateSceneNode::P_NODE] = node_;

		if (node_->GetVar("sex").GetBool())
		{
			vm[AnimateSceneNode::P_ANIMATION] = "attackF";
		}
		else
		{
			vm[AnimateSceneNode::P_ANIMATION] = "attackM";
		}

		vm[AnimateSceneNode::P_LOOP] = false;

		if (arrow->GetPosition().x_ < dest_.x_)
		{
			vm[AnimateSceneNode::P_LAYER] = 1;
		}
		else
		{
			vm[AnimateSceneNode::P_LAYER] = -1;
		}

		SendEvent(E_ANIMATESCENENODE, vm);
	}
}
Node* GameApplication::add_object(Node* pParentNode, const String& nodeName,enObjectType type,float x,float y,float z,const char* modelUrl,const char* material)
{
	ResourceCache* cache = GetSubsystem<ResourceCache>();

	Node* pNode = pParentNode->CreateChild(nodeName);
	pNode->SetPosition(Vector3(x, y, z));

	if(type == enObjectType_StaticModel)
	{
		StaticModel* pModel = pNode->CreateComponent<StaticModel>();
		pModel->SetModel(cache->GetResource<Model>(modelUrl));
		if(material != NULL)
			pModel->SetMaterial(0,cache->GetResource<Material>(material));

		pModel->SetCastShadows(true);
	}
	else
	{
		AnimatedModel* pAniModel = pNode->CreateComponent<AnimatedModel>();
		pAniModel->SetModel(cache->GetResource<Model>(modelUrl));
		if(material != NULL)
			pAniModel->SetMaterial(0,cache->GetResource<Material>(material));

		pAniModel->SetCastShadows(true);
	}

	return pNode;
}
Example #9
0
void PhysicsStressTest::SpawnObject()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    
    // Create a smaller box at camera position
    Node* boxNode = scene_->CreateChild("SmallBox");
    boxNode->SetPosition(cameraNode_->GetPosition());
    boxNode->SetRotation(cameraNode_->GetRotation());
    boxNode->SetScale(0.25f);
    StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
    boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
    boxObject->SetMaterial(cache->GetResource<Material>("Materials/StoneSmall.xml"));
    boxObject->SetCastShadows(true);
    
    // Create physics components, use a smaller mass also
    RigidBody* body = boxNode->CreateComponent<RigidBody>();
    body->SetMass(0.25f);
    body->SetFriction(0.75f);
    CollisionShape* shape = boxNode->CreateComponent<CollisionShape>();
    shape->SetBox(Vector3::ONE);
    
    const float OBJECT_VELOCITY = 10.0f;
    
    // Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
    // to overcome gravity better
    body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);
}
Example #10
0
void SelectLevelState::OnInitialize()
{
    Scene* scene = AddScene(new Scene("SelectLevel"));

    Node* camnode = scene->AddChildNode(new dt::Node("camnode"));
    camnode->SetPosition(Ogre::Vector3(0, 0, 10));
    camnode->AddComponent(new dt::CameraComponent("cam"))->LookAt(Ogre::Vector3(0, 0, 0));

    //************************************************************
    //The following lines are for test purpose only.
    //Todo: Replace them with the actual content.
    Ogre::FontManager::getSingleton().load("DejaVuSans", "General");

    Node* node1 = scene->AddChildNode(new dt::Node("node1"));
    dt::TextComponent* text1 = node1->AddComponent(new dt::TextComponent("Select Level", "text1"));
    text1->SetBackgroundMaterial("TextOverlayBackground");
    text1->SetColor(Ogre::ColourValue::White);
    text1->SetFont("DejaVuSans");
    text1->SetFontSize(72);
    text1->SetPadding(Ogre::Vector2(20, 20));

    GuiRootWindow& rootWindow = GuiManager::Get()->GetRootWindow();
    mReturnButton = rootWindow.CreateChild<GuiButton>("return");

    mReturnButton->SetPosition(100, 100);
    mReturnButton->SetSize(250, 100);
    mReturnButton->SetCaption("Return");
    dynamic_cast<MyGUI::Button*>(mReturnButton->GetMyGUIWidget())->eventMouseButtonClick
    += MyGUI::newDelegate(this, &SelectLevelState::OnReturnClick);
    //************************************************************
}
Example #11
0
TileMaster::TileMaster(Context *context, MasterControl* masterControl):
Object(context),
  masterControl_{masterControl}
{
    rootNode_ = masterControl_->world.scene->CreateChild("TileMaster");
    //Create hexagonal field
    //Lays a field of hexagons at the origin
    int bigHexSize = 23;
    for (int i = 0; i < bigHexSize; i++) {
        for (int j = 0; j < bigHexSize; j++) {
            if (i < (bigHexSize - bigHexSize / 4) + j / 2 &&  //Exclude bottom right
                    i > (bigHexSize / 4) - (j + 1) / 2 &&  //Exclude bottom left
                    i + 1 < (bigHexSize - bigHexSize / 4) + ((bigHexSize - j + 1)) / 2 &&  //Exclude top right
                    i - 1 > (bigHexSize / 4) - ((bigHexSize - j + 2) / 2)) { //Exclude top left
                Vector3 tilePos = Vector3((-bigHexSize / 2.0f + i) * 2.0f + j % 2, -0.1f, (-bigHexSize / 2.0f + j + 0.5f) * 1.8f);
                tileMap_[IntVector2(i, j)] = new Tile(context_, this, tilePos);
            }
        }
    }
    //Add a directional light to the arena. Enable cascaded shadows on it
    Node* lightNode = rootNode_->CreateChild("Sun");
    lightNode->SetPosition(Vector3::UP*5.0f);
    lightNode->SetRotation(Quaternion(90.0f, 0.0f, 0.0f));
    Light* playLight = lightNode->CreateComponent<Light>();
    playLight->SetLightType(LIGHT_DIRECTIONAL);
    playLight->SetBrightness(0.8f);
    playLight->SetRange(10.0f);
    playLight->SetColor(Color(1.0f, 0.9f, 0.95f));
    playLight->SetCastShadows(false);
}
Example #12
0
void LuaIntegration::CreateScene()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    scene_ = new Scene(context_);

    // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
    // (-1000, -1000, -1000) to (1000, 1000, 1000)
    scene_->CreateComponent<Octree>();

    // Create a Zone component into a child scene node. The Zone controls ambient lighting and fog settings. Like the Octree,
    // it also defines its volume with a bounding box, but can be rotated (so it does not need to be aligned to the world X, Y
    // and Z axes.) Drawable objects "pick up" the zone they belong to and use it when rendering; several zones can exist
    Node* zoneNode = scene_->CreateChild("Zone");
    Zone* zone = zoneNode->CreateComponent<Zone>();
    // Set same volume as the Octree, set a close bluish fog and some ambient light
    zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
    zone->SetAmbientColor(Color(0.05f, 0.1f, 0.15f));
    zone->SetFogColor(Color(0.1f, 0.2f, 0.3f));
    zone->SetFogStart(10.0f);
    zone->SetFogEnd(100.0f);
    
    // Create randomly positioned and oriented box StaticModels in the scene
    const unsigned NUM_OBJECTS = 2000;
    for (unsigned i = 0; i < NUM_OBJECTS; ++i)
    {
        Node* boxNode = scene_->CreateChild("Box");
        boxNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(200.0f) - 100.0f, Random(200.0f) - 100.0f));
        // Orient using random pitch, yaw and roll Euler angles
        boxNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
        StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
        boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
        boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
        
        // Add our custom Rotator script object (using the LuaScriptInstance C++ component to instantiate / store it) which will
        // rotate the scene node each frame, when the scene sends its update event
        LuaScriptInstance* instance = boxNode->CreateComponent<LuaScriptInstance>();
        instance->CreateObject("LuaScripts/Rotator.lua", "Rotator");
        
        // Call the script object's "SetRotationSpeed" function.
        WeakPtr<LuaFunction> function = instance->GetScriptObjectFunction("SetRotationSpeed");
        if (function && function->BeginCall(instance))
        {
            function->PushUserType(Vector3(10.0f, 20.0f, 30.0f), "Vector3");
            function->EndCall();
        }
    }
    
    // Create the camera. Let the starting position be at the world origin. As the fog limits maximum visible distance, we can
    // bring the far clip plane closer for more effective culling of distant objects
    cameraNode_ = scene_->CreateChild("Camera");
    Camera* camera = cameraNode_->CreateComponent<Camera>();
    camera->SetFarClip(100.0f);
    
    // Create a point light to the camera scene node
    Light* light = cameraNode_->CreateComponent<Light>();
    light->SetLightType(LIGHT_POINT);
    light->SetRange(30.0f);
}
void CollisionComponent::OnCreate() {
    //Preload the bullet mesh.
    Node* bullet = this->GetNode()->GetScene()->AddChildNode(new Node("preload_bullet"));
    bullet->AddComponent(new MeshComponent(mBulletMeshHandle, "", "bullet"));
    bullet->SetPosition(0, -100, 0, Node::SCENE);

    bullet->Kill();
}
Example #14
0
	void update_scene()
	{
		main_context::access(m_server, [&](main_context::Interface *imc)
		{
			Scene *scene = imc->check_scene(m_main_scene);
			Context *context = scene->GetContext();
			ResourceCache *cache = context->GetSubsystem<ResourceCache>();

			{
				Node *n = scene->GetChild("Base");
				n->SetScale(Vector3(1.0f, 1.0f, 1.0f));
				//n->SetPosition(Vector3(0.0f, 0.5f, 0.0f));
				n->SetPosition(Vector3(0.0f, 0.5f, 0.0f));
				//n->SetRotation(Quaternion(0, 90, 0));

				int w = 10, h = 3, d = 10;
				ss_ data =
						"222222222211211111211111111111"
						"222222222211111111111111111111"
						"222222222211111111111111111111"
						"222222222211111111111111111111"
						"222222222211122111111112111111"
						"222233222211123111111112111111"
						"222233222211111111111111111111"
						"222222222211111111111111111111"
						"222222222211111111111111111111"
						"222222222211111111111111111111"
						;

				// Convert data to the actually usable voxel type id namespace
				// starting from VOXELTYPEID_UNDEFINED=0
				for(size_t i = 0; i < data.size(); i++){
					data[i] = data[i] - '0';
				}

				// Crude way of dynamically defining a voxel model
				n->SetVar(StringHash("simple_voxel_data"), Variant(
						PODVector<uint8_t>((const uint8_t*)data.c_str(),
						data.size())));
				n->SetVar(StringHash("simple_voxel_w"), Variant(w));
				n->SetVar(StringHash("simple_voxel_h"), Variant(h));
				n->SetVar(StringHash("simple_voxel_d"), Variant(d));

				// Load the same model in here and give it to the physics
				// subsystem so that it can be collided to
				SharedPtr<Model> model(interface::mesh::
						create_8bit_voxel_physics_model(context, w, h, d, data,
						m_voxel_reg.get()));

				RigidBody *body = n->CreateComponent<RigidBody>(LOCAL);
				body->SetFriction(0.75f);
				CollisionShape *shape = n->CreateComponent<CollisionShape>(
						LOCAL);
				shape->SetTriangleMesh(model, 0, Vector3::ONE);
			}
		});
	}
Example #15
0
void RaycastVehicleDemo::CreateVehicle()
{
    Node* vehicleNode = scene_->CreateChild("Vehicle");
    vehicleNode->SetPosition(Vector3(0.0f, 25.0f, 0.0f));
    // Create the vehicle logic component
    vehicle_ = vehicleNode->CreateComponent<Vehicle>();
    // Create the rendering and physics components
    vehicle_->Init();
}
Example #16
0
void Urho2DConstraints::CreateFlag(const ea::string& text, float x, float y) // Used to create Tex3D flags
{
    Node* flagNode = scene_->CreateChild("Flag");
    flagNode->SetPosition(Vector3(x, y, 0.0f));
    auto* flag3D = flagNode->CreateComponent<Text3D>(); // We use Text3D in order to make the text affected by zoom (so that it sticks to 2D)
    flag3D->SetText(text);
    auto* cache = GetSubsystem<ResourceCache>();
    flag3D->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
}
Example #17
0
Node* Weapon::ProjectileFactory(const Vector3 offset)
{
    Node* projectileNode;

    projectileNode = node_->GetScene()->CreateChild("projectile");
    projectileNode->SetPosition(projectile_spawn_position_+offset);

    return projectileNode;
}
Example #18
0
void Player::CreateGUI()
{
    UI* ui = GetSubsystem<UI>();
    Text* scoreText = ui->GetRoot()->CreateChild<Text>();
    scoreText->SetName("Score");
    scoreTextName_ = scoreText->GetName();
    scoreText->SetText(String(score_));
    scoreText->SetFont(masterControl_->cache_->GetResource<Font>("Resources/Fonts/skirmishergrad.ttf"), 32);
    scoreText->SetColor(Color(0.5f, 0.95f, 1.0f, 0.666f));
    scoreText->SetHorizontalAlignment(HA_CENTER);
    scoreText->SetVerticalAlignment(VA_CENTER);
    scoreText->SetPosition(0, ui->GetRoot()->GetHeight()/2.5f);

    //Setup 3D GUI elements
    guiNode_ = masterControl_->world.scene->CreateChild("GUI3D");
    healthBarNode_ = guiNode_->CreateChild("HealthBar");
    healthBarNode_->SetPosition(Vector3(0.0f, 1.0f, 21.0f));
    healthBarNode_->SetScale(Vector3(health_, 1.0f, 1.0f));
    healthBarModel_ = healthBarNode_->CreateComponent<StaticModel>();
    healthBarModel_->SetModel(masterControl_->cache_->GetResource<Model>("Resources/Models/Bar.mdl"));
    healthBarModel_->SetMaterial(masterControl_->cache_->GetTempResource<Material>("Resources/Materials/GreenGlowEnvmap.xml"));

    shieldBarNode_ = guiNode_->CreateChild("HealthBar");
    shieldBarNode_->SetPosition(Vector3(0.0f, 1.0f, 21.0f));
    shieldBarNode_->SetScale(Vector3(health_, 0.9f, 0.9f));
    shieldBarModel_ = shieldBarNode_->CreateComponent<StaticModel>();
    shieldBarModel_->SetModel(masterControl_->cache_->GetResource<Model>("Resources/Models/Bar.mdl"));
    shieldBarModel_->SetMaterial(masterControl_->cache_->GetResource<Material>("Resources/Materials/BlueGlowEnvmap.xml"));

    Node* healthBarHolderNode = guiNode_->CreateChild("HealthBarHolder");
    healthBarHolderNode->SetPosition(Vector3(0.0f, 1.0f, 21.0f));
    StaticModel* healthBarHolderModel = healthBarHolderNode->CreateComponent<StaticModel>();
    healthBarHolderModel->SetModel(masterControl_->cache_->GetResource<Model>("Resources/Models/BarHolder.mdl"));
    healthBarHolderModel->SetMaterial(masterControl_->cache_->GetResource<Material>("Resources/Materials/Metal.xml"));

    appleCounterRoot_ = guiNode_->CreateChild("AppleCounter");
    for (int a = 0; a < 5; a++){
        appleCounter_[a] = appleCounterRoot_->CreateChild();
        appleCounter_[a]->SetEnabled(false);
        appleCounter_[a]->SetPosition(Vector3(-(a + 8.0f), 1.0f, 21.0f));
        appleCounter_[a]->SetScale(0.333f);
        StaticModel* apple = appleCounter_[a]->CreateComponent<StaticModel>();
        apple->SetModel(masterControl_->cache_->GetResource<Model>("Resources/Models/Apple.mdl"));
        apple->SetMaterial(masterControl_->cache_->GetTempResource<Material>("Resources/Materials/GoldEnvmap.xml"));
    }

    heartCounterRoot_ = guiNode_->CreateChild("HeartCounter");
    for (int h = 0; h < 5; h++){
        heartCounter_[h] = heartCounterRoot_->CreateChild();
        heartCounter_[h]->SetEnabled(false);
        heartCounter_[h]->SetPosition(Vector3(h + 8.0f, 1.0f, 21.0f));
        heartCounter_[h]->SetScale(0.333f);
        StaticModel* heart = heartCounter_[h]->CreateComponent<StaticModel>();
        heart->SetModel(masterControl_->cache_->GetResource<Model>("Resources/Models/Heart.mdl"));
        heart->SetMaterial(masterControl_->cache_->GetTempResource<Material>("Resources/Materials/RedEnvmap.xml"));
    }
}
Example #19
0
void Labyrinth::CreateCoins()
{
    Node* objectNode = scene_->CreateChild("Apple");
    objectNode->SetPosition(Vector3(6.0f, 3.0f, 0.0f));
    objectNode->SetScale(0.5f);
    
    Apple *apple = new Apple(context_);
    apple->CreateNode(objectNode, scene_->GetNode());
    apple = objectNode->CreateComponent<Apple>();
}
void Urho3DQtApplication::CreateScene()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    scene_ = new Scene(context_);

    // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
    // show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates; it
    // is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
    // optimizing manner
    scene_->CreateComponent<Octree>();

    // Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
    // plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
    // (100 x 100 world units)
    Node* planeNode = scene_->CreateChild("Plane");
    planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
    StaticModel* planeObject = planeNode->CreateComponent<StaticModel>();
    planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));
    planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml"));

    // Create a directional light to the world so that we can see something. The light scene node's orientation controls the
    // light direction; we will use the SetDirection() function which calculates the orientation from a forward direction vector.
    // The light will use default settings (white light, no shadows)
    Node* lightNode = scene_->CreateChild("DirectionalLight");
    lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f)); // The direction vector does not need to be normalized
    Light* light = lightNode->CreateComponent<Light>();
    light->SetLightType(LIGHT_DIRECTIONAL);

    // Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
    // quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
    // LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
    // see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
    // same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
    // scene.
    const unsigned NUM_OBJECTS = 200;
    for (unsigned i = 0; i < NUM_OBJECTS; ++i)
    {
        Node* mushroomNode = scene_->CreateChild("Mushroom");
        mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f));
        mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
        mushroomNode->SetScale(0.5f + Random(2.0f));
        StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
        mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
        mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
    }

    // Create a scene node for the camera, which we will move around
    // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
    cameraNode_ = scene_->CreateChild("Camera");
    cameraNode_->CreateComponent<Camera>();

    // Set an initial position for the camera scene node above the plane
    cameraNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
}
bool Gizmo3D::MoveEditNodes(Vector3 adjust)
{
    bool moved = false;

    if (adjust.Length() > M_EPSILON)
    {
        for (unsigned i = 0; i < editNodes_->Size(); ++i)
        {
            /*
            if (moveSnap)
            {
                float moveStepScaled = moveStep * snapScale;
                adjust.x = Floor(adjust.x / moveStepScaled + 0.5) * moveStepScaled;
                adjust.y = Floor(adjust.y / moveStepScaled + 0.5) * moveStepScaled;
                adjust.z = Floor(adjust.z / moveStepScaled + 0.5) * moveStepScaled;
            }
            */

            Node* node = editNodes_->At(i);
            Vector3 nodeAdjust = adjust;
            if (axisMode_ == AXIS_LOCAL && editNodes_->Size() == 1)
                nodeAdjust = node->GetWorldRotation() * nodeAdjust;

            Vector3 worldPos = node->GetWorldPosition();
            Vector3 oldPos = node->GetPosition();

            worldPos += nodeAdjust;

            if (!node->GetParent())
                node->SetPosition(worldPos);
            else
                node->SetPosition(node->GetParent()->WorldToLocal(worldPos));

            if (node->GetPosition() != oldPos)
                moved = true;
        }
    }

    return moved;


}
Example #22
0
void Labyrinth::CreatePlayer()
{
    Node* objectNode = scene_->CreateChild("Player");
    objectNode->SetPosition(Vector3(0.0f, 10.0f, 0.0f));
    
    //CreateNodes* nodes = new CreateNodes(context_);
    playerCtrl_ = objectNode->CreateComponent<PlayerController>();
    playerCtrl_->CreateNode(objectNode);
    
    
}
Example #23
0
void AnimatingScene::CreateScene()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    
    scene_ = new Scene(context_);
    
    // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
    // (-1000, -1000, -1000) to (1000, 1000, 1000)
    scene_->CreateComponent<Octree>();
    
    // Create a Zone component into a child scene node. The Zone controls ambient lighting and fog settings. Like the Octree,
    // it also defines its volume with a bounding box, but can be rotated (so it does not need to be aligned to the world X, Y
    // and Z axes.) Drawable objects "pick up" the zone they belong to and use it when rendering; several zones can exist
    Node* zoneNode = scene_->CreateChild("Zone");
    Zone* zone = zoneNode->CreateComponent<Zone>();
    // Set same volume as the Octree, set a close bluish fog and some ambient light
    zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
    zone->SetAmbientColor(Color(0.05f, 0.1f, 0.15f));
    zone->SetFogColor(Color(0.1f, 0.2f, 0.3f));
    zone->SetFogStart(10.0f);
    zone->SetFogEnd(100.0f);
    
    // Create randomly positioned and oriented box StaticModels in the scene
    const unsigned NUM_OBJECTS = 2000;
    for (unsigned i = 0; i < NUM_OBJECTS; ++i)
    {
        Node* boxNode = scene_->CreateChild("Box");
        boxNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(200.0f) - 100.0f, Random(200.0f) - 100.0f));
        // Orient using random pitch, yaw and roll Euler angles
        boxNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
        StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
        boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
        boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
        
        // Add our custom Rotator component which will rotate the scene node each frame, when the scene sends its update event.
        // The Rotator component derives from the base class LogicComponent, which has convenience functionality to subscribe
        // to the various update events, and forward them to virtual functions that can be implemented by subclasses. This way
        // writing logic/update components in C++ becomes similar to scripting.
        // Now we simply set same rotation speed for all objects
        Rotator* rotator = boxNode->CreateComponent<Rotator>();
        rotator->SetRotationSpeed(Vector3(10.0f, 20.0f, 30.0f));
    }
    
    // Create the camera. Let the starting position be at the world origin. As the fog limits maximum visible distance, we can
    // bring the far clip plane closer for more effective culling of distant objects
    cameraNode_ = scene_->CreateChild("Camera");
    Camera* camera = cameraNode_->CreateComponent<Camera>();
    camera->SetFarClip(100.0f);
    
    // Create a point light to the camera scene node
    Light* light = cameraNode_->CreateComponent<Light>();
    light->SetLightType(LIGHT_POINT);
    light->SetRange(30.0f);
}
Example #24
0
void GizmoBar::OnTextChanged(const MGUI::FocusEvent * e)
{
	Node * n = Editor::Instance()->GetSelectNode();
	if (n == NULL)
		return ;

	String x_str, y_str, z_str;
	x_str.FromUnicode(mEditBox_X->GetCaption().c_str());
	y_str.FromUnicode(mEditBox_Y->GetCaption().c_str());
	z_str.FromUnicode(mEditBox_Z->GetCaption().c_str());

	Float3 v;
	v.x = x_str.ToFloat();
	v.y = y_str.ToFloat();
	v.z = z_str.ToFloat();


	switch (Gizmo::Instance()->GetOperator())
	{
	case Gizmo::OP_MOVE:
		{
			UndoRedoManager::Instance()->Push(new UndoRedo_Move(n->GetUID(), n->GetPosition(), v));

			n->SetPosition(v);

			Editor::Instance()->E_NodePositionChanged();
		}
		break;

	case Gizmo::OP_ROTATE:
		{
			Quat q;
			q.FromEulerAngle(v);

			UndoRedoManager::Instance()->Push(new UndoRedo_Rotate(n->GetUID(), n->GetRotation(), q));

			n->SetRotation(q);

			Editor::Instance()->E_NodeRotationChanged();
		}
		break;

	case Gizmo::OP_SCALE:
		{
			UndoRedoManager::Instance()->Push(new UndoRedo_Scale(n->GetUID(), n->GetScale(), v));

			n->SetScale(v);

			Editor::Instance()->E_NodeScaleChanged();
		}
		break;
	}
}
Example #25
0
void VehicleDemo::CreateVehicle()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    Node* vehicleNode = scene_->CreateChild("Vehicle");
    vehicleNode->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
    
    // Create the vehicle logic component
    vehicle_ = vehicleNode->CreateComponent<Vehicle>();
    // Create the rendering and physics components
    vehicle_->Init();
}
Example #26
0
//=============================================================================
// sync wheels for rendering
//=============================================================================
void Vehicle::PostUpdate(float )
{
    for ( int i = 0; i < m_vehicle->getNumWheels(); i++ )
    {

        m_vehicle->updateWheelTransform( i, true );

        btTransform transform = m_vehicle->getWheelTransformWS( i );
        Vector3 v3Origin = ToVector3( transform.getOrigin() );
        Quaternion qRot = ToQuaternion( transform.getRotation() );

        Node *pWheel = m_vpNodeWheel[ i ];
        pWheel->SetPosition( v3Origin );

        btWheelInfo whInfo = m_vehicle->getWheelInfo( i );
        
        // tarting point of the ray, where the suspension connects to the chassis
        Vector3 v3PosLS = ToVector3( whInfo.m_chassisConnectionPointCS );
        Quaternion qRotator = ( v3PosLS.x_ >= 0.0 ? Quaternion(0.0f, 0.0f, -90.0f) : Quaternion(0.0f, 0.0f, 90.0f) );
        pWheel->SetRotation( qRot * qRotator );
        
   
        
   /*
        const btRigidBody* const chassis = m_vehicle->getRigidBody();
        
        // Calculate velocity of wheel wrt ground
        btVector3 rel_pos1 = whInfo.m_raycastInfo.m_contactPointWS -
        chassis->getCenterOfMassPosition();
        btVector3 vel = chassis->getVelocityInLocalPoint(rel_pos1);
        // Calculate velocity in x & y
        //btScalar vz = -m_vehicle->getForward(i).dot(vel);
        btScalar vz = -whInfo.m_wheelDirectionCS.dot(vel);
        //btScalar vx = m_vehicle->getAxle(i).dot(vel);
        btScalar vx = whInfo.m_wheelAxleCS.dot(vel);
        // Calculate slip angle of wheel.
        btScalar slip_angle = btAtan2(vx, btFabs(vz));
       */
      
        //URHO3D_LOGINFOF("slip_angle  %d: %f \n", i, slip_angle);
        
    //    if(whInfo.m_skidInfo < 1.0)
    //        URHO3D_LOGINFOF("whInfo.m_skidInfo %f \n", whInfo.m_skidInfo);
      
        
    }
    
    
    

    //URHO3D_LOGINFOF( "Speed: %f \n", (m_vehicle->getCurrentSpeedKmHour()));
}
Example #27
0
void LookMesh(Mesh * entity)
{
	Aabb bound = entity->GetWorldAabb();

	float size = 0;
	size = Max(size, bound.GetSize().x);
	size = Max(size, bound.GetSize().y);
	size = Max(size, bound.GetSize().z);

	Node * pCamera = World::Instance()->MainCamera();
	pCamera->SetPosition(bound.GetCenter() + Float3(0, 0, -2.0f) * size);
	pCamera->SetDirection(bound.GetCenter() - pCamera->GetPosition());
}
Example #28
0
	void Sample::CreateScene()
	{
		ResourceCache* cache = GetSubsystem<ResourceCache>();

		scene_ = new Scene(context_);


		sceneHierarchyWindow_->SetScene(scene_);
		// Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
		// Also create a DebugRenderer component so that we can draw debug geometry
		scene_->CreateComponent<Octree>();
		scene_->CreateComponent<DebugRenderer>();

		// Create a Zone component for ambient lighting & fog control
		Node* zoneNode = scene_->CreateChild("Zone");
		Zone* zone = zoneNode->CreateComponent<Zone>();
		zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
		zone->SetAmbientColor(Color(0.5f, 0.5f, 0.5f));
		zone->SetFogStart(100.0f);
		zone->SetFogEnd(300.0f);

		// Create a directional light without shadows
		Node* lightNode = scene_->CreateChild("DirectionalLight");
		lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
		Light* light = lightNode->CreateComponent<Light>();
		light->SetLightType(LIGHT_DIRECTIONAL);
		light->SetColor(Color(0.2f, 0.2f, 0.2f));
		light->SetSpecularIntensity(1.0f);

		// Create a "floor" consisting of several tiles
		for (int y = -5; y <= 5; ++y)
		{
			for (int x = -5; x <= 5; ++x)
			{
				Node* floorNode = scene_->CreateChild("FloorTile");
				floorNode->SetPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
				floorNode->SetScale(Vector3(20.0f, 1.0f, 20.f));
				StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
				floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
				floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
			}
		}

		// Create the camera. Limit far clip distance to match the fog
		camNode_ = scene_->CreateChild("Camera");
		Camera* camera = camNode_->CreateComponent<Camera>();
		camera->SetFarClip(1300.0f);

		// Set an initial position for the camera scene node above the plane
		camNode_->SetPosition(Vector3(0.0f, 5.0f, 0.0f));
	}
Example #29
0
	void on_tick(const interface::TickEvent &event)
	{
		log_d(MODULE, "entitytest::on_tick");
		static uint a = 0;
		if(((a++) % 100) == 0){
			main_context::access(m_server, [&](main_context::Interface *imc){
				Scene *scene = imc->check_scene(m_main_scene);
				Node *n = scene->GetChild("Box");
				n->SetPosition(Vector3(0.0f, 6.0f, 0.0f));
				n->SetRotation(Quaternion(30, 60, 90));
				Node *n2 = scene->GetChild("Box2");
				n2->SetPosition(Vector3(-0.4f, 8.0f, 0.0f));
				n2->SetRotation(Quaternion(30, 60, 90));
				m_slow_count++;
				if(m_slow_count == 2){
					Node *n = scene->CreateChild("Box");
					n->SetPosition(Vector3(0.0f, 10.0f, 0.0f));
					n->SetScale(Vector3(1.0f, 1.0f, 1.0f));
					RigidBody *body = n->CreateComponent<RigidBody>();
					CollisionShape *shape = n->CreateComponent<CollisionShape>();
					shape->SetBox(Vector3::ONE);
					body->SetMass(1.0);
					body->SetFriction(0.75f);
					// Model and material is set on client
				}
			});
			return;
		}
		main_context::access(m_server, [&](main_context::Interface *imc){
			Scene *scene = imc->check_scene(m_main_scene);
			Node *n = scene->GetChild("Box");
			//n->Translate(Vector3(0.1f, 0, 0));
			Vector3 p = n->GetPosition();
			log_v(MODULE, "Position: %s", p.ToString().CString());
		});
	}
Node* Urho3DTemplate::CreateMushroom(const Vector3 &pos)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    Node* mushroomNode = scene_->CreateChild("Mushroom");
    mushroomNode->SetPosition(pos);
    mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f));
    mushroomNode->SetScale(2.0f + Random(0.5f));
    StaticModel* mushroomObject = mushroomNode->CreateComponent<StaticModel>();
    mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl"));
    mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml"));
    mushroomObject->SetCastShadows(true);

    return mushroomNode;
}