level_editor.cpp 41 KB

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