Browse Source

Added C++ version of HugeObjectCount example, and animation to both versions.
Added note of event subscription time to the first C++ example.

Lasse Öörni 12 years ago
parent
commit
94a3c80e34

+ 29 - 6
Bin/Data/Scripts/20_HugeObjectCount.as

@@ -8,8 +8,10 @@
 
 Scene@ scene_;
 Node@ cameraNode;
+Array<Node@> boxNodes;
 float yaw = 0.0f;
 float pitch = 0.0f;
+bool animate = false;
 
 void Start()
 {
@@ -37,7 +39,7 @@ void CreateScene()
     // (-1000, -1000, -1000) to (1000, 1000, 1000)
     scene_.CreateComponent("Octree");
 
-    // Create a Zone component for ambient lighting & fog control
+    // Create a Zone for ambient light & fog control
     Node@ zoneNode = scene_.CreateChild("Zone");
     Zone@ zone = zoneNode.CreateComponent("Zone");
     zone.boundingBox = BoundingBox(-1000.0f, 1000.0f);
@@ -62,6 +64,7 @@ void CreateScene()
             boxNode.SetScale(0.25f);
             StaticModel@ boxObject = boxNode.CreateComponent("StaticModel");
             boxObject.model = cache.GetResource("Model", "Models/Box.mdl");
+            boxNodes.Push(boxNode);
         }
     }
 
@@ -76,9 +79,13 @@ void CreateInstructions()
 {
     // Construct new Text object, set string to display and font to use
     Text@ instructionText = ui.root.CreateChild("Text");
-    instructionText.text = "Use WASD keys and mouse to move";
+    instructionText.text = 
+        "Use WASD keys and mouse to move\n"
+        "Space to toggle animation";
     instructionText.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
-
+    // The text has multiple rows. Center them in relation to each other
+    instructionText.textAlignment = HA_CENTER;
+    
     // Position the text relative to the screen center
     instructionText.horizontalAlignment = HA_CENTER;
     instructionText.verticalAlignment= VA_CENTER;
@@ -92,6 +99,12 @@ void SetupViewport()
     renderer.viewports[0] = viewport;
 }
 
+void SubscribeToEvents()
+{
+    // Subscribe HandleUpdate() function for processing update events
+    SubscribeToEvent("Update", "HandleUpdate");
+}
+
 void MoveCamera(float timeStep)
 {
     // Do not move if the UI has a focused element (the console)
@@ -123,10 +136,12 @@ void MoveCamera(float timeStep)
         cameraNode.TranslateRelative(Vector3(1.0f, 0.0f, 0.0f) * MOVE_SPEED * timeStep);
 }
 
-void SubscribeToEvents()
+void AnimateObjects(float timeStep)
 {
-    // Subscribe HandleUpdate() function for processing update events
-    SubscribeToEvent("Update", "HandleUpdate");
+    const float ROTATE_SPEED = 15.0f;
+
+    for (uint i = 0; i < boxNodes.length; ++i)
+        boxNodes[i].Roll(ROTATE_SPEED * timeStep);
 }
 
 void HandleUpdate(StringHash eventType, VariantMap& eventData)
@@ -134,6 +149,14 @@ void HandleUpdate(StringHash eventType, VariantMap& eventData)
     // Take the frame time step, which is stored as a float
     float timeStep = eventData["TimeStep"].GetFloat();
 
+    // Toggle animation with space
+    if (input.keyPress[KEY_SPACE])
+        animate = !animate;
+
     // Move the camera, scale movement with time step
     MoveCamera(timeStep);
+    
+    // Animate scene if enabled
+    if (animate)
+        AnimateObjects(timeStep);
 }

+ 3 - 1
Source/Samples/01_HelloWorld/HelloWorld.cpp

@@ -48,7 +48,9 @@ void HelloWorld::Start()
     // Create "Hello World" Text
     CreateText();
 
-    // Finally, hook-up this HelloWorld instance to handle update events
+    // Finally subscribe to the update event. Note that by subscribing events at this point we have already missed some events
+    // like the ScreenMode event sent by the Graphics subsystem when opening the application window. To catch those as well we
+    // could subscribe in the constructor instead.
     SubscribeToEvents();
 }
 

+ 32 - 0
Source/Samples/20_HugeObjectCount/CMakeLists.txt

