SceneView3D.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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/Model.h>
  20. #include <Atomic/Atomic3D/StaticModel.h>
  21. #include <Atomic/Atomic3D/AnimatedModel.h>
  22. #include <Atomic/Atomic3D/AnimationController.h>
  23. #include <Atomic/Input/Input.h>
  24. #include <Atomic/IO/FileSystem.h>
  25. #include <Atomic/Resource/ResourceCache.h>
  26. #include <Atomic/Resource/XMLFile.h>
  27. #include <Atomic/Physics/PhysicsWorld.h>
  28. #include <Atomic/UI/UI.h>
  29. #include <Atomic/UI/UIEvents.h>
  30. #include <Atomic/Resource/ResourceEvents.h>
  31. #include <ToolCore/Assets/Asset.h>
  32. #include <ToolCore/Assets/AssetDatabase.h>
  33. #include "../../EditorMode/AEEditorEvents.h"
  34. #include "SceneView3D.h"
  35. #include "SceneEditor3D.h"
  36. #include "SceneEditor3DEvents.h"
  37. #include "SceneSelection.h"
  38. using namespace ToolCore;
  39. namespace AtomicEditor
  40. {
  41. SceneView3D ::SceneView3D(Context* context, SceneEditor3D *sceneEditor) :
  42. UISceneView(context),
  43. yaw_(0.0f),
  44. pitch_(0.0f),
  45. mouseLeftDown_(false),
  46. mouseMoved_(false),
  47. enabled_(true),
  48. cameraMove_(false)
  49. {
  50. sceneEditor_ = sceneEditor;
  51. ResourceCache* cache = GetSubsystem<ResourceCache>();
  52. scene_ = sceneEditor->GetScene();
  53. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  54. if (debugRenderer_.Null())
  55. {
  56. debugRenderer_ = scene_->CreateComponent<DebugRenderer>();
  57. debugRenderer_->SetTemporary(true);
  58. }
  59. octree_ = scene_->GetComponent<Octree>();
  60. if (octree_.Null())
  61. {
  62. LOGWARNING("Scene without an octree loaded");
  63. octree_ = scene_->CreateComponent<Octree>();
  64. }
  65. cameraNode_ = scene_->CreateChild("__atomic_sceneview3d_camera");
  66. cameraNode_->SetTemporary(true);
  67. camera_ = cameraNode_->CreateComponent<Camera>();
  68. debugRenderer_ = scene_->GetComponent<DebugRenderer>();
  69. assert(debugRenderer_.NotNull());
  70. octree_ = scene_->GetComponent<Octree>();
  71. assert(octree_.NotNull());
  72. cameraNode_->SetPosition(Vector3(0, 0, -10));
  73. SetView(scene_, camera_);
  74. SetAutoUpdate(false);
  75. SubscribeToEvent(E_UPDATE, HANDLER(SceneView3D, HandleUpdate));
  76. SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(SceneView3D, HandlePostRenderUpdate));
  77. SubscribeToEvent(E_MOUSEMOVE, HANDLER(SceneView3D,HandleMouseMove));
  78. SubscribeToEvent(this, E_DRAGENTERWIDGET, HANDLER(SceneView3D, HandleDragEnterWidget));
  79. SubscribeToEvent(this, E_DRAGEXITWIDGET, HANDLER(SceneView3D, HandleDragExitWidget));
  80. SubscribeToEvent(this, E_DRAGENDED, HANDLER(SceneView3D, HandleDragEnded));
  81. SubscribeToEvent(E_UIUNHANDLEDSHORTCUT, HANDLER(SceneView3D, HandleUIUnhandledShortcut));
  82. SubscribeToEvent(E_UIWIDGETFOCUSESCAPED, HANDLER(SceneView3D, HandleUIWidgetFocusEscaped));
  83. SetIsFocusable(true);
  84. }
  85. SceneView3D::~SceneView3D()
  86. {
  87. }
  88. void SceneView3D::Enable()
  89. {
  90. if (enabled_)
  91. return;
  92. enabled_ = true;
  93. }
  94. void SceneView3D::Disable()
  95. {
  96. if (!enabled_)
  97. return;
  98. enabled_ = false;
  99. }
  100. bool SceneView3D::GetOrbitting()
  101. {
  102. Input* input = GetSubsystem<Input>();
  103. return framedBBox_.defined_ && MouseInView() && input->GetKeyDown(KEY_ALT) && input->GetMouseButtonDown(MOUSEB_LEFT);
  104. }
  105. bool SceneView3D::GetZooming()
  106. {
  107. Input* input = GetSubsystem<Input>();
  108. return MouseInView() && input->GetKeyDown(KEY_ALT) && input->GetMouseMoveWheel();
  109. }
  110. void SceneView3D::MoveCamera(float timeStep)
  111. {
  112. if (!enabled_ && !GetFocus())
  113. return;
  114. Input* input = GetSubsystem<Input>();
  115. bool shiftDown = false;
  116. if (input->GetKeyDown(KEY_LSHIFT) || input->GetKeyDown(KEY_RSHIFT))
  117. shiftDown = true;
  118. bool mouseInView = MouseInView();
  119. bool orbitting = GetOrbitting();
  120. bool zooming = GetZooming();
  121. // Movement speed as world units per second
  122. float MOVE_SPEED = 20.0f;
  123. // Mouse sensitivity as degrees per pixel
  124. const float MOUSE_SENSITIVITY = 0.2f;
  125. if (shiftDown)
  126. MOVE_SPEED *= 3.0f;
  127. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  128. if ((mouseInView && input->GetMouseButtonDown(MOUSEB_RIGHT)) || orbitting)
  129. {
  130. SetFocus();
  131. IntVector2 mouseMove = input->GetMouseMove();
  132. yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
  133. pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
  134. pitch_ = Clamp(pitch_, -90.0f, 90.0f);
  135. }
  136. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  137. Quaternion q(pitch_, yaw_, 0.0f);
  138. if (!zooming)
  139. cameraNode_->SetRotation(q);
  140. if (orbitting)
  141. {
  142. BoundingBox bbox;
  143. sceneEditor_->GetSelection()->GetBounds(bbox);
  144. if (bbox.defined_)
  145. {
  146. Vector3 centerPoint = bbox.Center();
  147. Vector3 d = cameraNode_->GetWorldPosition() - centerPoint;
  148. cameraNode_->SetWorldPosition(centerPoint - q * Vector3(0.0, 0.0, d.Length()));
  149. }
  150. }
  151. if (zooming)
  152. {
  153. Ray ray = GetCameraRay();
  154. Vector3 wpos = cameraNode_->GetWorldPosition();
  155. wpos += ray.direction_ * (float (input->GetMouseMoveWheel()) * (shiftDown ? 0.6f : 0.2f));
  156. cameraNode_->SetWorldPosition(wpos);
  157. }
  158. #ifdef ATOMIC_PLATFORM_WINDOWS
  159. bool superdown = input->GetKeyDown(KEY_LCTRL) || input->GetKeyDown(KEY_RCTRL);
  160. #else
  161. bool superdown = input->GetKeyDown(KEY_LGUI) || input->GetKeyDown(KEY_RGUI);
  162. #endif
  163. if (!orbitting && mouseInView && !superdown && input->GetMouseButtonDown(MOUSEB_RIGHT)) {
  164. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  165. // Use the Translate() function (default local space) to move relative to the node's orientation.
  166. if (input->GetKeyDown(KEY_W))
  167. {
  168. SetFocus();
  169. cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
  170. }
  171. if (input->GetKeyDown(KEY_S))
  172. {
  173. SetFocus();
  174. cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
  175. }
  176. if (input->GetKeyDown(KEY_A))
  177. { SetFocus();
  178. cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
  179. }
  180. if (input->GetKeyDown(KEY_D))
  181. {
  182. SetFocus();
  183. cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
  184. }
  185. if (input->GetKeyDown(KEY_E))
  186. {
  187. SetFocus();
  188. cameraNode_->Translate(Vector3::UP * MOVE_SPEED * timeStep);
  189. }
  190. if (input->GetKeyDown(KEY_Q))
  191. {
  192. SetFocus();
  193. cameraNode_->Translate(Vector3::DOWN * MOVE_SPEED * timeStep);
  194. }
  195. }
  196. if (cameraMove_)
  197. {
  198. cameraMoveTime_ += timeStep * 3.0f;
  199. if (cameraMoveTime_ > 1.0f)
  200. {
  201. cameraMove_ = false;
  202. cameraMoveTime_ = 1.0f;
  203. }
  204. Vector3 pos = cameraMoveStart_.Lerp(cameraMoveTarget_, cameraMoveTime_);
  205. cameraNode_->SetWorldPosition(pos);
  206. }
  207. }
  208. Ray SceneView3D::GetCameraRay()
  209. {
  210. Ray camRay;
  211. Input* input = GetSubsystem<Input>();
  212. IntVector2 cpos = input->GetMousePosition();
  213. IntRect rect = GetRect();
  214. if (!rect.Width() || !rect.Height())
  215. return camRay;
  216. int x = rect.left_;
  217. int y = rect.top_;
  218. GetInternalWidget()->ConvertToRoot(x, y);
  219. return camera_->GetScreenRay(float(cpos.x_ - x) / rect.Width(),
  220. float(cpos.y_ - y) / rect.Height());
  221. }
  222. bool SceneView3D::MouseInView()
  223. {
  224. if (!GetInternalWidget())
  225. return false;
  226. if (!TBWidget::hovered_widget || TBWidget::hovered_widget->GetDelegate() != this)
  227. return false;
  228. Input* input = GetSubsystem<Input>();
  229. IntVector2 pos = input->GetMousePosition();
  230. IntRect rect = GetRect();
  231. GetInternalWidget()->ConvertToRoot(rect.left_, rect.top_);
  232. GetInternalWidget()->ConvertToRoot(rect.right_, rect.bottom_);
  233. return rect.IsInside(pos);
  234. }
  235. void SceneView3D::HandleUIUnhandledShortcut(StringHash eventType, VariantMap& eventData)
  236. {
  237. if (!enabled_)
  238. return;
  239. unsigned id = eventData[UIUnhandledShortcut::P_REFID].GetUInt();
  240. if (id == TBIDC("undo"))
  241. sceneEditor_->Undo();
  242. else if (id == TBIDC("redo"))
  243. sceneEditor_->Redo();
  244. else if (id == TBIDC("copy"))
  245. sceneEditor_->Copy();
  246. else if (id == TBIDC("cut"))
  247. sceneEditor_->Cut();
  248. else if (id == TBIDC("paste"))
  249. sceneEditor_->Paste();
  250. return;
  251. }
  252. void SceneView3D::HandleUIWidgetFocusEscaped(StringHash eventType, VariantMap& eventData)
  253. {
  254. if (!enabled_)
  255. return;
  256. SetFocus();
  257. }
  258. void SceneView3D::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
  259. {
  260. if (!MouseInView() || GetOrbitting())
  261. return;
  262. Input* input = GetSubsystem<Input>();
  263. mouseLeftDown_ = false;
  264. bool shiftDown = input->GetKeyDown(KEY_LSHIFT) || input->GetKeyDown(KEY_RSHIFT);
  265. if (input->GetMouseButtonPress(MOUSEB_LEFT))
  266. {
  267. SetFocus();
  268. if (!mouseMoved_ && !sceneEditor_->GetGizmo()->Selected())
  269. {
  270. Ray camRay = GetCameraRay();
  271. PODVector<RayQueryResult> result;
  272. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  273. octree_->RaycastSingle(query);
  274. if (query.result_.Size())
  275. {
  276. const RayQueryResult& r = result[0];
  277. if (r.drawable_)
  278. {
  279. VariantMap neventData;
  280. Node* node = r.drawable_->GetNode();
  281. // if temporary, this is a prefab
  282. // TODO: if we use temporary for other stuff
  283. // fix this to look for prefab
  284. if (node->IsTemporary())
  285. node = node->GetParent();
  286. if (sceneEditor_->GetSelection()->Contains(node) && shiftDown)
  287. {
  288. sceneEditor_->GetSelection()->RemoveNode(node);
  289. }
  290. else
  291. {
  292. sceneEditor_->GetSelection()->AddNode(node, !shiftDown);
  293. }
  294. }
  295. }
  296. else
  297. {
  298. sceneEditor_->GetSelection()->Clear();
  299. }
  300. }
  301. mouseMoved_ = false;
  302. }
  303. else if (!input->GetMouseButtonDown(MOUSEB_LEFT))
  304. {
  305. Ray camRay = GetCameraRay();
  306. PODVector<RayQueryResult> result;
  307. mouseMoved_ = false;
  308. /*
  309. Array<int> pickModeDrawableFlags = {
  310. DRAWABLE_GEOMETRY,
  311. DRAWABLE_LIGHT,
  312. DRAWABLE_ZONE
  313. };
  314. */
  315. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  316. octree_->RaycastSingle(query);
  317. if (query.result_.Size())
  318. {
  319. const RayQueryResult& r = result[0];
  320. if (r.drawable_)
  321. {
  322. debugRenderer_->AddNode(r.drawable_->GetNode(), 1.0, false);
  323. r.drawable_->DrawDebugGeometry(debugRenderer_, false);
  324. }
  325. }
  326. }
  327. else
  328. {
  329. mouseLeftDown_ = true;
  330. if (Abs(input->GetMouseMoveX() > 3 || input->GetMouseMoveY() > 3))
  331. {
  332. mouseMoved_ = true;
  333. }
  334. }
  335. }
  336. bool SceneView3D::OnEvent(const TBWidgetEvent &ev)
  337. {
  338. if (ev.type == EVENT_TYPE_SHORTCUT)
  339. {
  340. if (ev.ref_id == TBIDC("close"))
  341. return false;
  342. }
  343. if (ev.type == EVENT_TYPE_KEY_UP)
  344. {
  345. if (ev.special_key == TB_KEY_ESC)
  346. {
  347. sceneEditor_->GetSelection()->Clear();
  348. }
  349. }
  350. return sceneEditor_->OnEvent(ev);
  351. }
  352. void SceneView3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
  353. {
  354. // parent is the contentRoot for our tab, when tab isn't active it will not be visible
  355. if (!GetParent() || GetParent()->GetVisibility() != UI_WIDGET_VISIBILITY_VISIBLE)
  356. {
  357. Disable();
  358. return;
  359. }
  360. Enable();
  361. // Timestep parameter is same no matter what event is being listened to
  362. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  363. MoveCamera(timeStep);
  364. QueueUpdate();
  365. if (preloadResourceScene_.NotNull())
  366. {
  367. if (preloadResourceScene_->GetAsyncProgress() == 1.0f)
  368. {
  369. ResourceCache* cache = GetSubsystem<ResourceCache>();
  370. XMLFile* xml = cache->GetResource<XMLFile>(dragAssetGUID_);
  371. if (dragNode_.NotNull())
  372. {
  373. dragNode_->LoadXML(xml->GetRoot());
  374. UpdateDragNode(0, 0);
  375. AnimationController* controller = dragNode_->GetComponent<AnimationController>();
  376. if (controller)
  377. {
  378. controller->PlayExclusive("Idle", 0, true);
  379. dragNode_->GetScene()->SetUpdateEnabled(true);
  380. }
  381. }
  382. preloadResourceScene_ = 0;
  383. dragAssetGUID_ = "";
  384. }
  385. }
  386. }
  387. void SceneView3D::UpdateDragNode(int mouseX, int mouseY)
  388. {
  389. if (dragNode_.Null())
  390. return;
  391. Ray ray = GetCameraRay();
  392. Vector3 pos = ray.origin_;
  393. pos += ray.direction_ * 10;
  394. dragNode_->SetWorldPosition(pos);
  395. }
  396. void SceneView3D::HandleMouseMove(StringHash eventType, VariantMap& eventData)
  397. {
  398. if (dragNode_.Null())
  399. return;
  400. Input* input = GetSubsystem<Input>();
  401. if (!input->IsMouseVisible())
  402. return;
  403. using namespace MouseMove;
  404. int x = eventData[P_X].GetInt();
  405. int y = eventData[P_Y].GetInt();
  406. UpdateDragNode(x, y);
  407. }
  408. void SceneView3D::HandleDragEnterWidget(StringHash eventType, VariantMap& eventData)
  409. {
  410. using namespace DragEnterWidget;
  411. UIWidget* widget = static_cast<UIWidget*>(eventData[P_WIDGET].GetPtr());
  412. if (widget != this)
  413. return;
  414. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  415. Object* object = dragObject->GetObject();
  416. if (!object)
  417. return;
  418. if (object->GetType() == Asset::GetTypeStatic())
  419. {
  420. Asset* asset = (Asset*) object;
  421. dragNode_ = asset->InstantiateNode(scene_, asset->GetName());
  422. if (dragNode_.NotNull())
  423. {
  424. Input* input = GetSubsystem<Input>();
  425. IntVector2 pos = input->GetMousePosition();
  426. UpdateDragNode(pos.x_, pos.y_);
  427. }
  428. //LOGINFOF("Dropped %s : %s on SceneView3D", asset->GetPath().CString(), asset->GetGUID().CString());
  429. }
  430. }
  431. void SceneView3D::HandleDragExitWidget(StringHash eventType, VariantMap& eventData)
  432. {
  433. if (preloadResourceScene_.NotNull())
  434. {
  435. preloadResourceScene_->StopAsyncLoading();
  436. preloadResourceScene_ = 0;
  437. }
  438. if (dragNode_.NotNull())
  439. {
  440. scene_->RemoveChild(dragNode_);
  441. }
  442. dragAssetGUID_ = "";
  443. dragNode_ = 0;
  444. }
  445. void SceneView3D::HandleDragEnded(StringHash eventType, VariantMap& eventData)
  446. {
  447. using namespace DragEnded;
  448. UIDragObject* dragObject = static_cast<UIDragObject*>(eventData[P_DRAGOBJECT].GetPtr());
  449. if (dragNode_.NotNull())
  450. {
  451. VariantMap nodeCreatedEvent;
  452. nodeCreatedEvent[SceneEditNodeCreated::P_NODE] = dragNode_;
  453. scene_->SendEvent(E_SCENEEDITNODECREATED, nodeCreatedEvent);
  454. }
  455. if (dragObject && dragObject->GetObject()->GetType() == ToolCore::Asset::GetTypeStatic())
  456. {
  457. Asset* asset = (ToolCore::Asset*) dragObject->GetObject();
  458. if (asset->GetImporterTypeName() == "MaterialImporter") {
  459. Material* material = GetSubsystem<ResourceCache>()->GetResource<Material>(asset->GetPath());
  460. if (material) {
  461. material = material;
  462. Ray camRay = GetCameraRay();
  463. PODVector<RayQueryResult> result;
  464. RayOctreeQuery query(result, camRay, RAY_TRIANGLE, camera_->GetFarClip(), DRAWABLE_GEOMETRY, 0x7fffffff);
  465. octree_->RaycastSingle(query);
  466. if (query.result_.Size())
  467. {
  468. const RayQueryResult& r = result[0];
  469. if (r.drawable_ && (r.drawable_->GetType() == StaticModel::GetTypeStatic() || r.drawable_->GetType() == AnimatedModel::GetTypeStatic()))
  470. {
  471. ((StaticModel*)r.drawable_)->SetMaterial(material);
  472. }
  473. }
  474. }
  475. }
  476. }
  477. dragAssetGUID_ = "";
  478. dragNode_ = 0;
  479. }
  480. void SceneView3D::FrameSelection()
  481. {
  482. BoundingBox bbox;
  483. sceneEditor_->GetSelection()->GetBounds(bbox);
  484. if (!bbox.defined_)
  485. return;
  486. Sphere sphere(bbox);
  487. if (sphere.radius_ < .01f || sphere.radius_ > 512)
  488. return;
  489. framedBBox_ = bbox;
  490. cameraMoveStart_ = cameraNode_->GetWorldPosition();
  491. cameraMoveTarget_ = bbox.Center() - (cameraNode_->GetWorldDirection() * sphere.radius_ * 3);
  492. cameraMoveTime_ = 0.0f;
  493. cameraMove_ = true;
  494. }
  495. }