SceneView3D.cpp 17 KB

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