LuaIntegration.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. //
  2. // Copyright (c) 2008-2015 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. #include <Urho3D/Core/CoreEvents.h>
  23. #include <Urho3D/Engine/Engine.h>
  24. #include <Urho3D/Graphics/Camera.h>
  25. #include <Urho3D/Graphics/Graphics.h>
  26. #include <Urho3D/Graphics/Material.h>
  27. #include <Urho3D/Graphics/Model.h>
  28. #include <Urho3D/Graphics/Octree.h>
  29. #include <Urho3D/Graphics/Renderer.h>
  30. #include <Urho3D/Graphics/StaticModel.h>
  31. #include <Urho3D/Graphics/Zone.h>
  32. #include <Urho3D/Input/Input.h>
  33. #include <Urho3D/LuaScript/LuaFile.h>
  34. #include <Urho3D/LuaScript/LuaFunction.h>
  35. #include <Urho3D/LuaScript/LuaScript.h>
  36. #include <Urho3D/LuaScript/LuaScriptInstance.h>
  37. #include <Urho3D/Resource/ResourceCache.h>
  38. #include <Urho3D/Scene/Scene.h>
  39. #include <Urho3D/UI/Font.h>
  40. #include <Urho3D/UI/Text.h>
  41. #include <Urho3D/UI/UI.h>
  42. #include "LuaIntegration.h"
  43. #include <Urho3D/DebugNew.h>
  44. DEFINE_APPLICATION_MAIN(LuaIntegration)
  45. LuaIntegration::LuaIntegration(Context* context) :
  46. Sample(context)
  47. {
  48. // Instantiate and register the Lua script subsystem so that we can use the LuaScriptInstance component
  49. context_->RegisterSubsystem(new LuaScript(context_));
  50. }
  51. void LuaIntegration::Start()
  52. {
  53. // Execute base class startup
  54. Sample::Start();
  55. // Create the scene content
  56. CreateScene();
  57. // Create the UI content
  58. CreateInstructions();
  59. // Setup the viewport for displaying the scene
  60. SetupViewport();
  61. // Hook up to the frame update events
  62. SubscribeToEvents();
  63. }
  64. void LuaIntegration::CreateScene()
  65. {
  66. ResourceCache* cache = GetSubsystem<ResourceCache>();
  67. scene_ = new Scene(context_);
  68. // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume
  69. // (-1000, -1000, -1000) to (1000, 1000, 1000)
  70. scene_->CreateComponent<Octree>();
  71. // Create a Zone component into a child scene node. The Zone controls ambient lighting and fog settings. Like the Octree,
  72. // 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
  73. // and Z axes.) Drawable objects "pick up" the zone they belong to and use it when rendering; several zones can exist
  74. Node* zoneNode = scene_->CreateChild("Zone");
  75. Zone* zone = zoneNode->CreateComponent<Zone>();
  76. // Set same volume as the Octree, set a close bluish fog and some ambient light
  77. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
  78. zone->SetAmbientColor(Color(0.05f, 0.1f, 0.15f));
  79. zone->SetFogColor(Color(0.1f, 0.2f, 0.3f));
  80. zone->SetFogStart(10.0f);
  81. zone->SetFogEnd(100.0f);
  82. LuaFile* scriptFile = cache->GetResource<LuaFile>("LuaScripts/Rotator.lua");
  83. if (!scriptFile)
  84. return;
  85. // Create randomly positioned and oriented box StaticModels in the scene
  86. const unsigned NUM_OBJECTS = 2000;
  87. for (unsigned i = 0; i < NUM_OBJECTS; ++i)
  88. {
  89. Node* boxNode = scene_->CreateChild("Box");
  90. boxNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(200.0f) - 100.0f, Random(200.0f) - 100.0f));
  91. // Orient using random pitch, yaw and roll Euler angles
  92. boxNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
  93. StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
  94. boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
  95. boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
  96. // Add our custom Rotator script object (using the LuaScriptInstance C++ component to instantiate / store it) which will
  97. // rotate the scene node each frame, when the scene sends its update event
  98. LuaScriptInstance* instance = boxNode->CreateComponent<LuaScriptInstance>();
  99. instance->CreateObject(scriptFile, "Rotator");
  100. // Call the script object's "SetRotationSpeed" function.
  101. LuaFunction* function = instance->GetScriptObjectFunction("SetRotationSpeed");
  102. if (function && function->BeginCall(instance))
  103. {
  104. function->PushUserType(Vector3(10.0f, 20.0f, 30.0f), "Vector3");
  105. function->EndCall();
  106. }
  107. }
  108. // Create the camera. Let the starting position be at the world origin. As the fog limits maximum visible distance, we can
  109. // bring the far clip plane closer for more effective culling of distant objects
  110. cameraNode_ = scene_->CreateChild("Camera");
  111. Camera* camera = cameraNode_->CreateComponent<Camera>();
  112. camera->SetFarClip(100.0f);
  113. // Create a point light to the camera scene node
  114. Light* light = cameraNode_->CreateComponent<Light>();
  115. light->SetLightType(LIGHT_POINT);
  116. light->SetRange(30.0f);
  117. }
  118. void LuaIntegration::CreateInstructions()
  119. {
  120. ResourceCache* cache = GetSubsystem<ResourceCache>();
  121. UI* ui = GetSubsystem<UI>();
  122. // Construct new Text object, set string to display and font to use
  123. Text* instructionText = ui->GetRoot()->CreateChild<Text>();
  124. instructionText->SetText("Use WASD keys and mouse/touch to move");
  125. instructionText->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
  126. // Position the text relative to the screen center
  127. instructionText->SetHorizontalAlignment(HA_CENTER);
  128. instructionText->SetVerticalAlignment(VA_CENTER);
  129. instructionText->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
  130. }
  131. void LuaIntegration::SetupViewport()
  132. {
  133. Renderer* renderer = GetSubsystem<Renderer>();
  134. // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
  135. SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>()));
  136. renderer->SetViewport(0, viewport);
  137. }
  138. void LuaIntegration::SubscribeToEvents()
  139. {
  140. // Subscribe HandleUpdate() function for processing update events
  141. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(LuaIntegration, HandleUpdate));
  142. }
  143. void LuaIntegration::MoveCamera(float timeStep)
  144. {
  145. // Do not move if the UI has a focused element (the console)
  146. if (GetSubsystem<UI>()->GetFocusElement())
  147. return;
  148. Input* input = GetSubsystem<Input>();
  149. // Movement speed as world units per second
  150. const float MOVE_SPEED = 20.0f;
  151. // Mouse sensitivity as degrees per pixel
  152. const float MOUSE_SENSITIVITY = 0.1f;
  153. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  154. IntVector2 mouseMove = input->GetMouseMove();
  155. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  156. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  157. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  158. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  159. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  160. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  161. if (input->GetKeyDown('W'))
  162. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  163. if (input->GetKeyDown('S'))
  164. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  165. if (input->GetKeyDown('A'))
  166. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  167. if (input->GetKeyDown('D'))
  168. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  169. }
  170. void LuaIntegration::HandleUpdate(StringHash eventType, VariantMap& eventData)
  171. {
  172. using namespace Update;
  173. // Take the frame time step, which is stored as a float
  174. float timeStep = eventData[P_TIMESTEP].GetFloat();
  175. // Move the camera, scale movement with time step
  176. MoveCamera(timeStep);
  177. }