@@ -0,0 +1,32 @@
+#
+# Copyright (c) 2008-2013 the Urho3D project.
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+#
+
+# Define target name
+set (TARGET_NAME 20_HugeObjectCount)
+
+# Define source files
+file (GLOB CPP_FILES *.cpp)
+file (GLOB H_FILES *.h)
+set (SOURCE_FILES ${CPP_FILES} ${H_FILES} ${COMMON_SAMPLE_H_FILES})
+
+# Setup target with resource copying
+setup_main_executable ()

+ 216 - 0
Source/Samples/20_HugeObjectCount/HugeObjectCount.cpp

@@ -0,0 +1,216 @@
+//
+// Copyright (c) 2008-2013 the Urho3D project.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#include "Camera.h"
+#include "CoreEvents.h"
+#include "Engine.h"
+#include "Font.h"
+#include "Graphics.h"
+#include "Input.h"
+#include "Material.h"
+#include "Model.h"
+#include "Octree.h"
+#include "Profiler.h"
+#include "Renderer.h"
+#include "ResourceCache.h"
+#include "Scene.h"
+#include "StaticModel.h"
+#include "Text.h"
+#include "UI.h"
+#include "Zone.h"
+
+#include "HugeObjectCount.h"
+
+#include "DebugNew.h"
+
+DEFINE_APPLICATION_MAIN(HugeObjectCount)
+
+HugeObjectCount::HugeObjectCount(Context* context) :
+    Sample(context),
+    yaw_(0.0f),
+    pitch_(0.0f),
+    animate_(false)
+{
+}
+
+void HugeObjectCount::Start()
+{
+    // Execute base class startup
+    Sample::Start();
+
+    // Create the scene content
+    CreateScene();
+    
+    // Create the UI content
+    CreateInstructions();
+    
+    // Setup the viewport for displaying the scene
+    SetupViewport();
+
+    // Hook up to the frame update events
+    SubscribeToEvents();
+}
+
+void HugeObjectCount::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 for ambient light & fog control
+    Node* zoneNode = scene_->CreateChild("Zone");
+    Zone* zone = zoneNode->CreateComponent<Zone>();
+    zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
+    zone->SetFogColor(Color(0.2f, 0.2f, 0.2f));
+    zone->SetFogStart(200.0f);
+    zone->SetFogEnd(300.0f);
+    
+    // Create a directional light
+    Node* lightNode = scene_->CreateChild("DirectionalLight");
+    lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f)); // The direction vector does not need to be normalized
+    Light* light = lightNode->CreateComponent<Light>();
+    light->SetLightType(LIGHT_DIRECTIONAL);
+    light->SetColor(Color(0.7f, 0.35f, 0.0f));
+
+    // Create box StaticModels in the scene
+    for (int y = -125; y < 125; ++y)
+    {
+        for (int x = -125; x < 125; ++x)
+        {
+            Node* boxNode = scene_->CreateChild("Box");
+            boxNode->SetPosition(Vector3(x * 0.3f, 0.0f, y * 0.3f));
+            boxNode->SetScale(0.25f);
+            StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
+            boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
+            boxNodes_.Push(SharedPtr<Node>(boxNode));
+        }
+    }
+    
+    // Create the camera
+    cameraNode_ = scene_->CreateChild("Camera");
+    cameraNode_->SetPosition(Vector3(0.0f, 10.0f, -100.0f));
+    Camera* camera = cameraNode_->CreateComponent<Camera>();
+    camera->SetFarClip(300.0f);
+}
+
+void HugeObjectCount::CreateInstructions()
+{
+    ResourceCache* cache = GetSubsystem<ResourceCache>();
+    UI* ui = GetSubsystem<UI>();
+    
+    // Construct new Text object, set string to display and font to use
+    Text* instructionText = ui->GetRoot()->CreateChild<Text>();
+    instructionText->SetText(
+        "Use WASD keys and mouse to move\n"
+        "Space to toggle animation"
+    );
+    instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
+    // The text has multiple rows. Center them in relation to each other
+    instructionText->SetTextAlignment(HA_CENTER);
+
+    // Position the text relative to the screen center
+    instructionText->SetHorizontalAlignment(HA_CENTER);
+    instructionText->SetVerticalAlignment(VA_CENTER);
+    instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
+}
+
+void HugeObjectCount::SetupViewport()
+{
+    Renderer* renderer = GetSubsystem<Renderer>();
+    
+    // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
+    SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
+    renderer->SetViewport(0, viewport);
+}
+
+void HugeObjectCount::SubscribeToEvents()
+{
+    // Subscribe HandleUpdate() function for processing update events
+    SubscribeToEvent(E_UPDATE, HANDLER(HugeObjectCount, HandleUpdate));
+}
+
+void HugeObjectCount::MoveCamera(float timeStep)
+{
+    // Do not move if the UI has a focused element (the console)
+    if (GetSubsystem<UI>()->GetFocusElement())
+        return;
+    
+    Input* input = GetSubsystem<Input>();
+    
+    // Movement speed as world units per second
+    const float MOVE_SPEED = 20.0f;
+    // Mouse sensitivity as degrees per pixel
+    const float MOUSE_SENSITIVITY = 0.1f;
+    
+    // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
+    IntVector2 mouseMove = input->GetMouseMove();
+    yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
+    pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
+    pitch_ = Clamp(pitch_, -90.0f, 90.0f);
+    
+    // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
+    cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
+    
+    // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
+    if (input->GetKeyDown('W'))
+        cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);
+    if (input->GetKeyDown('S'))
+        cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);
+    if (input->GetKeyDown('A'))
+        cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);
+    if (input->GetKeyDown('D'))
+        cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);
+}
+
+void HugeObjectCount::AnimateObjects(float timeStep)
+{
+    PROFILE(AnimateObjects);
+    
+    const float ROTATE_SPEED = 15.0f;
+
+    for (unsigned i = 0; i < boxNodes_.Size(); ++i)
+        boxNodes_[i]->Roll(ROTATE_SPEED * timeStep);
+}
+
+void HugeObjectCount::HandleUpdate(StringHash eventType, VariantMap& eventData)
+{
+    using namespace Update;
+
+    // Take the frame time step, which is stored as a float
+    float timeStep = eventData[P_TIMESTEP].GetFloat();
+    
+    // Toggle animation with space
+    Input* input = GetSubsystem<Input>();
+    if (input->GetKeyPress(KEY_SPACE))
+        animate_ = !animate_;
+
+    // Move the camera, scale movement with time step
+    MoveCamera(timeStep);
+    
+    // Animate scene if enabled
+    if (animate_)
+        AnimateObjects(timeStep);
+}

