SceneView3D.cpp 15 KB

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