SceneView3D.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. // Portions Copyright (c) 2008-2015 the Urho3D project.
  2. //
  3. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  4. // LICENSE: Atomic Game Engine Editor and Tools EULA
  5. // Please see LICENSE_ATOMIC_EDITOR_AND_TOOLS.md in repository root for
  6. // license information: https://github.com/AtomicGameEngine/AtomicGameEngine
  7. //
  8. #include <Atomic/IO/Log.h>
  9. #include <Atomic/Core/CoreEvents.h>
  10. #include <Atomic/Scene/SceneEvents.h>
  11. #include <Atomic/Scene/Scene.h>
  12. #include <Atomic/Scene/PrefabComponent.h>
  13. #include <Atomic/Graphics/Camera.h>
  14. #include <Atomic/Graphics/Graphics.h>
  15. #include <Atomic/Graphics/DebugRenderer.h>
  16. #include <Atomic/Graphics/Viewport.h>
  17. #include <Atomic/Graphics/Octree.h>
  18. #include <Atomic/Graphics/Material.h>
  19. #include <Atomic/Atomic3D/Terrain.h>
  20. #include <Atomic/Atomic3D/Model.h>
  21. #include <Atomic/Atomic3D/StaticModel.h>
  22. #include <Atomic/Atomic3D/AnimatedModel.h>
  23. #include <Atomic/Atomic3D/AnimationController.h>
  24. #include <Atomic/Input/Input.h>
  25. #include <Atomic/IO/FileSystem.h>
  26. #include <Atomic/Resource/ResourceCache.h>
  27. #include <Atomic/Resource/XMLFile.h>
  28. #include <Atomic/Physics/PhysicsWorld.h>
  29. #include <Atomic/UI/UI.h>
  30. #include <Atomic/UI/UIEvents.h>
  31. #include <Atomic/Resource/ResourceEvents.h>
  32. #include <ToolCore/Assets/Asset.h>
  33. #include <ToolCore/Assets/AssetDatabase.h>
  34. #include "../../EditorMode/AEEditorEvents.h"
  35. #include "SceneView3D.h"
  36. #include "SceneEditor3D.h"
  37. using namespace ToolCore;
  38. namespace AtomicEditor
  39. {
  40. SceneView3D ::SceneView3D(Context* context, SceneEditor3D *sceneEditor) :
  41. UISceneView(context),
  42. yaw_(0.0f),
  43. pitch_(0.0f),
  44. mouseLeftDown_(false),
  45. mouseMoved_(false),
  46. enabled_(true)
  47. {
  48. sceneEditor_ = sceneEditor;
  49. ResourceCache* cache = GetSubsystem<ResourceCache>();
  50. scene_ = sceneEditor->GetScene();
  51. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  52. if (debugRenderer_.Null())
  53. {
  54. debugRenderer_ = scene_->CreateComponent<DebugRenderer>();
  55. }
  56. octree_ = scene_->GetComponent<Octree>();
  57. if (octree_.Null())
  58. {
  59. LOGWARNING("Scene without an octree loaded");
  60. octree_ = scene_->CreateComponent<Octree>();
  61. }
  62. cameraNode_ = scene_->CreateChild("__atomic_sceneview3d_camera");
  63. cameraNode_->SetTemporary(true);
  64. camera_ = cameraNode_->CreateComponent<Camera>();
  65. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  66. assert(debugRenderer_.NotNull());
  67. octree_ = scene_->GetComponent<Octree>();
  68. assert(octree_.NotNull());
  69. cameraNode_->SetPosition(Vector3(0, 0, -10));
  70. SetView(scene_, camera_);
  71. SetAutoUpdate(false);
  72. SubscribeToEvent(E_UPDATE, HANDLER(SceneView3D, HandleUpdate));
  73. SubscribeToEvent(E_EDITORACTIVENODECHANGE, HANDLER(SceneView3D, HandleEditorActiveNodeChange));
  74. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SceneView3D, HandlePostRenderUpdate));
  75. SubscribeToEvent(scene_, E_NODEREMOVED, HANDLER(SceneView3D, HandleNodeRemoved));
  76. SubscribeToEvent(E_MOUSEMOVE, HANDLER(SceneView3D,HandleMouseMove));
  77. SubscribeToEvent(this, E_DRAGENTERWIDGET, HANDLER(SceneView3D, HandleDragEnterWidget));
  78. SubscribeToEvent(this, E_DRAGEXITWIDGET, HANDLER(SceneView3D, HandleDragExitWidget));
  79. SubscribeToEvent(this, E_DRAGENDED, HANDLER(SceneView3D, HandleDragEnded));
  80. SetIsFocusable(true);
  81. }
  82. SceneView3D::~SceneView3D()
  83. {
  84. }
  85. void SceneView3D::Enable()
  86. {
  87. if (enabled_)
  88. return;
  89. enabled_ = true;
  90. SetVisibility(UI_WIDGET_VISIBILITY_VISIBLE);
  91. }
  92. void SceneView3D::Disable()
  93. {
  94. if (!enabled_)
  95. return;
  96. enabled_ = false;
  97. SetVisibility(UI_WIDGET_VISIBILITY_INVISIBLE);
  98. }
  99. void SceneView3D::MoveCamera(float timeStep)
  100. {
  101. if (!enabled_ && !GetFocus())
  102. return;
  103. Input* input = GetSubsystem<Input>();
  104. // Movement speed as world units per second
  105. float MOVE_SPEED = 20.0f;
  106. // Mouse sensitivity as degrees per pixel
  107. const float MOUSE_SENSITIVITY = 0.2f;
  108. if (input->GetKeyDown(KEY_LSHIFT) || input->GetKeyDown(KEY_RSHIFT))
  109. MOVE_SPEED *= 3.0f;
  110. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  111. if (input->GetMouseButtonDown(MOUSEB_RIGHT))
  112. {
  113. SetFocus();
  114. IntVector2 mouseMove = input->GetMouseMove();
  115. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  116. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  117. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  118. }
  119. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  120. cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
  121. #ifdef ATOMIC_PLATFORM_WINDOWS
  122. bool superdown = input->GetKeyDown(KEY_LCTRL) || input->GetKeyDown(KEY_RCTRL);
  123. #else
  124. bool superdown = input->GetKeyDown(KEY_LGUI) || input->GetKeyDown(KEY_RGUI);
  125. #endif
  126. if (!superdown && input->GetMouseButtonDown(MOUSEB_RIGHT)) {
  127. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  128. // Use the Translate() function (default local space) to move relative to the node's orientation.
  129. if (input->GetKeyDown('W'))
  130. {
  131. SetFocus();
  132. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  133. }
  134. if (input->GetKeyDown('S'))
  135. {
  136. SetFocus();
  137. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  138. }
  139. if (input->GetKeyDown('A'))
  140. { SetFocus();
  141. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  142. }
  143. if (input->GetKeyDown('D'))
  144. {
  145. SetFocus();
  146. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  147. }
  148. }
  149. }
  150. Ray SceneView3D::GetCameraRay()
  151. {
  152. Ray camRay;
  153. Input* input = GetSubsystem<Input>();
  154. IntVector2 cpos = input->GetMousePosition();
  155. IntRect rect = GetRect();
  156. if (!rect.Width() || !rect.Height())
  157. return camRay;
  158. int x = rect.left_;
  159. int y = rect.top_;
  160. GetInternalWidget()->ConvertToRoot(x, y);
  161. return camera_->GetScreenRay(float(cpos.x_ - x) / rect.Width(),
  162. float(cpos.y_ - y) / rect.Height());
  163. }
  164. void SceneView3D::DrawNodeDebug(Node* node, DebugRenderer* debug, bool drawNode)
  165. {
  166. if (drawNode)
  167. debug->AddNode(node, 1.0, false);
  168. // Exception for the scene to avoid bringing the editor to its knees: drawing either the whole hierarchy or the subsystem-
  169. // components can have a large performance hit. Also do not draw terrain child nodes due to their large amount
  170. // (TerrainPatch component itself draws nothing as debug geometry)
  171. if (node != scene_ && !node->GetComponent<Terrain>())
  172. {
  173. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  174. for (unsigned j = 0; j < components.Size(); ++j)
  175. components[j]->DrawDebugGeometry(debug, false);
  176. // To avoid cluttering the view, do not draw the node axes for child nodes
  177. for (unsigned k = 0; k < node->GetNumChildren(); ++k)
  178. DrawNodeDebug(node->GetChild(k), debug, false);
  179. }
  180. }
  181. bool SceneView3D::MouseInView()
  182. {
  183. if (!GetInternalWidget())
  184. return false;
  185. if (!TBWidget::hovered_widget || TBWidget::hovered_widget->GetDelegate() != this)
  186. return false;
  187. Input* input = GetSubsystem<Input>();
  188. IntVector2 pos = input->GetMousePosition();
  189. IntRect rect = GetRect();
  190. GetInternalWidget()->ConvertToRoot(rect.left_, rect.top_);
  191. GetInternalWidget()->ConvertToRoot(rect.right_, rect.bottom_);
  192. return rect.IsInside(pos);
  193. }
  194. void SceneView3D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  195. {
  196. // Visualize the currently selected nodes
  197. if (selectedNode_.NotNull())
  198. {
  199. DrawNodeDebug(selectedNode_, debugRenderer_);
  200. }
  201. if (!MouseInView())
  202. return;
  203. Input* input = GetSubsystem<Input>();
  204. mouseLeftDown_ = false;
  205. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  206. {
  207. SetFocus();
  208. if (!mouseMoved_ && !sceneEditor_->GetGizmo()->Selected())
  209. {
  210. Ray camRay = GetCameraRay();
  211. PODVector<RayQueryResult> result;
  212. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  213. octree_->RaycastSingle(query);
  214. if (query.result_.Size())
  215. {
  216. const RayQueryResult& r = result[0];
  217. if (r.drawable_)
  218. {
  219. VariantMap neventData;
  220. Node* node = r.drawable_->GetNode();
  221. // if temporary, this is a prefab
  222. // TODO: if we use temporary for other stuff
  223. // fix this to look for prefab
  224. if (node->IsTemporary())
  225. node = node->GetParent();
  226. neventData[EditorActiveNodeChange::P_NODE] = node;
  227. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  228. }
  229. }
  230. }
  231. mouseMoved_ = false;
  232. }
  233. else if (!input->GetMouseButtonDown(MOUSEB_LEFT))
  234. {
  235. Ray camRay = GetCameraRay();
  236. PODVector<RayQueryResult> result;
  237. mouseMoved_ = false;
  238. /*
  239. Array<int> pickModeDrawableFlags = {
  240. DRAWABLE_GEOMETRY,
  241. DRAWABLE_LIGHT,
  242. DRAWABLE_ZONE
  243. };
  244. */
  245. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  246. octree_->RaycastSingle(query);
  247. if (query.result_.Size())
  248. {
  249. const RayQueryResult& r = result[0];
  250. if (r.drawable_)
  251. {
  252. debugRenderer_->AddNode(r.drawable_->GetNode(), 1.0, false);
  253. r.drawable_->DrawDebugGeometry(debugRenderer_, false);
  254. }
  255. }
  256. }
  257. else
  258. {
  259. mouseLeftDown_ = true;
  260. if (Abs(input->GetMouseMoveX() > 3 || input->GetMouseMoveY() > 3))
  261. {
  262. mouseMoved_ = true;
  263. }
  264. }
  265. }
  266. void SceneView3D::SelectNode(Node* node)
  267. {
  268. selectedNode_ = node;
  269. }
  270. bool SceneView3D::OnEvent(const TBWidgetEvent &ev)
  271. {
  272. return sceneEditor_->OnEvent(ev);
  273. }
  274. void SceneView3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  275. {
  276. // Timestep parameter is same no matter what event is being listened to
  277. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  278. if (MouseInView())
  279. MoveCamera(timeStep);
  280. QueueUpdate();
  281. if (preloadResourceScene_.NotNull())
  282. {
  283. if (preloadResourceScene_->GetAsyncProgress() == 1.0f)
  284. {
  285. ResourceCache* cache = GetSubsystem<ResourceCache>();
  286. XMLFile* xml = cache->GetResource<XMLFile>(dragAssetGUID_);
  287. if (dragNode_.NotNull())
  288. {
  289. dragNode_->LoadXML(xml->GetRoot());
  290. UpdateDragNode(0, 0);
  291. AnimationController* controller = dragNode_->GetComponent<AnimationController>();
  292. if (controller)
  293. {
  294. controller->PlayExclusive("Idle", 0, true);
  295. dragNode_->GetScene()->SetUpdateEnabled(true);
  296. }
  297. }
  298. preloadResourceScene_ = 0;
  299. dragAssetGUID_ = "";
  300. }
  301. }
  302. }
  303. void SceneView3D::HandleEditorActiveNodeChange(StringHash eventType, VariantMap& eventData)
  304. {
  305. Node* node = (Node*) (eventData[EditorActiveNodeChange::P_NODE].GetPtr());
  306. SelectNode(node);
  307. }
  308. void SceneView3D::HandleNodeRemoved(StringHash eventType, VariantMap& eventData)
  309. {
  310. Node* node = (Node*) (eventData[NodeRemoved::P_NODE].GetPtr());
  311. if (node == selectedNode_)
  312. SelectNode(0);
  313. }
  314. void SceneView3D::UpdateDragNode(int mouseX, int mouseY)
  315. {
  316. if (dragNode_.Null())
  317. return;
  318. Ray ray = GetCameraRay();
  319. Vector3 pos = ray.origin_;
  320. pos += ray.direction_ * 10;
  321. dragNode_->SetWorldPosition(pos);
  322. }
  323. void SceneView3D::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  324. {
  325. if (dragNode_.Null())
  326. return;
  327. Input* input = GetSubsystem<Input>();
  328. if (!input->IsMouseVisible())
  329. return;
  330. using namespace MouseMove;
  331. int x = eventData[P_X].GetInt();
  332. int y = eventData[P_Y].GetInt();
  333. UpdateDragNode(x, y);
  334. }
  335. void SceneView3D::HandleDragEnterWidget(StringHash eventType, VariantMap& eventData)
  336. {
  337. using namespace DragEnterWidget;
  338. UIWidget* widget = static_cast<UIWidget*>(eventData[P_WIDGET].GetPtr());
  339. if (widget != this)
  340. return;
  341. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  342. Object* object = dragObject->GetObject();
  343. if (!object)
  344. return;
  345. if (object->GetType() == Asset::GetTypeStatic())
  346. {
  347. Asset* asset = (Asset*) object;
  348. dragNode_ = asset->InstantiateNode(scene_, asset->GetName());
  349. if (dragNode_.NotNull())
  350. {
  351. Input* input = GetSubsystem<Input>();
  352. IntVector2 pos = input->GetMousePosition();
  353. UpdateDragNode(pos.x_, pos.y_);
  354. }
  355. //LOGINFOF("Dropped %s : %s on SceneView3D", asset->GetPath().CString(), asset->GetGUID().CString());
  356. }
  357. }
  358. void SceneView3D::HandleDragExitWidget(StringHash eventType, VariantMap& eventData)
  359. {
  360. if (preloadResourceScene_.NotNull())
  361. {
  362. preloadResourceScene_->StopAsyncLoading();
  363. preloadResourceScene_ = 0;
  364. }
  365. if (dragNode_.NotNull())
  366. {
  367. scene_->RemoveChild(dragNode_);
  368. }
  369. dragAssetGUID_ = "";
  370. dragNode_ = 0;
  371. }
  372. void SceneView3D::HandleDragEnded(StringHash eventType, VariantMap& eventData)
  373. {
  374. using namespace DragEnded;
  375. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  376. if (dragNode_.NotNull())
  377. {
  378. VariantMap neventData;
  379. neventData[EditorActiveNodeChange::P_NODE] = dragNode_;
  380. SendEvent(E_EDITORACTIVENODECHANGE, neventData);
  381. }
  382. if (dragObject && dragObject->GetObject()->GetType() == ToolCore::Asset::GetTypeStatic())
  383. {
  384. Asset* asset = (ToolCore::Asset*) dragObject->GetObject();
  385. if (asset->GetImporterTypeName() == "MaterialImporter") {
  386. Material* material = GetSubsystem<ResourceCache>()->GetResource<Material>(asset->GetPath());
  387. if (material) {
  388. material = material;
  389. Ray camRay = GetCameraRay();
  390. PODVector<RayQueryResult> result;
  391. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  392. octree_->RaycastSingle(query);
  393. if (query.result_.Size())
  394. {
  395. const RayQueryResult& r = result[0];
  396. if (r.drawable_ && (r.drawable_->GetType() == StaticModel::GetTypeStatic() || r.drawable_->GetType() == AnimatedModel::GetTypeStatic()))
  397. {
  398. ((StaticModel*)r.drawable_)->SetMaterial(material);
  399. }
  400. }
  401. }
  402. }
  403. }
  404. dragAssetGUID_ = "";
  405. dragNode_ = 0;
  406. }
  407. }