Beispiel #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();
}
Beispiel #2
0
bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage)
{
    if (width <= 0 || height <= 0)
    {
        URHO3D_LOGERROR("Zero or negative texture dimensions");
        return false;
    }

    // Delete the old rendersurface if any
    renderSurface_.Reset();
    usage_ = usage;

    if (usage_ == TEXTURE_RENDERTARGET || usage_ == TEXTURE_DEPTHSTENCIL)
    {
        renderSurface_ = new RenderSurface(this);

        // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
        addressMode_[COORD_U] = ADDRESS_CLAMP;
        addressMode_[COORD_V] = ADDRESS_CLAMP;
        filterMode_ = FILTER_NEAREST;
        requestedLevels_ = 1;
    }

    if (usage_ == TEXTURE_RENDERTARGET)
        SubscribeToEvent(E_RENDERSURFACEUPDATE, URHO3D_HANDLER(Texture2D, HandleRenderSurfaceUpdate));
    else
        UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);

    width_ = width;
    height_ = height;
    format_ = format;

    return Create();
}
Beispiel #3
0
DebugRenderer::DebugRenderer(Context* context) :
    Component(context)
{
    vertexBuffer_ = new VertexBuffer(context_);

    SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(DebugRenderer, HandleEndFrame));
}
Beispiel #4
0
/** Support objects created, start application specific content. */
void UApp::Start() {
    // the mouse must be in cursor mode before setting the UI.
    auto input_ = GetSubsystem< Urho3D::Input >();
    input_->SetMouseVisible(true);

    // resources origin.
    cache_ = GetSubsystem< Urho3D::ResourceCache >();

    // use the default style from Urho3D.
    GetSubsystem< Urho3D::UI >()->GetRoot()->SetDefaultStyle(
                cache_->GetResource< Urho3D::XMLFile >("UI/DefaultStyle.xml"));

    // grab mouse
    input_->SetMouseGrabbed(true);

    // setup scene to render.
    scene_ = new Urho3D::Scene(context_);
    scene_->CreateComponent< Urho3D::Octree >();

    // Create the light
    {
        auto lightNode = scene_->CreateChild("Light");
        lightNode->SetPosition(Urho3D::Vector3(6, 6, -20));
        auto light = lightNode->CreateComponent< Urho3D::Light >();
        light->SetLightType(Urho3D::LIGHT_POINT);
        light->SetRange(1000);
    }

    // setup camera
    {
        auto cameraNode_ = scene_->CreateChild("Camera");
        cameraNode_->SetPosition(Urho3D::Vector3(6, 6, -20));
        auto camera_ = cameraNode_->CreateComponent< Urho3D::Camera >();
        camera_->SetFarClip(2000);
        auto renderer = GetSubsystem< Urho3D::Renderer >();
        Urho3D::SharedPtr< Urho3D::Viewport > viewport(new Urho3D::Viewport(context_, scene_, camera_));
        renderer->SetViewport(0, viewport);
    }

    // start the game
    game.start();

    // subscribe to events
    SubscribeToEvent(Urho3D::E_UPDATE,URHO3D_HANDLER(UApp,HandleUpdate));
    SubscribeToEvent(Urho3D::E_KEYDOWN,URHO3D_HANDLER(UApp,HandleKeyDown));
    SubscribeToEvent(Urho3D::E_KEYUP,URHO3D_HANDLER(UApp,HandleKeyUp));
}
Beispiel #5
0
void HelloGUI::InitWindow()
{
    // Create the Window and add it to the UI's root node
    window_ = new Window(context_);
    uiRoot_->AddChild(window_);

    // Set Window size and layout settings
    window_->SetMinWidth(384);
    window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6));
    window_->SetAlignment(HA_CENTER, VA_CENTER);
    window_->SetName("Window");

    // Create Window 'titlebar' container
    auto* titleBar = new UIElement(context_);
    titleBar->SetMinSize(0, 24);
    titleBar->SetVerticalAlignment(VA_TOP);
    titleBar->SetLayoutMode(LM_HORIZONTAL);

    // Create the Window title Text
    auto* windowTitle = new Text(context_);
    windowTitle->SetName("WindowTitle");
    windowTitle->SetText("Hello GUI!");

    // Create the Window's close button
    auto* buttonClose = new Button(context_);
    buttonClose->SetName("CloseButton");

    // Add the controls to the title bar
    titleBar->AddChild(windowTitle);
    titleBar->AddChild(buttonClose);

    // Add the title bar to the Window
    window_->AddChild(titleBar);

    // Apply styles
    window_->SetStyleAuto();
    windowTitle->SetStyleAuto();
    buttonClose->SetStyle("CloseButton");

    // Subscribe to buttonClose release (following a 'press') events
    SubscribeToEvent(buttonClose, E_RELEASED, URHO3D_HANDLER(HelloGUI, HandleClosePressed));

    // Subscribe also to all UI mouse clicks just to see where we have clicked
    SubscribeToEvent(E_UIMOUSECLICK, URHO3D_HANDLER(HelloGUI, HandleControlClicked));
}
Beispiel #6
0
bool TextureCube::SetSize(int size, unsigned format, TextureUsage usage, int multiSample)
{
    if (size <= 0)
    {
        URHO3D_LOGERROR("Zero or negative cube texture size");
        return false;
    }
    if (usage == TEXTURE_DEPTHSTENCIL)
    {
        URHO3D_LOGERROR("Depth-stencil usage not supported for cube textures");
        return false;
    }

    multiSample = Clamp(multiSample, 1, 16);
    if (multiSample > 1 && usage < TEXTURE_RENDERTARGET)
    {
        URHO3D_LOGERROR("Multisampling is only supported for rendertarget cube textures");
        return false;
    }

    // Delete the old rendersurfaces if any
    for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
    {
        renderSurfaces_[i].Reset();
        faceMemoryUse_[i] = 0;
    }

    usage_ = usage;

    if (usage == TEXTURE_RENDERTARGET)
    {
        for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
        {
            renderSurfaces_[i] = new RenderSurface(this);
#ifdef URHO3D_OPENGL
            renderSurfaces_[i]->target_ = GL_TEXTURE_CUBE_MAP_POSITIVE_X + i;
#endif
        }

        // Nearest filtering by default
        filterMode_ = FILTER_NEAREST;
    }

    if (usage == TEXTURE_RENDERTARGET)
        SubscribeToEvent(E_RENDERSURFACEUPDATE, URHO3D_HANDLER(TextureCube, HandleRenderSurfaceUpdate));
    else
        UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);

    width_ = size;
    height_ = size;
    depth_ = 1;
    format_ = format;
    multiSample_ = multiSample;
    autoResolve_ = multiSample > 1;

    return Create();
}
 /// Called before the first update. At this point all other components of the node should exist. Will also be called if update events are not wanted; in that case the event is immediately unsubscribed afterward.
 void PlayerInterface::DelayedStart()
 {
     // Show UI
     
     // Ensure UI matches size correctly
     
     // Subscribe to events
     SubscribeToEvent(Urho3D::E_POSTRENDERUPDATE, URHO3D_HANDLER(PlayerInterface, HandlePostRenderUpdate));
 }
