1 //
2 // Copyright (c) 2008-2017 the Urho3D project.
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21 //
22 
23 #include <Urho3D/Core/CoreEvents.h>
24 #include <Urho3D/Engine/Engine.h>
25 #include <Urho3D/Graphics/Camera.h>
26 #include <Urho3D/Graphics/Graphics.h>
27 #include <Urho3D/Graphics/Material.h>
28 #include <Urho3D/Graphics/Model.h>
29 #include <Urho3D/Graphics/Octree.h>
30 #include <Urho3D/Graphics/Renderer.h>
31 #include <Urho3D/Graphics/StaticModel.h>
32 #include <Urho3D/Graphics/Zone.h>
33 #include <Urho3D/Input/Input.h>
34 #include <Urho3D/LuaScript/LuaFile.h>
35 #include <Urho3D/LuaScript/LuaFunction.h>
36 #include <Urho3D/LuaScript/LuaScript.h>
37 #include <Urho3D/LuaScript/LuaScriptInstance.h>
38 #include <Urho3D/Resource/ResourceCache.h>
39 #include <Urho3D/Scene/Scene.h>
40 #include <Urho3D/UI/Font.h>
41 #include <Urho3D/UI/Text.h>
42 #include <Urho3D/UI/UI.h>
43 
44 #include "LuaIntegration.h"
45 
46 #include <Urho3D/DebugNew.h>
47 
URHO3D_DEFINE_APPLICATION_MAIN(LuaIntegration)48 URHO3D_DEFINE_APPLICATION_MAIN(LuaIntegration)
49 
50 LuaIntegration::LuaIntegration(Context* context) :
51     Sample(context)
52 {
53     // Instantiate and register the Lua script subsystem so that we can use the LuaScriptInstance component
54     context_->RegisterSubsystem(new LuaScript(context_));
55 }
56 
Start()57 void LuaIntegration::Start()
58 {
59     // Execute base class startup
60     Sample::Start();
61 
62     // Create the scene content
63     CreateScene();
64 
65     // Create the UI content
66     CreateInstructions();
67 
68     // Setup the viewport for displaying the scene
69     SetupViewport();
70 
71     // Hook up to the frame update events
72     SubscribeToEvents();
73 
74     // Set the mouse mode to use in the sample
75     Sample::InitMouseMode(MM_RELATIVE);
76 }
77 
CreateScene()78 void LuaIntegration::CreateScene()
79 {
80     ResourceCache* cache = GetSubsystem<ResourceCache>();
81 
82     scene_ = new Scene(context_);
83 
84     // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
85     // (-1000, -1000, -1000) to (1000, 1000, 1000)
86     scene_->CreateComponent<Octree>();
87 
88     // Create a Zone component into a child scene node. The Zone controls ambient lighting and fog settings. Like the Octree,
89     // 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
90     // and Z axes.) Drawable objects "pick up" the zone they belong to and use it when rendering; several zones can exist
91     Node* zoneNode = scene_->CreateChild("Zone");
92     Zone* zone = zoneNode->CreateComponent<Zone>();
93     // Set same volume as the Octree, set a close bluish fog and some ambient light
94     zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
95     zone->SetAmbientColor(Color(0.05f, 0.1f, 0.15f));
96     zone->SetFogColor(Color(0.1f, 0.2f, 0.3f));
97     zone->SetFogStart(10.0f);
98     zone->SetFogEnd(100.0f);
99 
100     LuaFile* scriptFile = cache->GetResource<LuaFile>("LuaScripts/Utilities/Rotator.lua");
101     if (!scriptFile)
102         return;
103 
104     // Create randomly positioned and oriented box StaticModels in the scene
105     const unsigned NUM_OBJECTS = 2000;
106     for (unsigned i = 0; i < NUM_OBJECTS; ++i)
107     {
108         Node* boxNode = scene_->CreateChild("Box");
109         boxNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(200.0f) - 100.0f, Random(200.0f) - 100.0f));
110         // Orient using random pitch, yaw and roll Euler angles
111         boxNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
112         StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
113         boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
114         boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
115 
116         // Add our custom Rotator script object (using the LuaScriptInstance C++ component to instantiate / store it) which will
117         // rotate the scene node each frame, when the scene sends its update event
118         LuaScriptInstance* instance = boxNode->CreateComponent<LuaScriptInstance>();
119         instance->CreateObject(scriptFile, "Rotator");
120 
121         // Call the script object's "SetRotationSpeed" function.
122         LuaFunction* function = instance->GetScriptObjectFunction("SetRotationSpeed");
123         if (function && function->BeginCall(instance))
124         {
125             function->PushUserType(Vector3(10.0f, 20.0f, 30.0f), "Vector3");
126             function->EndCall();
127         }
128     }
129 
130     // Create the camera. Let the starting position be at the world origin. As the fog limits maximum visible distance, we can
131     // bring the far clip plane closer for more effective culling of distant objects
132     cameraNode_ = scene_->CreateChild("Camera");
133     Camera* camera = cameraNode_->CreateComponent<Camera>();
134     camera->SetFarClip(100.0f);
135 
136     // Create a point light to the camera scene node
137     Light* light = cameraNode_->CreateComponent<Light>();
138     light->SetLightType(LIGHT_POINT);
139     light->SetRange(30.0f);
140 }
141 
CreateInstructions()142 void LuaIntegration::CreateInstructions()
143 {
144     ResourceCache* cache = GetSubsystem<ResourceCache>();
145     UI* ui = GetSubsystem<UI>();
146 
147     // Construct new Text object, set string to display and font to use
148     Text* instructionText = ui->GetRoot()->CreateChild<Text>();
149     instructionText->SetText("Use WASD keys and mouse/touch to move");
150     instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
151 
152     // Position the text relative to the screen center
153     instructionText->SetHorizontalAlignment(HA_CENTER);
154     instructionText->SetVerticalAlignment(VA_CENTER);
155     instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
156 }
157 
SetupViewport()158 void LuaIntegration::SetupViewport()
159 {
160     Renderer* renderer = GetSubsystem<Renderer>();
161 
162     // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
163     SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
164     renderer->SetViewport(0, viewport);
165 }
166 
SubscribeToEvents()167 void LuaIntegration::SubscribeToEvents()
168 {
169     // Subscribe HandleUpdate() function for processing update events
170     SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(LuaIntegration, HandleUpdate));
171 }
172 
MoveCamera(float timeStep)173 void LuaIntegration::MoveCamera(float timeStep)
174 {
175     // Do not move if the UI has a focused element (the console)
176     if (GetSubsystem<UI>()->GetFocusElement())
177         return;
178 
179     Input* input = GetSubsystem<Input>();
180 
181     // Movement speed as world units per second
182     const float MOVE_SPEED = 20.0f;
183     // Mouse sensitivity as degrees per pixel
184     const float MOUSE_SENSITIVITY = 0.1f;
185 
186     // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
187     IntVector2 mouseMove = input->GetMouseMove();
188     yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
189     pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
190     pitch_ = Clamp(pitch_, -90.0f, 90.0f);
191 
192     // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
193     cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
194 
195     // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
196     if (input->GetKeyDown(KEY_W))
197         cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
198     if (input->GetKeyDown(KEY_S))
199         cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
200     if (input->GetKeyDown(KEY_A))
201         cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
202     if (input->GetKeyDown(KEY_D))
203         cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
204 }
205 
HandleUpdate(StringHash eventType,VariantMap & eventData)206 void LuaIntegration::HandleUpdate(StringHash eventType, VariantMap& eventData)
207 {
208     using namespace Update;
209 
210     // Take the frame time step, which is stored as a float
211     float timeStep = eventData[P_TIMESTEP].GetFloat();
212 
213     // Move the camera, scale movement with time step
214     MoveCamera(timeStep);
215 }
216