level_editor.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. /*
  2. * Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. #if CROWN_TOOLS
  6. #include "core/containers/vector.h"
  7. #include "core/filesystem/file.h"
  8. #include "core/filesystem/filesystem_disk.h"
  9. #include "core/filesystem/path.h"
  10. #include "core/json/json.h"
  11. #include "core/json/json_object.h"
  12. #include "core/json/sjson.h"
  13. #include "core/math/vector2.h"
  14. #include "core/network/socket.h"
  15. #include "core/strings/dynamic_string.h"
  16. #include "device/device.h"
  17. #include "device/device_event_queue.h"
  18. #include "device/device_options.h"
  19. #include "device/input_device.h"
  20. #include "device/input_manager.h"
  21. #include "device/input_types.h"
  22. #include "device/log.h"
  23. #include "device/pipeline.h"
  24. #include "imgui_context.h"
  25. #include "resource/resource_manager.h"
  26. #include "resource/texture_resource.h"
  27. #include "tool_api.h"
  28. #include <iconfontheaders/icons_material_design.h>
  29. #include <imgui.h>
  30. #include <nfd.h>
  31. #include <time.h>
  32. #if CROWN_PLATFORM_POSIX
  33. #include <sys/time.h>
  34. #endif
  35. namespace { const crown::log_internal::System LEVEL_EDITOR = { "LevelEditor" }; }
  36. namespace crown
  37. {
  38. static u16 _width = 1280;
  39. static u16 _height = 720;
  40. struct Pivot
  41. {
  42. enum Enum
  43. {
  44. TOP_LEFT,
  45. TOP_CENTER,
  46. TOP_RIGHT,
  47. LEFT,
  48. CENTER,
  49. RIGHT,
  50. BOTTOM_LEFT,
  51. BOTTOM_CENTER,
  52. BOTTOM_RIGHT,
  53. COUNT
  54. };
  55. };
  56. static const char* pivot_names[] =
  57. {
  58. "Top Left", // Pivot::TOP_LEFT
  59. "Top Right", // Pivot::TOP_CENTER
  60. "Top Center", // Pivot::TOP_RIGHT
  61. "Left", // Pivot::LEFT
  62. "Center", // Pivot::CENTER
  63. "Right", // Pivot::RIGHT
  64. "Bottom Left", // Pivot::BOTTOM_LEFT
  65. "Bottom Center", // Pivot::BOTTOM_CENTER
  66. "Bottom Right" // Pivot::BOTTOM_RIGHT
  67. };
  68. CE_STATIC_ASSERT(countof(pivot_names) == Pivot::COUNT);
  69. Vector2 sprite_cell_xy(int r, int c, int offset_x, int offset_y, int cell_w, int cell_h, int spacing_x, int spacing_y)
  70. {
  71. int x0 = offset_x + c*cell_w + c*spacing_x;
  72. int y0 = offset_y + r*cell_h + r*spacing_y;
  73. return vector2(x0, y0);
  74. }
  75. Vector2 sprite_cell_pivot_xy(int cell_w, int cell_h, int pivot)
  76. {
  77. int pivot_x = 0;
  78. int pivot_y = 0;
  79. switch (pivot)
  80. {
  81. case Pivot::TOP_LEFT:
  82. pivot_x = 0;
  83. pivot_y = 0;
  84. break;
  85. case Pivot::TOP_CENTER:
  86. pivot_x = cell_w / 2;
  87. pivot_y = 0;
  88. break;
  89. case Pivot::TOP_RIGHT:
  90. pivot_x = cell_w;
  91. pivot_y = 0;
  92. break;
  93. case Pivot::BOTTOM_LEFT:
  94. pivot_x = 0;
  95. pivot_y = cell_h;
  96. break;
  97. case Pivot::BOTTOM_CENTER:
  98. pivot_x = cell_w / 2;
  99. pivot_y = cell_h;
  100. break;
  101. case Pivot::BOTTOM_RIGHT:
  102. pivot_x = cell_w;
  103. pivot_y = cell_h;
  104. break;
  105. case Pivot::LEFT:
  106. pivot_x = 0;
  107. pivot_y = cell_h / 2;
  108. break;
  109. case Pivot::CENTER:
  110. pivot_x = cell_w / 2;
  111. pivot_y = cell_h / 2;
  112. break;
  113. case Pivot::RIGHT:
  114. pivot_x = cell_w;
  115. pivot_y = cell_h / 2;
  116. break;
  117. default:
  118. CE_FATAL("Unknown pivot");
  119. break;
  120. }
  121. return vector2(pivot_x, pivot_y);
  122. }
  123. struct SpriteImporter
  124. {
  125. int width;
  126. int height;
  127. int cells_h;
  128. int cells_v;
  129. bool cell_wh_auto;
  130. int cell_w;
  131. int cell_h;
  132. int offset_x;
  133. int offset_y;
  134. int spacing_x;
  135. int spacing_y;
  136. int pivot;
  137. int layer;
  138. int depth;
  139. SpriteImporter()
  140. : width(128)
  141. , height(128)
  142. , cells_h(4)
  143. , cells_v(4)
  144. , cell_wh_auto(false)
  145. , cell_w(16)
  146. , cell_h(16)
  147. , offset_x(0)
  148. , offset_y(0)
  149. , spacing_x(0)
  150. , spacing_y(0)
  151. , pivot(Pivot::CENTER)
  152. , layer(0)
  153. , depth(0)
  154. {
  155. }
  156. void draw()
  157. {
  158. ImGui::Columns(2);
  159. #if 1
  160. ImDrawList* draw_list = ImGui::GetWindowDrawList();
  161. {
  162. // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered()
  163. // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos().
  164. // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max).
  165. ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
  166. ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
  167. if (canvas_size.x < 50.0f) canvas_size.x = 10.0f;
  168. if (canvas_size.y < 50.0f) canvas_size.y = 50.0f;
  169. draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60));
  170. // Pivot is relative to the top-left corner of the cell
  171. Vector2 pivot_xy = sprite_cell_pivot_xy(cell_w
  172. , cell_h
  173. , pivot
  174. );
  175. int num_v = cells_v;
  176. int num_h = cells_h;
  177. for (int h = 0; h < num_v; ++h)
  178. {
  179. for (int w = 0; w < num_h; ++w)
  180. {
  181. Vector2 cell = sprite_cell_xy(h
  182. , w
  183. , offset_x
  184. , offset_y
  185. , cell_w
  186. , cell_h
  187. , spacing_x
  188. , spacing_y
  189. );
  190. const int x0 = (int)cell.x;
  191. const int y0 = (int)cell.y;
  192. const int x1 = x0+(int)cell_w;
  193. const int y1 = y0+(int)cell_h;
  194. draw_list->AddRect(ImVec2(canvas_pos.x + x0, canvas_pos.y + y0)
  195. , ImVec2(canvas_pos.x + x1, canvas_pos.y + y1)
  196. , ImColor(230, 26, 26, 153)
  197. );
  198. draw_list->AddCircleFilled(ImVec2(x0 + canvas_pos.x + pivot_xy.x, y0 + canvas_pos.y + pivot_xy.y)
  199. , 5.0f
  200. , ImColor(26, 26, 230, 153)
  201. );
  202. }
  203. }
  204. ImGui::InvisibleButton("canvas", canvas_size);
  205. ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y);
  206. draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.)
  207. }
  208. #endif
  209. ImGui::NextColumn();
  210. ImGui::BeginGroup();
  211. ImGui::LabelText("Resolution", "%d x %d", width, height);
  212. // FIXME: replace fclamp
  213. ImGui::InputInt("Cells H", &cells_h);
  214. cells_h = (int)fclamp(cells_h, 1, 256);
  215. ImGui::InputInt("Cells V", &cells_v);
  216. cells_v = (int)fclamp(cells_v, 1, 256);
  217. ImGui::Checkbox("Cell WH auto", &cell_wh_auto);
  218. ImGui::InputInt("Cell W", &cell_w);
  219. cell_w = (int)fclamp(cell_w, 1, 4096);
  220. ImGui::InputInt("Cell H", &cell_h);
  221. cell_h = (int)fclamp(cell_h, 1, 4096);
  222. ImGui::InputInt("Offset X", &offset_x);
  223. offset_x = (int)fclamp(offset_x, 0, 128);
  224. ImGui::InputInt("Offset Y", &offset_y);
  225. offset_y = (int)fclamp(offset_y, 0, 128);
  226. ImGui::InputInt("Spacing X", &spacing_x);
  227. spacing_x = (int)fclamp(spacing_x, 0, 128);
  228. ImGui::InputInt("Spacing Y", &spacing_y);
  229. spacing_y = (int)fclamp(spacing_y, 0, 128);
  230. ImGui::Combo("Pivot", &pivot, pivot_names, Pivot::COUNT);
  231. ImGui::InputInt("Layer", &layer);
  232. layer = (int)fclamp(layer, 0, 7);
  233. ImGui::InputInt("Depth", &depth);
  234. depth = (int)fclamp(depth, 0, 9999);
  235. ImGui::EndGroup();
  236. }
  237. };
  238. //-----------------------------------------------------------------------------
  239. struct Inspector
  240. {
  241. // Inspector
  242. char _name[1024];
  243. f32 _position[3];
  244. f32 _rotation[3];
  245. f32 _scale[3];
  246. char _sprite[1024];
  247. char _material[1024];
  248. bool _visible;
  249. char _state_machine[1024];
  250. bool _open;
  251. Inspector()
  252. : _visible(true)
  253. , _open(true)
  254. {
  255. memset(_name, 0, sizeof(_name));
  256. memset(_sprite, 0, sizeof(_sprite));
  257. memset(_material, 0, sizeof(_material));
  258. memset(_position, 0, sizeof(_position));
  259. memset(_rotation, 0, sizeof(_rotation));
  260. memset(_scale, 0, sizeof(_scale));
  261. memset(_state_machine, 0, sizeof(_state_machine));
  262. }
  263. void draw()
  264. {
  265. if (!_open)
  266. return;
  267. if (ImGui::TreeNodeEx("Unit", ImGuiTreeNodeFlags_DefaultOpen))
  268. {
  269. ImGui::InputText("Name", _name, sizeof(_name));
  270. ImGui::TreePop();
  271. }
  272. if (ImGui::TreeNodeEx("Transform", ImGuiTreeNodeFlags_DefaultOpen))
  273. {
  274. ImGui::InputFloat3("Position", _position, ImGuiInputTextFlags_CharsDecimal);
  275. ImGui::InputFloat3("Rotation", _rotation, ImGuiInputTextFlags_CharsDecimal);
  276. ImGui::InputFloat3("Scale", _scale, ImGuiInputTextFlags_CharsDecimal);
  277. ImGui::TreePop();
  278. }
  279. if (ImGui::TreeNodeEx("Renderer", ImGuiTreeNodeFlags_DefaultOpen))
  280. {
  281. ImGui::InputText("Sprite", _sprite, sizeof(_sprite));
  282. ImGui::InputText("Material", _material, sizeof(_material));
  283. ImGui::Checkbox("Visible", &_visible);
  284. ImGui::TreePop();
  285. }
  286. if (ImGui::TreeNodeEx("Animation", ImGuiTreeNodeFlags_DefaultOpen))
  287. {
  288. ImGui::InputText("State Machine", _state_machine, sizeof(_state_machine));
  289. ImGui::TreePop();
  290. }
  291. }
  292. };
  293. //-----------------------------------------------------------------------------
  294. struct SceneView
  295. {
  296. ImVec2 _view_origin;
  297. ImVec2 _view_size;
  298. ImVec2 _mouse_curr;
  299. ImVec2 _mouse_last;
  300. bool _open;
  301. SceneView()
  302. : _open(true)
  303. {
  304. }
  305. void draw()
  306. {
  307. if (!_open)
  308. return;
  309. _view_origin = ImGui::GetCursorScreenPos();
  310. uint16_t w, h;
  311. device()->resolution(w, h);
  312. bgfx::TextureHandle txh = device()->_pipeline->_buffers[0];
  313. CE_ENSURE(bgfx::isValid(txh));
  314. ImGui::Image((void*)(uintptr_t)txh.idx
  315. , ImVec2(w, h)
  316. #if CROWN_PLATFORM_WINDOWS
  317. , ImVec2(0, 0)
  318. , ImVec2(1, 1)
  319. #else
  320. , ImVec2(0, 1)
  321. , ImVec2(1, 0)
  322. #endif // CROWN_PLATFORM_WINDOWS
  323. );
  324. ImVec2 mouse_pos_in_view = ImVec2(ImGui::GetIO().MousePos.x - _view_origin.x
  325. , ImGui::GetIO().MousePos.y - _view_origin.y
  326. );
  327. if (ImGui::IsWindowHovered()
  328. && mouse_pos_in_view.x > 0
  329. && mouse_pos_in_view.x < w
  330. && mouse_pos_in_view.y > 0
  331. && mouse_pos_in_view.y < h
  332. )
  333. {
  334. // Send all input to engine
  335. ImGui::CaptureMouseFromApp(false);
  336. ImGui::CaptureKeyboardFromApp(false);
  337. }
  338. else
  339. {
  340. // Send all input to imgui
  341. ImGui::CaptureMouseFromApp(true);
  342. ImGui::CaptureKeyboardFromApp(true);
  343. }
  344. _view_size = ImGui::GetWindowSize();
  345. _view_size.x -= _view_origin.x;
  346. }
  347. };
  348. //-----------------------------------------------------------------------------
  349. struct SceneTree
  350. {
  351. bool _open;
  352. SceneTree()
  353. : _open(true)
  354. {
  355. }
  356. void draw()
  357. {
  358. if (!_open)
  359. return;
  360. if (ImGui::TreeNodeEx("Units", ImGuiTreeNodeFlags_DefaultOpen))
  361. {
  362. if (ImGui::TreeNodeEx("Objects", ImGuiTreeNodeFlags_DefaultOpen))
  363. {
  364. for (int i = 0; i < 5; i++)
  365. if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i))
  366. {
  367. ImGui::Text("blah blah");
  368. ImGui::SameLine();
  369. if (ImGui::SmallButton("print")) printf("Child %d pressed", i);
  370. ImGui::TreePop();
  371. }
  372. ImGui::TreePop();
  373. }
  374. if (ImGui::TreeNodeEx("Lights", ImGuiTreeNodeFlags_DefaultOpen))
  375. {
  376. // ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, Ctrl+Click to toggle, click on arrows or double-click to open.");
  377. static bool align_label_with_current_x_position = false;
  378. ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position);
  379. ImGui::Text("Hello!");
  380. if (align_label_with_current_x_position)
  381. ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
  382. static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit.
  383. int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc.
  384. ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()*3); // Increase spacing to differentiate leaves from expanded contents.
  385. for (int i = 0; i < 6; i++)
  386. {
  387. // Disable the default open on single-click behavior and pass in Selected flag according to our selection state.
  388. ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0);
  389. if (i < 3)
  390. {
  391. // Node
  392. bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i);
  393. if (ImGui::IsItemClicked())
  394. node_clicked = i;
  395. if (node_open)
  396. {
  397. ImGui::Text("Blah blah\nBlah Blah");
  398. ImGui::TreePop();
  399. }
  400. }
  401. else
  402. {
  403. // Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text().
  404. ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i);
  405. if (ImGui::IsItemClicked())
  406. node_clicked = i;
  407. }
  408. }
  409. if (node_clicked != -1)
  410. {
  411. // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame.
  412. if (ImGui::GetIO().KeyCtrl)
  413. selection_mask ^= (1 << node_clicked); // Ctrl+click to toggle
  414. else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection
  415. selection_mask = (1 << node_clicked); // Click to single-select
  416. }
  417. ImGui::PopStyleVar();
  418. if (align_label_with_current_x_position)
  419. ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
  420. ImGui::TreePop();
  421. }
  422. ImGui::TreePop();
  423. }
  424. }
  425. };
  426. //-----------------------------------------------------------------------------
  427. struct SpriteAnimator
  428. {
  429. bool _open;
  430. bool _add_animation_popup_open;
  431. Array<const char*> _entities;
  432. s32 _cur_entity;
  433. TextureResource* _texture;
  434. u32 _texture_width;
  435. u32 _texture_height;
  436. struct Frame
  437. {
  438. char name[512];
  439. ImVec2 pivot;
  440. ImVec4 region;
  441. };
  442. Array<Frame> _frames;
  443. char _anim_name[512];
  444. f32 _anim_time;
  445. Array<const char*> _listbox_items;
  446. s32 _listbox_item_current;
  447. Array<Frame> _anim_preview_frames;
  448. f32 _delta;
  449. u32 current;
  450. Vector<DynamicString> file_list_sprites;
  451. FilesystemDisk* _fs;
  452. SpriteAnimator(const DynamicString& src_dir)
  453. : _open(false)
  454. , _add_animation_popup_open(false)
  455. , _entities(default_allocator())
  456. , _cur_entity(0)
  457. , _texture(nullptr)
  458. , _texture_width(0)
  459. , _texture_height(0)
  460. , _frames(default_allocator())
  461. , _anim_time(0.1f)
  462. , _listbox_items(default_allocator())
  463. , _listbox_item_current(0)
  464. , _anim_preview_frames(default_allocator())
  465. , _delta(0.0f)
  466. , current(0)
  467. , file_list_sprites(default_allocator())
  468. {
  469. memset(_anim_name, 0, sizeof(_anim_name));
  470. _fs = CE_NEW(default_allocator(), FilesystemDisk)(default_allocator());
  471. _fs->set_prefix(src_dir.c_str());
  472. get_sprites_list();
  473. }
  474. ~SpriteAnimator()
  475. {
  476. CE_DELETE(default_allocator(), _fs);
  477. }
  478. ImVec2 pixel_to_uv(u32 tex_w, u32 tex_h, f32 x, f32 y)
  479. {
  480. ImVec2 uv;
  481. uv.x = (f32)x / (f32)tex_w;
  482. uv.y = (f32)y / (f32)tex_h;
  483. return uv;
  484. }
  485. void get_directory(DynamicString& dir, const char* path)
  486. {
  487. CE_ENSURE(NULL != path);
  488. const char* ls = strrchr(path, '/');
  489. u32 file_len = strlen(ls+1);
  490. u32 dir_len = strlen(path) - file_len;
  491. char buff[1024];
  492. memcpy(buff, path, dir_len);
  493. buff[dir_len] = '\0';
  494. path::reduce(dir, buff);
  495. }
  496. void save_sprite_animation()
  497. {
  498. TempAllocator4096 ta;
  499. StringStream ss(ta);
  500. ss << "frames = [ ";
  501. for (u32 i = 0; i < array::size(_listbox_items); i++)
  502. {
  503. ss << _listbox_items[i] + 7 << " ";
  504. }
  505. ss << "]\n";
  506. ss << "total_time = ";
  507. ss << _anim_time;
  508. DynamicString dir(ta);
  509. get_directory(dir, _entities[_cur_entity]);
  510. DynamicString file_name(ta);
  511. path::join(file_name, dir.c_str(), _anim_name);
  512. file_name += ".sprite_animation";
  513. File* f = _fs->open(file_name.c_str(), FileOpenMode::WRITE);
  514. f->write(string_stream::c_str(ss), strlen(string_stream::c_str(ss)));
  515. f->close();
  516. }
  517. void get_files_list(Vector<DynamicString>& out, const char* path="")
  518. {
  519. TempAllocator4096 ta;
  520. Vector<DynamicString> files(ta);
  521. _fs->list_files(path, files);
  522. for (u32 i = 0; i < vector::size(files); i++)
  523. {
  524. DynamicString join(ta);
  525. path::join(join, path, files[i].c_str());
  526. join = join.c_str()[0] == '/' ? join.c_str()+1 : join.c_str();
  527. if (_fs->is_directory(join.c_str()))
  528. {
  529. get_files_list(out, join.c_str());
  530. }
  531. else
  532. {
  533. vector::push_back(out, join);
  534. }
  535. }
  536. }
  537. void get_sprites_list()
  538. {
  539. TempAllocator4096 ta;
  540. Vector<DynamicString> files(ta);
  541. get_files_list(files);
  542. for (DynamicString* f = vector::begin(files); f != vector::end(files); f++)
  543. if (f->has_suffix(".sprite"))
  544. array::push_back(_entities, (const char*) strdup(f->c_str()));
  545. }
  546. void draw()
  547. {
  548. if (!_open)
  549. return;
  550. if (_texture)
  551. {
  552. Frame f = _frames[0];
  553. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  554. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  555. ImGui::Image((void*)(uintptr_t)_texture->handle.idx
  556. , ImVec2(f.region.z, f.region.w)
  557. , start
  558. , end
  559. , ImColor(255, 255, 255, 55)
  560. );
  561. }
  562. if (ImGui::Combo("Entities", &_cur_entity, (const char* const*) array::begin(_entities), array::size(_entities)))
  563. {
  564. array::clear(_frames);
  565. const char* sprite = _entities[_cur_entity];
  566. u32 sprite_len = strlen(sprite);
  567. char entity[1024];
  568. strncpy(entity, sprite, strlen(sprite));
  569. entity[sprite_len-7] = '\0'; // remove ".sprite"
  570. ResourceManager* resman = device()->_resource_manager;
  571. _texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64(entity));
  572. File* file = _fs->open(sprite, FileOpenMode::READ);
  573. const u32 size = file->size();
  574. Buffer buf(default_allocator());
  575. array::resize(buf, size);
  576. file->read(array::begin(buf), size);
  577. _fs->close(*file);
  578. JsonObject obj(default_allocator());
  579. JsonArray list(default_allocator());
  580. sjson::parse(buf, obj);
  581. sjson::parse_array(obj["frames"], list);
  582. _texture_width = sjson::parse_int(obj["width"]);
  583. _texture_height = sjson::parse_int(obj["height"]);
  584. for (u32 i = 0; i < array::size(list); i++)
  585. {
  586. JsonObject frame(default_allocator());
  587. DynamicString name(default_allocator());
  588. JsonArray pivot(default_allocator());
  589. JsonArray region(default_allocator());
  590. sjson::parse_object(list[i], frame);
  591. sjson::parse_array(frame["pivot"], pivot);
  592. sjson::parse_array(frame["region"], region);
  593. Frame f;
  594. sjson::parse_string(frame["name"], name);
  595. strncpy(f.name, name.c_str(), name.length());
  596. f.name[name.length()] = '\0';
  597. f.pivot.x = sjson::parse_float(pivot[0]);
  598. f.pivot.y = sjson::parse_float(pivot[1]);
  599. f.region.x = sjson::parse_float(region[0]);
  600. f.region.y = sjson::parse_float(region[1]);
  601. f.region.z = sjson::parse_float(region[2]);
  602. f.region.w = sjson::parse_float(region[3]);
  603. array::push_back(_frames, f);
  604. }
  605. }
  606. if (ImGui::Button("Add animation", ImVec2(100, 25)))
  607. {
  608. _add_animation_popup_open = true;
  609. }
  610. if (_add_animation_popup_open)
  611. {
  612. ImGui::OpenPopup("Add animation");
  613. }
  614. if (ImGui::BeginPopup("Add animation"))
  615. {
  616. ImGui::InputText("Name", _anim_name, sizeof(_anim_name));
  617. ImGui::InputFloat("Time", &_anim_time, 0.1f, 0.1f, 1);
  618. ImGui::ListBox("Animation Frames", &_listbox_item_current, (const char* const*)array::begin(_listbox_items), array::size(_listbox_items));
  619. if (ImGui::Button("Clear Frames", ImVec2(100.0f, 25.0f)))
  620. {
  621. array::clear(_listbox_items);
  622. array::clear(_anim_preview_frames);
  623. _delta = 0.0f;
  624. current = 0;
  625. }
  626. if (array::size(_anim_preview_frames) > 0)
  627. {
  628. _delta += 1.0f/60.0f;
  629. if (_delta >= _anim_time/array::size(_anim_preview_frames))
  630. {
  631. _delta = 0;
  632. current++;
  633. if (current >= array::size(_anim_preview_frames))
  634. current = 0;
  635. }
  636. Frame f = _anim_preview_frames[current];
  637. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  638. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  639. ImGui::Image(
  640. (void*)(uintptr_t)_texture->handle.idx
  641. , ImVec2(f.region.z, f.region.w)
  642. , start
  643. , end
  644. , ImColor(255, 255, 255, 55)
  645. );
  646. }
  647. ImGui::Separator();
  648. for (u32 i = 0; i < array::size(_frames); i++)
  649. {
  650. Frame f = _frames[i];
  651. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  652. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  653. ImGui::SameLine();
  654. if (i % 9 == 0) ImGui::NewLine();
  655. ImGui::BeginGroup();
  656. ImGui::Image(
  657. (void*)(uintptr_t)_texture->handle.idx
  658. , ImVec2(f.region.z, f.region.w)
  659. , start
  660. , end
  661. , ImColor(255, 255, 255, 55)
  662. );
  663. ImGui::NewLine();
  664. if (ImGui::Button(_frames[i].name, ImVec2(100.0f, 25.0f)))
  665. {
  666. array::push_back(_listbox_items, (const char*) strdup(_frames[i].name));
  667. array::push_back(_anim_preview_frames, _frames[i]);
  668. }
  669. ImGui::EndGroup();
  670. }
  671. if (ImGui::Button("Save", ImVec2(100, 25)))
  672. {
  673. save_sprite_animation();
  674. ImGui::CloseCurrentPopup();
  675. _add_animation_popup_open = false;
  676. }
  677. ImGui::SameLine();
  678. if (ImGui::Button("Cancel", ImVec2(100, 25)))
  679. {
  680. ImGui::CloseCurrentPopup();
  681. _add_animation_popup_open = false;
  682. }
  683. ImGui::EndPopup();
  684. }
  685. }
  686. };
  687. //-----------------------------------------------------------------------------
  688. struct LevelEditor
  689. {
  690. DynamicString _source_dir;
  691. // FX
  692. TextureResource* tool_move_texture;
  693. TextureResource* tool_place_texture;
  694. TextureResource* tool_rotate_texture;
  695. TextureResource* tool_scale_texture;
  696. TextureResource* reference_world_texture;
  697. TextureResource* reference_local_texture;
  698. TextureResource* axis_local_texture;
  699. TextureResource* axis_world_texture;
  700. TextureResource* snap_to_grid_texture;
  701. // State
  702. f32 _grid_size;
  703. s32 _rotation_snap;
  704. bool _show_grid;
  705. bool _snap_to_grid;
  706. bool _debug_render_world;
  707. bool _debug_physics_world;
  708. tool::ToolType::Enum _tool_type;
  709. tool::SnapMode::Enum _snap_mode;
  710. tool::ReferenceSystem::Enum _reference_system;
  711. ImVec2 _main_menu_pos;
  712. ImVec2 _main_menu_size;
  713. ImVec2 _toolbar_pos;
  714. ImVec2 _toolbar_size;
  715. Console _console;
  716. Inspector _inspector;
  717. SceneView _scene_view;
  718. SceneTree _scene_tree;
  719. SpriteAnimator _animator;
  720. SpriteImporter _sprite_importer;
  721. LevelEditor(const DynamicString& source_dir)
  722. : _source_dir(default_allocator())
  723. , _grid_size(1.0f)
  724. , _rotation_snap(15)
  725. , _show_grid(true)
  726. , _snap_to_grid(true)
  727. , _debug_render_world(false)
  728. , _debug_physics_world(false)
  729. , _tool_type(tool::ToolType::MOVE)
  730. , _snap_mode(tool::SnapMode::RELATIVE)
  731. , _reference_system(tool::ReferenceSystem::LOCAL)
  732. , _main_menu_pos(0, 0)
  733. , _main_menu_size(0, 0)
  734. , _toolbar_pos(0, 0)
  735. , _toolbar_size(0, 0)
  736. , _animator(source_dir)
  737. {
  738. ResourceManager* resman = device()->_resource_manager;
  739. tool_move_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-move"));
  740. tool_place_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-place"));
  741. tool_rotate_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-rotate"));
  742. tool_scale_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-scale"));
  743. reference_world_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/reference-world"));
  744. reference_local_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/reference-local"));
  745. axis_local_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/axis-local"));
  746. axis_world_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/axis-world"));
  747. snap_to_grid_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/snap-to-grid"));
  748. imgui_create();
  749. ImGui::LoadDock();
  750. }
  751. ~LevelEditor()
  752. {
  753. ImGui::SaveDock();
  754. imgui_destroy();
  755. }
  756. void update(f32 dt)
  757. {
  758. CE_UNUSED(dt);
  759. static f32 last_w = 0.0f;
  760. static f32 last_h = 0.0f;
  761. if (last_w != _scene_view._view_size.x || last_h != _scene_view._view_size.y)
  762. {
  763. last_w = _scene_view._view_size.x;
  764. last_h = _scene_view._view_size.y;
  765. device()->_width = _scene_view._view_size.x != 0.0f ? _scene_view._view_size.x : 128.0f;
  766. device()->_height = _scene_view._view_size.y != 0.0f ? _scene_view._view_size.y : 128.0f;
  767. }
  768. u32 message_count = 0;
  769. // Receive response from engine
  770. for (;;)
  771. {
  772. u32 msg_len = 0;
  773. ReadResult rr = _console._client.read_nonblock(&msg_len, sizeof(msg_len));
  774. if (rr.error == ReadResult::WOULDBLOCK)
  775. break;
  776. if (ReadResult::SUCCESS == rr.error)
  777. {
  778. char msg[8192];
  779. rr = _console._client.read(msg, msg_len);
  780. msg[msg_len] = '\0';
  781. message_count++;
  782. // logi(LEVEL_EDITOR, "count: %d", message_count);
  783. if (ReadResult::SUCCESS == rr.error)
  784. {
  785. TempAllocator4096 ta;
  786. JsonObject obj(ta);
  787. DynamicString type(ta);
  788. json::parse(msg, obj);
  789. json::parse_string(obj["type"], type);
  790. if (type == "message")
  791. {
  792. DynamicString severity(ta);
  793. DynamicString message(ta);
  794. json::parse_string(obj["severity"], severity);
  795. json::parse_string(obj["message"], message);
  796. LogSeverity::Enum ls = LogSeverity::COUNT;
  797. if (strcmp("info", severity.c_str()) == 0)
  798. ls = LogSeverity::LOG_INFO;
  799. else if (strcmp("warning", severity.c_str()) == 0)
  800. ls = LogSeverity::LOG_WARN;
  801. else if (strcmp("error", severity.c_str()) == 0)
  802. ls = LogSeverity::LOG_ERROR;
  803. else
  804. CE_FATAL("Unknown severity");
  805. ConsoleLog log(ls, message.c_str());
  806. vector::push_back(_console._console_items, log);
  807. }
  808. else
  809. {
  810. ConsoleLog log(LogSeverity::LOG_ERROR, "Unknown message type");
  811. vector::push_back(_console._console_items, log);
  812. }
  813. console_scroll_to_bottom();
  814. }
  815. }
  816. }
  817. imgui_begin_frame(VIEW_IMGUI, _width, _height);
  818. f32 offset_y = _main_menu_size.y;
  819. ImGui::RootDock(ImVec2(0, offset_y), ImVec2(_width, _height-offset_y));
  820. main_menu_bar();
  821. if (ImGui::BeginDock("Scene View"
  822. , &_scene_view._open
  823. , ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)
  824. )
  825. {
  826. // Draw toolbar
  827. ImGui::BeginGroup();
  828. if (ImGui::ImageButton((void*)(uintptr_t)tool_place_texture->handle.idx, ImVec2(16, 16)))
  829. {
  830. _tool_type = tool::ToolType::PLACE;
  831. tool_send_state();
  832. }
  833. if (ImGui::ImageButton((void*)(uintptr_t)tool_move_texture->handle.idx, ImVec2(16, 16)))
  834. {
  835. _tool_type = tool::ToolType::MOVE;
  836. tool_send_state();
  837. }
  838. if (ImGui::ImageButton((void*)(uintptr_t)tool_rotate_texture->handle.idx, ImVec2(16, 16)))
  839. {
  840. _tool_type = tool::ToolType::ROTATE;
  841. tool_send_state();
  842. }
  843. if (ImGui::ImageButton((void*)(uintptr_t)tool_scale_texture->handle.idx, ImVec2(16, 16)))
  844. {
  845. _tool_type = tool::ToolType::SCALE;
  846. tool_send_state();
  847. }
  848. if (ImGui::ImageButton((void*)(uintptr_t)axis_local_texture->handle.idx, ImVec2(16, 16)))
  849. {
  850. _reference_system = tool::ReferenceSystem::LOCAL;
  851. tool_send_state();
  852. }
  853. if (ImGui::ImageButton((void*)(uintptr_t)axis_world_texture->handle.idx, ImVec2(16, 16)))
  854. {
  855. _reference_system = tool::ReferenceSystem::WORLD;
  856. tool_send_state();
  857. }
  858. if (ImGui::ImageButton((void*)(uintptr_t)reference_world_texture->handle.idx, ImVec2(16, 16)))
  859. {
  860. _snap_mode = tool::SnapMode::RELATIVE;
  861. tool_send_state();
  862. }
  863. if (ImGui::ImageButton((void*)(uintptr_t)reference_local_texture->handle.idx, ImVec2(16, 16)))
  864. {
  865. _snap_mode = tool::SnapMode::ABSOLUTE;
  866. tool_send_state();
  867. }
  868. ImGui::EndGroup();
  869. // Draw scene view
  870. ImGui::SameLine();
  871. _scene_view.draw();
  872. }
  873. ImGui::EndDock();
  874. if (ImGui::BeginDock("Scene Tree", &_scene_tree._open))
  875. {
  876. _scene_tree.draw();
  877. }
  878. ImGui::EndDock();
  879. if (ImGui::BeginDock("Inspector", &_inspector._open))
  880. {
  881. _inspector.draw();
  882. }
  883. ImGui::EndDock();
  884. if (ImGui::BeginDock("Console", &_console._open, ImGuiWindowFlags_NoScrollbar))
  885. {
  886. console_draw(_console);
  887. }
  888. ImGui::EndDock();
  889. if (ImGui::BeginDock("Animator", &_animator._open))
  890. {
  891. _animator.draw();
  892. }
  893. ImGui::EndDock();
  894. imgui_end_frame();
  895. }
  896. void send_command(StringStream& ss)
  897. {
  898. TempAllocator4096 ta;
  899. StringStream out(ta);
  900. out << "{\"type\":\"script\",\"script\":\"";
  901. out << string_stream::c_str(ss);
  902. out << "\"}";
  903. const char* cmd = string_stream::c_str(out);
  904. const u32 size = strlen32(cmd);
  905. _console._client.write(&size, sizeof(u32));
  906. _console._client.write(cmd, size);
  907. }
  908. void tool_send_state()
  909. {
  910. TempAllocator256 ta;
  911. StringStream ss(ta);
  912. tool::set_grid_size(ss, _grid_size);
  913. tool::set_rotation_snap(ss, _rotation_snap);
  914. tool::enable_show_grid(ss, _show_grid);
  915. tool::enable_snap_to_grid(ss, _snap_to_grid);
  916. tool::enable_debug_render_world(ss, _debug_render_world);
  917. tool::enable_debug_physics_world(ss, _debug_physics_world);
  918. tool::set_tool_type(ss, _tool_type);
  919. tool::set_snap_mode(ss, _snap_mode);
  920. tool::set_reference_system(ss, _reference_system);
  921. send_command(ss);
  922. }
  923. void format_time(uint64_t time, char* str, size_t size)
  924. {
  925. #if CROWN_PLATFORM_WINDOWS
  926. // SYSTEMTIME st;
  927. // FileTimeToSystemTime(&time, &st);
  928. // sprintf(str, "%d/%d/%d %d:%d"
  929. // , st.wDay
  930. // , st.wMonth
  931. // , st.wYear
  932. // , st.wHour
  933. // , st.wMinute);
  934. #else
  935. struct tm lt;
  936. localtime_r((time_t*)&time, &lt);
  937. strftime(str, size, "%d/%m/%Y %H:%M", &lt);
  938. #endif
  939. }
  940. void main_menu_bar()
  941. {
  942. // Main Menu
  943. if (ImGui::BeginMainMenuBar())
  944. {
  945. if (ImGui::BeginMenu("File"))
  946. {
  947. if (ImGui::MenuItem("New"))
  948. {
  949. }
  950. if (ImGui::MenuItem("Open", "Ctrl+O"))
  951. {
  952. nfdchar_t *out_path = NULL;
  953. nfdresult_t result = NFD_OpenDialog(NULL, NULL, &out_path);
  954. if ( result == NFD_OKAY )
  955. {
  956. logi(LEVEL_EDITOR, "Success!");
  957. logi(LEVEL_EDITOR, out_path);
  958. free(out_path);
  959. }
  960. else if ( result == NFD_CANCEL )
  961. {
  962. logi(LEVEL_EDITOR, "User pressed cancel.");
  963. }
  964. else
  965. {
  966. loge(LEVEL_EDITOR, "Error: %s\n", NFD_GetError());
  967. }
  968. }
  969. if (ImGui::MenuItem("Save", "Ctrl+S"))
  970. {
  971. }
  972. if (ImGui::MenuItem("Save As..."))
  973. {
  974. }
  975. ImGui::Separator();
  976. if (ImGui::MenuItem("Quit", "Ctrl+Q", false, true))
  977. {
  978. TempAllocator64 ta;
  979. StringStream ss(ta);
  980. tool::device_quit(ss);
  981. send_command(ss);
  982. }
  983. ImGui::EndMenu();
  984. }
  985. if (ImGui::BeginMenu("Edit"))
  986. {
  987. if (ImGui::MenuItem("Undo", "Ctrl+Z")) {}
  988. if (ImGui::MenuItem("Redo", "Ctrl+Y")) {}
  989. ImGui::EndMenu();
  990. }
  991. if (ImGui::BeginMenu("Create"))
  992. {
  993. TempAllocator256 ta;
  994. StringStream ss(ta);
  995. if (ImGui::BeginMenu("Primitives"))
  996. {
  997. if (ImGui::MenuItem("Cube", NULL, false, true))
  998. {
  999. _tool_type = tool::ToolType::PLACE;
  1000. tool_send_state();
  1001. tool::set_placeable(ss, "unit", "core/units/primitives/cube");
  1002. send_command(ss);
  1003. }
  1004. if (ImGui::MenuItem("Sphere"))
  1005. {
  1006. _tool_type = tool::ToolType::PLACE;
  1007. tool_send_state();
  1008. tool::set_placeable(ss, "unit", "core/units/primitives/sphere");
  1009. send_command(ss);
  1010. }
  1011. if (ImGui::MenuItem("Cone"))
  1012. {
  1013. _tool_type = tool::ToolType::PLACE;
  1014. tool_send_state();
  1015. tool::set_placeable(ss, "unit", "core/units/primitives/cone");
  1016. send_command(ss);
  1017. }
  1018. if (ImGui::MenuItem("Cylinder"))
  1019. {
  1020. _tool_type = tool::ToolType::PLACE;
  1021. tool_send_state();
  1022. tool::set_placeable(ss, "unit", "core/units/primitives/cylinder");
  1023. send_command(ss);
  1024. }
  1025. if (ImGui::MenuItem("Plane"))
  1026. {
  1027. _tool_type = tool::ToolType::PLACE;
  1028. tool_send_state();
  1029. tool::set_placeable(ss, "unit", "core/units/primitives/plane");
  1030. send_command(ss);
  1031. }
  1032. ImGui::EndMenu();
  1033. }
  1034. if (ImGui::MenuItem("Camera"))
  1035. {
  1036. _tool_type = tool::ToolType::PLACE;
  1037. tool_send_state();
  1038. tool::set_placeable(ss, "unit", "core/units/camera");
  1039. send_command(ss);
  1040. }
  1041. if (ImGui::MenuItem("Light"))
  1042. {
  1043. _tool_type = tool::ToolType::PLACE;
  1044. tool_send_state();
  1045. tool::set_placeable(ss, "unit", "core/units/light");
  1046. send_command(ss);
  1047. }
  1048. if (ImGui::MenuItem("Sound"))
  1049. {
  1050. _tool_type = tool::ToolType::PLACE;
  1051. tool_send_state();
  1052. tool::set_placeable(ss, "sound", "core/units/camera");
  1053. send_command(ss);
  1054. }
  1055. ImGui::EndMenu();
  1056. }
  1057. if (ImGui::BeginMenu("Scene View"))
  1058. {
  1059. TempAllocator256 ta;
  1060. StringStream ss(ta);
  1061. if (ImGui::BeginMenu("Camera View"))
  1062. {
  1063. if (ImGui::MenuItem("Perspective"))
  1064. {
  1065. tool::camera_view_perspective(ss);
  1066. send_command(ss);
  1067. }
  1068. if (ImGui::MenuItem("Front"))
  1069. {
  1070. tool::camera_view_front(ss);
  1071. send_command(ss);
  1072. }
  1073. if (ImGui::MenuItem("Back"))
  1074. {
  1075. tool::camera_view_back(ss);
  1076. send_command(ss);
  1077. }
  1078. if (ImGui::MenuItem("Right"))
  1079. {
  1080. tool::camera_view_right(ss);
  1081. send_command(ss);
  1082. }
  1083. if (ImGui::MenuItem("Left"))
  1084. {
  1085. tool::camera_view_left(ss);
  1086. send_command(ss);
  1087. }
  1088. if (ImGui::MenuItem("Top"))
  1089. {
  1090. tool::camera_view_top(ss);
  1091. send_command(ss);
  1092. }
  1093. if (ImGui::MenuItem("Bottom"))
  1094. {
  1095. tool::camera_view_bottom(ss);
  1096. send_command(ss);
  1097. }
  1098. ImGui::EndMenu();
  1099. }
  1100. ImGui::Separator();
  1101. if (ImGui::MenuItem("Show Grid", NULL, _show_grid))
  1102. {
  1103. _show_grid = !_show_grid;
  1104. tool_send_state();
  1105. }
  1106. if (ImGui::SliderFloat("Grid Size", &_grid_size, 0.1f, 5.0f))
  1107. {
  1108. tool_send_state();
  1109. }
  1110. if (ImGui::SliderInt("Snap Rot", &_rotation_snap, 1, 180))
  1111. {
  1112. tool_send_state();
  1113. }
  1114. ImGui::EndMenu();
  1115. }
  1116. if (ImGui::BeginMenu("Windows"))
  1117. {
  1118. if (ImGui::MenuItem("Scene"))
  1119. {
  1120. _scene_view._open = true;
  1121. }
  1122. if (ImGui::MenuItem("Scene Tree"))
  1123. {
  1124. _scene_tree._open = true;
  1125. }
  1126. if (ImGui::MenuItem("Inspector"))
  1127. {
  1128. _inspector._open = true;
  1129. }
  1130. if (ImGui::MenuItem("Console"))
  1131. {
  1132. _console._open = true;
  1133. }
  1134. if (ImGui::MenuItem("Animator"))
  1135. {
  1136. _animator._open = true;
  1137. }
  1138. ImGui::EndMenu();
  1139. }
  1140. if (ImGui::BeginMenu("Help"))
  1141. {
  1142. ImGui::MenuItem("About", "");
  1143. ImGui::EndMenu();
  1144. }
  1145. _main_menu_pos = ImGui::GetWindowPos();
  1146. _main_menu_size = ImGui::GetWindowSize();
  1147. ImGui::EndMainMenuBar();
  1148. }
  1149. }
  1150. void toolbar()
  1151. {
  1152. if (ImGui::BeginToolbar("Toolbar", _toolbar_pos, _toolbar_size))
  1153. {
  1154. if (ImGui::ToolbarButton((void*)(uintptr_t)tool_place_texture->handle.idx, ImVec4(0, 0, 0, 0), "Place"))
  1155. {
  1156. _tool_type = tool::ToolType::PLACE;
  1157. tool_send_state();
  1158. }
  1159. if (ImGui::ToolbarButton((void*)(uintptr_t)tool_move_texture->handle.idx, ImVec4(0, 0, 0, 0), "Move"))
  1160. {
  1161. _tool_type = tool::ToolType::MOVE;
  1162. tool_send_state();
  1163. }
  1164. if (ImGui::ToolbarButton((void*)(uintptr_t)tool_rotate_texture->handle.idx, ImVec4(0, 0, 0, 0), "Rotate"))
  1165. {
  1166. _tool_type = tool::ToolType::ROTATE;
  1167. tool_send_state();
  1168. }
  1169. if (ImGui::ToolbarButton((void*)(uintptr_t)tool_scale_texture->handle.idx, ImVec4(0, 0, 0, 0), "Scale"))
  1170. {
  1171. _tool_type = tool::ToolType::SCALE;
  1172. tool_send_state();
  1173. }
  1174. if (ImGui::ToolbarButton((void*)(uintptr_t)axis_local_texture->handle.idx, ImVec4(0, 0, 0, 0), "Reference System: Local"))
  1175. {
  1176. _reference_system = tool::ReferenceSystem::LOCAL;
  1177. tool_send_state();
  1178. }
  1179. if (ImGui::ToolbarButton((void*)(uintptr_t)axis_world_texture->handle.idx, ImVec4(0, 0, 0, 0), "Reference System: World"))
  1180. {
  1181. _reference_system = tool::ReferenceSystem::WORLD;
  1182. tool_send_state();
  1183. }
  1184. if (ImGui::ToolbarButton((void*)(uintptr_t)axis_local_texture->handle.idx, ImVec4(0, 0, 0, 0), "Snap Mode: Relative"))
  1185. {
  1186. _snap_mode = tool::SnapMode::RELATIVE;
  1187. tool_send_state();
  1188. }
  1189. if (ImGui::ToolbarButton((void*)(uintptr_t)reference_world_texture->handle.idx, ImVec4(0, 0, 0, 0), "Snap Mode: Absolute"))
  1190. {
  1191. _snap_mode = tool::SnapMode::ABSOLUTE;
  1192. tool_send_state();
  1193. }
  1194. _toolbar_pos = ImGui::GetWindowPos();
  1195. _toolbar_size = ImGui::GetWindowSize();
  1196. ImGui::EndToolbar();
  1197. }
  1198. }
  1199. };
  1200. LevelEditor* s_editor;
  1201. void tool_init()
  1202. {
  1203. const DeviceOptions& opt = device()->_device_options;
  1204. s_editor = CE_NEW(default_allocator(), LevelEditor)(opt._source_dir);
  1205. }
  1206. void tool_update(f32 dt)
  1207. {
  1208. s_editor->update(dt);
  1209. }
  1210. void tool_shutdown()
  1211. {
  1212. CE_DELETE(default_allocator(), s_editor);
  1213. }
  1214. extern bool next_event(OsEvent& ev);
  1215. bool tool_process_events()
  1216. {
  1217. ImGuiIO& io = ImGui::GetIO();
  1218. bool exit = false;
  1219. bool reset = false;
  1220. TempAllocator4096 ta;
  1221. StringStream ss(ta);
  1222. OsEvent event;
  1223. while (next_event(event))
  1224. {
  1225. if (event.type == OsEventType::NONE)
  1226. continue;
  1227. switch (event.type)
  1228. {
  1229. case OsEventType::BUTTON:
  1230. switch (event.button.device_id)
  1231. {
  1232. case crown::InputDeviceType::KEYBOARD:
  1233. io.KeyCtrl = ((event.button.button_num == crown::KeyboardButton::CTRL_LEFT)
  1234. || (event.button.button_num == crown::KeyboardButton::CTRL_RIGHT)) && event.button.pressed;
  1235. io.KeyShift = ((event.button.button_num == crown::KeyboardButton::SHIFT_LEFT)
  1236. || (event.button.button_num == crown::KeyboardButton::SHIFT_RIGHT)) && event.button.pressed;
  1237. io.KeyAlt = ((event.button.button_num == crown::KeyboardButton::ALT_LEFT)
  1238. || (event.button.button_num == crown::KeyboardButton::ALT_RIGHT)) && event.button.pressed;
  1239. io.KeySuper = ((event.button.button_num == crown::KeyboardButton::SUPER_LEFT)
  1240. || (event.button.button_num == crown::KeyboardButton::SUPER_RIGHT)) && event.button.pressed;
  1241. io.KeysDown[event.button.button_num] = event.button.pressed;
  1242. if (!io.WantCaptureKeyboard)
  1243. {
  1244. if (event.button.pressed)
  1245. {
  1246. if (event.button.button_num == crown::KeyboardButton::W)
  1247. tool::keyboard_pressed(ss, 'w');
  1248. if (event.button.button_num == crown::KeyboardButton::A)
  1249. tool::keyboard_pressed(ss, 'a');
  1250. if (event.button.button_num == crown::KeyboardButton::S)
  1251. tool::keyboard_pressed(ss, 's');
  1252. if (event.button.button_num == crown::KeyboardButton::D)
  1253. tool::keyboard_pressed(ss, 'd');
  1254. }
  1255. else
  1256. {
  1257. if (event.button.button_num == crown::KeyboardButton::W)
  1258. tool::keyboard_released(ss, 'w');
  1259. if (event.button.button_num == crown::KeyboardButton::A)
  1260. tool::keyboard_released(ss, 'a');
  1261. if (event.button.button_num == crown::KeyboardButton::S)
  1262. tool::keyboard_released(ss, 's');
  1263. if (event.button.button_num == crown::KeyboardButton::D)
  1264. tool::keyboard_released(ss, 'd');
  1265. }
  1266. }
  1267. break;
  1268. case crown::InputDeviceType::MOUSE:
  1269. io.MouseDown[0] = (event.button.button_num == crown::MouseButton::LEFT) && event.button.pressed;
  1270. io.MouseDown[1] = (event.button.button_num == crown::MouseButton::RIGHT) && event.button.pressed;
  1271. io.MouseDown[2] = (event.button.button_num == crown::MouseButton::MIDDLE) && event.button.pressed;
  1272. if (!io.WantCaptureMouse)
  1273. {
  1274. ImVec2& mouse_curr = s_editor->_scene_view._mouse_curr;
  1275. mouse_curr.x = io.MousePos.x - s_editor->_scene_view._view_origin.x;
  1276. mouse_curr.y = io.MousePos.y - s_editor->_scene_view._view_origin.y;
  1277. tool::set_mouse_state(ss
  1278. , mouse_curr.x
  1279. , mouse_curr.y
  1280. , io.MouseDown[0]
  1281. , io.MouseDown[2]
  1282. , io.MouseDown[1]
  1283. );
  1284. if (event.button.button_num == crown::MouseButton::LEFT)
  1285. {
  1286. if (event.button.pressed)
  1287. tool::mouse_down(ss, mouse_curr.x, mouse_curr.y);
  1288. else
  1289. tool::mouse_up(ss, mouse_curr.x, mouse_curr.y);
  1290. }
  1291. }
  1292. break;
  1293. }
  1294. break;
  1295. case OsEventType::AXIS:
  1296. switch(event.axis.device_id)
  1297. {
  1298. case InputDeviceType::MOUSE:
  1299. switch(event.axis.axis_num)
  1300. {
  1301. case crown::MouseAxis::CURSOR:
  1302. io.MousePos = ImVec2(event.axis.axis_x, event.axis.axis_y);
  1303. if (!io.WantCaptureMouse)
  1304. {
  1305. ImVec2& mouse_curr = s_editor->_scene_view._mouse_curr;
  1306. ImVec2& mouse_last = s_editor->_scene_view._mouse_last;
  1307. mouse_curr.x = io.MousePos.x - s_editor->_scene_view._view_origin.x;
  1308. mouse_curr.y = io.MousePos.y - s_editor->_scene_view._view_origin.y;
  1309. f32 delta_x = mouse_curr.x - mouse_last.x;
  1310. f32 delta_y = mouse_curr.y - mouse_last.y;
  1311. tool::mouse_move(ss, mouse_curr.x, mouse_curr.y, delta_x, delta_y);
  1312. mouse_last = mouse_curr;
  1313. }
  1314. break;
  1315. case crown::MouseAxis::WHEEL:
  1316. io.MouseWheel += event.axis.axis_y;
  1317. if (!io.WantCaptureMouse)
  1318. tool::mouse_wheel(ss, io.MouseWheel);
  1319. break;
  1320. }
  1321. }
  1322. break;
  1323. case OsEventType::TEXT:
  1324. io.AddInputCharactersUTF8((const char*) event.text.utf8);
  1325. break;
  1326. case OsEventType::RESOLUTION:
  1327. _width = event.resolution.width;
  1328. _height = event.resolution.height;
  1329. reset = true;
  1330. break;
  1331. case OsEventType::EXIT:
  1332. exit = true;
  1333. break;
  1334. default:
  1335. break;
  1336. }
  1337. }
  1338. s_editor->send_command(ss);
  1339. bool vsync = true;
  1340. if (reset)
  1341. bgfx::reset(_width, _height, (vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE));
  1342. return exit;
  1343. }
  1344. } // namespace crown
  1345. #endif // CROWN_TOOLS