WindowConfirmExit::WindowConfirmExit(Context *) :
    lWindow()
{
    SET_VERTICAL_LAYOUT_0_6(this);
    SharedPtr<Label> label(Label::Create("Exit in OS?"));
    AddChild(label);

    SharedPtr<UIElement> layer(CreateChild<UIElement>());
    SET_HORIZONTAL_LAYOUT_6_6(layer);
    
    buttonOk = new ButtonMain(layer, "Ok");
    buttonCancel = new ButtonMain(layer, "Cancel");

    SubscribeToEvent(buttonOk, Urho3D::E_RELEASED, URHO3D_HANDLER(WindowConfirmExit, HandleButtonRelease));
    SubscribeToEvent(buttonCancel, Urho3D::E_RELEASED, URHO3D_HANDLER(WindowConfirmExit, HandleButtonRelease));

    AddChild(layer);
}
Beispiel #9
0
Pickup::Pickup(Context *context, MasterControl *masterControl):
    SceneObject(context, masterControl),
    sinceLastPickup_{0.0f},
    chaoInterval_{Random(23.0f, 100.0f)}
{
    rootNode_->SetName("Pickup");
    graphicsNode_ = rootNode_->CreateChild("Graphics");

    model_ = graphicsNode_->CreateComponent<StaticModel>();
    rootNode_->SetScale(0.8f);
    rootNode_->SetEnabledRecursive(false);

    rigidBody_ = rootNode_->CreateComponent<RigidBody>();
    rigidBody_->SetRestitution(0.666f);
    rigidBody_->SetMass(0.666f);
    rigidBody_->SetLinearFactor(Vector3::ONE - Vector3::UP);
    rigidBody_->SetLinearDamping(0.5f);
    rigidBody_->SetFriction(0.0f);
    rigidBody_->SetAngularFactor(Vector3::UP);
    rigidBody_->SetAngularDamping(0.0f);
    rigidBody_->ApplyTorque(Vector3::UP * 32.0f);
    rigidBody_->SetLinearRestThreshold(0.0f);
    rigidBody_->SetAngularRestThreshold(0.0f);

    CollisionShape* collisionShape = rootNode_->CreateComponent<CollisionShape>();
    collisionShape->SetSphere(1.5f);

    masterControl_->tileMaster_->AddToAffectors(WeakPtr<Node>(rootNode_), WeakPtr<RigidBody>(rigidBody_));

    triggerNode_ = masterControl_->world.scene->CreateChild("PickupTrigger");
    triggerBody_ = triggerNode_->CreateComponent<RigidBody>();
    triggerBody_->SetTrigger(true);
    triggerBody_->SetMass(0.0f);
    triggerBody_->SetLinearFactor(Vector3::ZERO);
    CollisionShape* triggerShape = triggerNode_->CreateComponent<CollisionShape>();
    triggerShape->SetSphere(2.5f);

    particleEmitter_ = graphicsNode_->CreateComponent<ParticleEmitter>();

    particleEmitter_->SetEffect(masterControl_->cache_->GetTempResource<ParticleEffect>("Resources/Particles/Shine.xml"));

    SubscribeToEvent(triggerNode_, E_NODECOLLISIONSTART, URHO3D_HANDLER(Pickup, HandleTriggerStart));
    SubscribeToEvent(E_SCENEUPDATE, URHO3D_HANDLER(Pickup, HandleSceneUpdate));
}
Beispiel #10
0
void MainGameState::create_right_click_menu(int mouse_x, int mouse_y) {
    Urho3D::Window *menu = ui_factory.create_window("right_click_menu");
    ui_factory.m_sub_root_map["right_click_menu"]->AddChild(menu);
    menu->SetLayout(Urho3D::LM_VERTICAL);

    std::cout << mouse_x << " " << mouse_y << std::endl;
    ui_factory.m_sub_root_map["right_click_menu"]->SetPosition(mouse_x, mouse_y);
    Urho3D::UIElement *button_row = ui_factory.create_row(0);
    menu->AddChild(button_row);
    Urho3D::UIElement *chop = ui_factory.create_button("Chop", 30, 30);
    SubscribeToEvent(chop, Urho3D::E_RELEASED, URHO3D_HANDLER(MainGameState, start_select_chop));
    button_row->AddChild(chop);
    Urho3D::UIElement *gather = ui_factory.create_button("Gather", 30, 30);
    button_row->AddChild(gather);
    Urho3D::UIElement *pl = ui_factory.create_button("Placeholder", 30, 30);
    SubscribeToEvent(gather, Urho3D::E_RELEASED,
                     URHO3D_HANDLER(MainGameState, start_select_gather));
    button_row->AddChild(pl);
}
Beispiel #11
0
void MoveController::SetUpJumpSensor() {
    sensor = node_->CreateChild("jump_sensor");
    const auto collision = node_->GetDerivedComponent<CollisionBox2D>();
    sensor->SetPosition2D(0.0, -collision->GetSize().y_ / 2);

    const auto rigidBody = sensor->CreateComponent<RigidBody2D>();
    rigidBody->SetAllowSleep(false);
    rigidBody->SetBodyType(BT_DYNAMIC);
    rigidBody->SetMass(0.0);
    rigidBody->SetGravityScale(0.0f);
    rigidBody->SetVolatilePosition(true);

    CollisionBox2D *box = sensor->CreateComponent<CollisionBox2D>();
    box->SetTrigger(true);
    box->SetGroupIndex(-((short) node_->GetID()));
    box->SetSize(collision->GetSize().x_ * 0.7f, 0.01f);

    sensor->SubscribeToEvent(E_PHYSICSBEGINCONTACT2D, URHO3D_HANDLER(MoveController, BeginSense));
    sensor->SubscribeToEvent(E_PHYSICSENDCONTACT2D, URHO3D_HANDLER(MoveController, StopSense));
}
void RotateTo::Start()
{
	//SubscribeToURHO3D_EVENT(E_SETCLIENTMODELNODE, URHO3D_HANDLER(RotateTo, HandleSetClientModelNode));
	SubscribeToEvent(E_ROTATEMODELNODE, URHO3D_HANDLER(RotateTo, HandleRotateModelNode));

	/*VariantMap vm;
	vm[GetClientModelNode::P_NODE] = node_;
	SendURHO3D_EVENT(E_GETCLIENTMODELNODE, vm);*/

	SetUpdateEventMask(USE_FIXEDUPDATE);
}
Beispiel #13
0
bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage, int multiSample, bool autoResolve)
{
    if (width <= 0 || height <= 0)
    {
        URHO3D_LOGERROR("Zero or negative texture dimensions");
        return false;
    }

    multiSample = Clamp(multiSample, 1, 16);
    if (multiSample == 1)
        autoResolve = false;
    else if (multiSample > 1 && usage < TEXTURE_RENDERTARGET)
    {
        URHO3D_LOGERROR("Multisampling is only supported for rendertarget or depth-stencil textures");
        return false;
    }

    // Disable mipmaps if multisample & custom resolve
    if (multiSample > 1 && autoResolve == false)
        requestedLevels_ = 1;

    // Delete the old rendersurface if any
    renderSurface_.Reset();

    usage_ = usage;

    if (usage >= TEXTURE_RENDERTARGET)
    {
        renderSurface_ = new RenderSurface(this);

        // Clamp mode addressing by default and nearest filtering
        addressModes_[COORD_U] = ADDRESS_CLAMP;
        addressModes_[COORD_V] = ADDRESS_CLAMP;
        filterMode_ = FILTER_NEAREST;
    }

    if (usage == TEXTURE_RENDERTARGET)
        SubscribeToEvent(E_RENDERSURFACEUPDATE, URHO3D_HANDLER(Texture2D, HandleRenderSurfaceUpdate));
    else
        UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);

    width_ = width;
    height_ = height;
    format_ = format;
    depth_ = 1;
    multiSample_ = multiSample;
    autoResolve_ = autoResolve;

    return Create();
}
Beispiel #14
0
void StaticModel::SetModel(Model* model)
{
    if (model == model_)
        return;

    // If script erroneously calls StaticModel::SetModel on an AnimatedModel, warn and redirect
    if (GetType() == AnimatedModel::GetTypeStatic())
    {
        URHO3D_LOGWARNING("StaticModel::SetModel() called on AnimatedModel. Redirecting to AnimatedModel::SetModel()");
        AnimatedModel* animatedModel = static_cast<AnimatedModel*>(this);
        animatedModel->SetModel(model);
        return;
    }

    // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
    if (model_)
        UnsubscribeFromEvent(model_, E_RELOADFINISHED);

    model_ = model;

    if (model)
    {
        SubscribeToEvent(model, E_RELOADFINISHED, URHO3D_HANDLER(StaticModel, HandleModelReloadFinished));

        // Copy the subgeometry & LOD level structure
        SetNumGeometries(model->GetNumGeometries());
        const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
        const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
        const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : (const Matrix3x4*)0;
        for (unsigned i = 0; i < geometries.Size(); ++i)
        {
            batches_[i].worldTransform_ = worldTransform;
            geometries_[i] = geometries[i];
            geometryData_[i].center_ = geometryCenters[i];
        }

        SetBoundingBox(model->GetBoundingBox());
        ResetLodLevels();
    }
    else
    {
        SetNumGeometries(0);
        SetBoundingBox(BoundingBox());
    }

    MarkNetworkUpdate();
}
Beispiel #15
0
void StaticModel::SetModel(Model* model)
{
    if (model == model_)
        return;

    if (!node_)
    {
        URHO3D_LOGERROR("Can not set model while model component is not attached to a scene node");
        return;
    }

    // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
    if (model_)
        UnsubscribeFromEvent(model_, E_RELOADFINISHED);

    model_ = model;

    if (model)
    {
        SubscribeToEvent(model, E_RELOADFINISHED, URHO3D_HANDLER(StaticModel, HandleModelReloadFinished));

        // Copy the subgeometry & LOD level structure
        SetNumGeometries(model->GetNumGeometries());
        const ea::vector<ea::vector<ea::shared_ptr<Geometry> > >& geometries = model->GetGeometries();
        const ea::vector<Vector3>& geometryCenters = model->GetGeometryCenters();
        const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : nullptr;
        for (unsigned i = 0; i < geometries.size(); ++i)
        {
            batches_[i].worldTransform_ = worldTransform;
            geometries_[i] = geometries[i];
            geometryData_[i].center_ = geometryCenters[i];
        }

        SetBoundingBox(model->GetBoundingBox());
        ResetLodLevels();
    }
    else
    {
        SetNumGeometries(0);
        SetBoundingBox(BoundingBox());
    }

    MarkNetworkUpdate();
}
Beispiel #16
0
bool TextureCube::SetSize(int size, unsigned format, TextureUsage usage)
{
    if (size <= 0)
    {
        URHO3D_LOGERROR("Zero or negative cube texture size");
        return false;
    }
    if (usage == TEXTURE_DEPTHSTENCIL)
    {
        URHO3D_LOGERROR("Depth-stencil usage not supported for cube maps");
        return false;
    }

    // Delete the old rendersurfaces if any
    for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
    {
        renderSurfaces_[i].Reset();
        faceMemoryUse_[i] = 0;
    }

    usage_ = usage;
    if (usage_ == TEXTURE_RENDERTARGET)
    {
        for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
            renderSurfaces_[i] = new RenderSurface(this);

        // Nearest filtering and mipmaps disabled by default
        filterMode_ = FILTER_NEAREST;
        requestedLevels_ = 1;
    }

    if (usage_ == TEXTURE_RENDERTARGET)
        SubscribeToEvent(E_RENDERSURFACEUPDATE, URHO3D_HANDLER(TextureCube, HandleRenderSurfaceUpdate));
    else
        UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);

    width_ = size;
    height_ = size;
    format_ = format;

    return Create();
}
GraphicsWorld::GraphicsWorld(UrhoRenderer* owner, Scene* scene) :
    Object(owner->GetContext()),
    framework_(scene->GetFramework()),
    renderer_(owner),
    scene_(scene)
{
    urhoScene_ = new Urho3D::Scene(context_);
    urhoScene_->CreateComponent<Urho3D::Octree>();
    urhoScene_->CreateComponent<Urho3D::DebugRenderer>();

    // Set a default ambient color that matches the default ambient color of EnvironmentLight, in case there is no environmentlight component.
    Urho3D::Zone* zone = urhoScene_->CreateComponent<Urho3D::Zone>();
    // Just set up a large bounding zone for the whole scene
    /// \todo The octree size is not adjusted yet, so objects outside the default octree range always end up in the root octqant
    zone->SetBoundingBox(Urho3D::BoundingBox(-100000.0f, 100000.0f));
    zone->SetAmbientColor(DefaultSceneAmbientLightColor());
    
    SetDefaultSceneFog();

    SubscribeToEvent(Urho3D::E_POSTRENDERUPDATE, URHO3D_HANDLER(GraphicsWorld, HandlePostRenderUpdate));
}
Beispiel #18
0
void Text::SetAutoLocalizable(bool enable)
{
    if (enable != autoLocalizable_)
    {
        autoLocalizable_ = enable;
        if (enable)
        {
            stringId_ = text_;
            auto* l10n = GetSubsystem<Localization>();
            text_ = l10n->Get(stringId_);
            SubscribeToEvent(E_CHANGELANGUAGE, URHO3D_HANDLER(Text, HandleChangeLanguage));
        }
        else
        {
            text_ = stringId_;
            stringId_ = "";
            UnsubscribeFromEvent(E_CHANGELANGUAGE);
        }
        DecodeToUnicode();
        ValidateSelection();
        UpdateText();
    }
}
Beispiel #19
0
UIComponent::UIComponent(Context* context)
    : Component(context),
    viewportIndex_(0)
{
    texture_ = context_->CreateObject<Texture2D>();
    texture_->SetFilterMode(FILTER_BILINEAR);
    texture_->SetAddressMode(COORD_U, ADDRESS_CLAMP);
    texture_->SetAddressMode(COORD_V, ADDRESS_CLAMP);
    texture_->SetNumLevels(1);                                        // No mipmaps

    rootElement_ = context_->CreateObject<UIElement3D>();
    rootElement_->SetTraversalMode(TM_BREADTH_FIRST);
    rootElement_->SetEnabled(true);

    material_ = context_->CreateObject<Material>();
    material_->SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/Diff.xml"));
    material_->SetTexture(TU_DIFFUSE, texture_);

    SubscribeToEvent(rootElement_, E_RESIZED, URHO3D_HANDLER(UIComponent, OnElementResized));

    // Triggers resizing of texture.
    rootElement_->SetRenderTexture(texture_);
    rootElement_->SetSize(UICOMPONENT_DEFAULT_TEXTURE_SIZE, UICOMPONENT_DEFAULT_TEXTURE_SIZE);
}
Beispiel #20
0
void MyGame::SubscribeToEvents() {
    // Subscribe HandleUpdate() function for processing update events
    SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(MyGame, HandleUpdate));
}
Beispiel #21
0
void Gravity::Start()
{
	SubscribeToEvent(E_GETCLIENTGRAVITY, URHO3D_HANDLER(Gravity, HandleGetGravity));
}
Beispiel #22
0
void HelloWorld::SubscribeToEvents()
{
    // Subscribe HandleUpdate() function for processing update events
    SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(HelloWorld, HandleUpdate));
}
Beispiel #23
0
void Sky::Update()
{
    if (!urhoNode_)
        return;

    Urho3D::ResourceCache* cache = GetSubsystem<Urho3D::ResourceCache>();

    if (material_ != nullptr && textureRefListListener_->Assets().Size() < 6)
    {
        // Use material as is

        ///\todo Remove diff color setting once DefaultOgreMaterialProcessor sets it properly.
        material_->UrhoMaterial()->SetShaderParameter("MatDiffColor", Urho3D::Vector4(1, 1, 1, 1));
        material_->UrhoMaterial()->SetCullMode(Urho3D::CULL_NONE);
        urhoNode_->GetComponent<Urho3D::Skybox>()->SetMaterial(material_->UrhoMaterial());
        return;
    }

    Vector<SharedPtr<Urho3D::Image> > images(6);
    Vector<AssetPtr> textureAssets = textureRefListListener_->Assets();
    int numLoadedImages = 0;
    for(uint mi=0; mi<textureAssets.Size(); ++mi)
    {
        AssetPtr &TextureAssetPtr = textureAssets[mi];
        BinaryAsset *binaryAsset = dynamic_cast<BinaryAsset*>(TextureAssetPtr.Get());
        TextureAsset *textureAsset = dynamic_cast<TextureAsset*>(TextureAssetPtr.Get());
        if ((textureAsset || binaryAsset) && TextureAssetPtr->IsLoaded())
        {
            SharedPtr<Urho3D::Image> image = SharedPtr<Urho3D::Image>(new Urho3D::Image(GetContext()));
            Vector<u8> data;
            if (binaryAsset)
                data = binaryAsset->data;
            ///\todo Loading raw image data from disksource leaves an extra GPU texture resource unused.
            else if (!LoadFileToVector(textureAsset->DiskSource(), data))
                continue;

            Urho3D::MemoryBuffer imageBuffer(&data[0], data.Size());
            if (!image->Load(imageBuffer))
                continue;

            images[mi] = image;
            numLoadedImages++;
        }
    }

    if (numLoadedImages == 6)
    {
        // Reuse the previous cube texture if possible
        SharedPtr<Urho3D::TextureCube> textureCube = (cubeTexture_.Get() == nullptr) ? SharedPtr<Urho3D::TextureCube>(new Urho3D::TextureCube(GetContext())) : cubeTexture_.Lock();

        const Urho3D::CubeMapFace faces[6] = { Urho3D::FACE_POSITIVE_X, Urho3D::FACE_NEGATIVE_X, Urho3D::FACE_POSITIVE_Y, Urho3D::FACE_NEGATIVE_Y, Urho3D::FACE_POSITIVE_Z, Urho3D::FACE_NEGATIVE_Z };
        const int faceOrder[6] = { 3, 2, 4, 5, 0, 1 };

        for (size_t i=0 ; i<images.Size() ; ++i)
            if (images[faceOrder[i]] != nullptr)
                textureCube->SetData(faces[i], images[faceOrder[i]]);

        // Remember the created texture for tracking device loss
        cubeTexture_ = textureCube;
        SubscribeToEvent(Urho3D::E_DEVICERESET, URHO3D_HANDLER(Sky, HandleDeviceReset));

        SharedPtr<Urho3D::Material> material;
        if (material_)
            material = material_->UrhoMaterial()->Clone();
        else
            material = SharedPtr<Urho3D::Material>(new Urho3D::Material(GetContext()));
        material->SetCullMode(Urho3D::CULL_NONE);
        material->SetTechnique(0, cache->GetResource<Urho3D::Technique>("Techniques/DiffSkybox.xml"));
        material->SetTexture(Urho3D::TU_DIFFUSE, textureCube);
        ///\todo Remove diff color setting once DefaultOgreMaterialProcessor sets it properly.
        material->SetShaderParameter("MatDiffColor", Urho3D::Vector4(1, 1, 1, 1));
    
        urhoNode_->GetComponent<Urho3D::Skybox>()->SetMaterial(material);
    } 
    else
    {
        if (GetFramework()->HasCommandLineParameter("--useErrorAsset"))
        {
            urhoNode_->GetComponent<Urho3D::Skybox>()->SetMaterial(cache->GetResource<Urho3D::Material>("Materials/AssetLoadError.xml"));
        }
    }
}
Beispiel #24
0
void Spire::Set(Vector3 position)
{
    shotInterval_ = initialShotInterval_;
    Enemy::Set(position);
    SubscribeToEvent(E_SCENEPOSTUPDATE, URHO3D_HANDLER(Spire, HandleSpireUpdate));
}
Beispiel #25
0
PlanetComponent::PlanetComponent(Context* context) : LogicComponent(context)
{
    SetUpdateEventMask(USE_FIXEDUPDATE | USE_UPDATE);
    SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(PlanetComponent, HandlePostRenderUpdate));
}
Beispiel #26
0
//---------------------------------------------------------------------------------------------------------------------------------------------------
void TerminalTWT::SubscribeToEvents()
{
    SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(TerminalTWT, HandlePostUpdate));
}
Beispiel #27
0
void MainGameState::subscribe_to_events() {
    SubscribeToEvent(Urho3D::E_MOUSEBUTTONUP, URHO3D_HANDLER(MainGameState, HandleMouseButtonUp));
    SubscribeToEvent(Urho3D::E_MOUSEBUTTONDOWN,
                     URHO3D_HANDLER(MainGameState, HandleMouseButtonDown));
    SubscribeToEvent(Urho3D::E_MOUSEWHEEL, URHO3D_HANDLER(MainGameState, HandleMouseWheel));
}
Beispiel #28
0
void Mortal::Start() {
    SubscribeToEvent(node_, EVENT_RECEIVE_DAMAGE, URHO3D_HANDLER(Mortal, ReceiveDamage));
}
Beispiel #29
0
void RigidBody::AddBodyToWorld()
{
    if (!physicsWorld_)
        return;

    URHO3D_PROFILE(AddBodyToWorld);

    if (mass_ < 0.0f)
        mass_ = 0.0f;

    if (body_)
        RemoveBodyFromWorld();
    else
    {
        // Correct inertia will be calculated below
        btVector3 localInertia(0.0f, 0.0f, 0.0f);
        body_ = new btRigidBody(mass_, this, shiftedCompoundShape_, localInertia);
        body_->setUserPointer(this);

        // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
        // If it exists, subscribe to its change events
        smoothedTransform_ = GetComponent<SmoothedTransform>();
        if (smoothedTransform_)
        {
            SubscribeToEvent(smoothedTransform_, E_TARGETPOSITION, URHO3D_HANDLER(RigidBody, HandleTargetPosition));
            SubscribeToEvent(smoothedTransform_, E_TARGETROTATION, URHO3D_HANDLER(RigidBody, HandleTargetRotation));
        }

        // Check if CollisionShapes already exist in the node and add them to the compound shape.
        // Do not update mass yet, but do it once all shapes have been added
        PODVector<CollisionShape*> shapes;
        node_->GetComponents<CollisionShape>(shapes);
        for (PODVector<CollisionShape*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
            (*i)->NotifyRigidBody(false);

        // Check if this node contains Constraint components that were waiting for the rigid body to be created, and signal them
        // to create themselves now
        PODVector<Constraint*> constraints;
        node_->GetComponents<Constraint>(constraints);
        for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
            (*i)->CreateConstraint();
    }

    UpdateMass();
    UpdateGravity();

    int flags = body_->getCollisionFlags();
    if (trigger_)
        flags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
    else
        flags &= ~btCollisionObject::CF_NO_CONTACT_RESPONSE;
    if (kinematic_)
        flags |= btCollisionObject::CF_KINEMATIC_OBJECT;
    else
        flags &= ~btCollisionObject::CF_KINEMATIC_OBJECT;
    body_->setCollisionFlags(flags);
    body_->forceActivationState(kinematic_ ? DISABLE_DEACTIVATION : ISLAND_SLEEPING);

    if (!IsEnabledEffective())
        return;

    btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
    world->addRigidBody(body_, (short)collisionLayer_, (short)collisionMask_);
    inWorld_ = true;
    readdBody_ = false;

    if (mass_ > 0.0f)
        Activate();
    else
    {
        SetLinearVelocity(Vector3::ZERO);
        SetAngularVelocity(Vector3::ZERO);
    }
}
Beispiel #30
0
void Urho3DPlayer::Start()
{
    // Reattempt reading the command line now on Web platform
#ifdef __EMSCRIPTEN__
    if (GetArguments().Empty())
    {
        SharedPtr<File> commandFile = GetSubsystem<ResourceCache>()->GetFile("CommandLine.txt", false);
        if (commandFile)
        {
            String commandLine = commandFile->ReadLine();
            commandFile->Close();
            ParseArguments(commandLine, false);
        }
    }

    GetScriptFileName();

    if (scriptFileName_.Empty())
    {
        ErrorExit("Script file name not specified; cannot proceed");
        return;
    }
#endif

    String extension = GetExtension(scriptFileName_);
    if (extension != ".lua" && extension != ".luc")
    {
#ifdef URHO3D_ANGELSCRIPT
        // Instantiate and register the AngelScript subsystem
        context_->RegisterSubsystem(new Script(context_));

        // Hold a shared pointer to the script file to make sure it is not unloaded during runtime
        scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_);

        /// \hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances
#ifdef URHO3D_LUA
        if (scriptFileName_.Contains("Editor.as", false))
            context_->RegisterSubsystem(new LuaScript(context_));
#endif
        // If script loading is successful, proceed to main loop
        if (scriptFile_ && scriptFile_->Execute("void Start()"))
        {
            // Subscribe to script's reload event to allow live-reload of the application
            SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted));
            SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished));
            SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed));
            return;
        }
#else
        ErrorExit("AngelScript is not enabled!");
        return;
#endif
    }
    else
    {
#ifdef URHO3D_LUA
        // Instantiate and register the Lua script subsystem
        LuaScript* luaScript = new LuaScript(context_);
        context_->RegisterSubsystem(luaScript);

        // If script loading is successful, proceed to main loop
        if (luaScript->ExecuteFile(scriptFileName_))
        {
            luaScript->ExecuteFunction("Start");
            return;
        }
#else
        ErrorExit("Lua is not enabled!");
        return;
#endif
    }

    // The script was not successfully loaded. Show the last error message and do not run the main loop
    ErrorExit();
}