+ 80 - 0
Source/Samples/20_HugeObjectCount/HugeObjectCount.h

@@ -0,0 +1,80 @@
+//
+// Copyright (c) 2008-2013 the Urho3D project.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+
+#pragma once
+
+#include "Sample.h"
+
+namespace Urho3D
+{
+    class Node;
+    class Scene;
+}
+
+using namespace Urho3D;
+
+/// Huge object count example.
+///  This sample demonstrates:
+///     - Creating a scene with 250 x 250 simple objects;
+///     - Competing with http://yosoygames.com.ar/wp/2013/07/ogre-2-0-is-up-to-3x-faster/ :)
+///     - Allowing examination of performance hotspots in the rendering code;
+///     - Using the profiler to measure the time taken to animate the scene;
+class HugeObjectCount : public Sample
+{
+    OBJECT(HugeObjectCount);
+
+public:
+    /// Construct.
+    HugeObjectCount(Context* context);
+
+    /// Setup after engine initialization and before running the main loop.
+    virtual void Start();
+
+private:
+    /// Construct the scene content.
+    void CreateScene();
+    /// Construct an instruction text to the UI.
+    void CreateInstructions();
+    /// Set up a viewport for displaying the scene.
+    void SetupViewport();
+    /// Subscribe to application-wide logic update events.
+    void SubscribeToEvents();
+    /// Read input and moves the camera.
+    void MoveCamera(float timeStep);
+    /// Animate the scene.
+    void AnimateObjects(float timeStep);
+    /// Handle the logic update event.
+    void HandleUpdate(StringHash eventType, VariantMap& eventData);
+
+    /// Scene.
+    SharedPtr<Scene> scene_;
+    /// Camera scene node.
+    SharedPtr<Node> cameraNode_;
+    /// Box scene nodes.
+    Vector<SharedPtr<Node> > boxNodes_;
+    /// Camera yaw angle.
+    float yaw_;
+    /// Camera pitch angle.
+    float pitch_;
+    /// Animation flag.
+    bool animate_;
+};

+ 2 - 1
Source/Samples/CMakeLists.txt

@@ -60,4 +60,5 @@ add_subdirectory (15_Navigation)
 add_subdirectory (16_Chat)
 add_subdirectory (17_SceneReplication)
 add_subdirectory (18_CharacterDemo)
-add_subdirectory (19_VehicleDemo)
+add_subdirectory (19_VehicleDemo)
+add_subdirectory (20_HugeObjectCount)