level_editor.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  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/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((f32)x0, (f32)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((f32)pivot_x, (f32)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. 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.)
  206. }
  207. #endif
  208. ImGui::NextColumn();
  209. ImGui::BeginGroup();
  210. ImGui::LabelText("Resolution", "%d x %d", width, height);
  211. // FIXME: replace fclamp
  212. ImGui::InputInt("Cells H", &cells_h);
  213. cells_h = (int)fclamp((f32)cells_h, 1.0f, 256.0f);
  214. ImGui::InputInt("Cells V", &cells_v);
  215. cells_v = (int)fclamp((f32)cells_v, 1.0f, 256.0f);
  216. ImGui::Checkbox("Cell WH auto", &cell_wh_auto);
  217. ImGui::InputInt("Cell W", &cell_w);
  218. cell_w = (int)fclamp((f32)cell_w, 1.0f, 4096.0f);
  219. ImGui::InputInt("Cell H", &cell_h);
  220. cell_h = (int)fclamp((f32)cell_h, 1.0f, 4096.0f);
  221. ImGui::InputInt("Offset X", &offset_x);
  222. offset_x = (int)fclamp((f32)offset_x, 0.0f, 128.0f);
  223. ImGui::InputInt("Offset Y", &offset_y);
  224. offset_y = (int)fclamp((f32)offset_y, 0.0f, 128.0f);
  225. ImGui::InputInt("Spacing X", &spacing_x);
  226. spacing_x = (int)fclamp((f32)spacing_x, 0.0f, 128.0f);
  227. ImGui::InputInt("Spacing Y", &spacing_y);
  228. spacing_y = (int)fclamp((f32)spacing_y, 0.0f, 128.0f);
  229. ImGui::Combo("Pivot", &pivot, pivot_names, Pivot::COUNT);
  230. ImGui::InputInt("Layer", &layer);
  231. layer = (int)fclamp((f32)layer, 0.0f, 7.0f);
  232. ImGui::InputInt("Depth", &depth);
  233. depth = (int)fclamp((f32)depth, 0.0f, 9999.0f);
  234. ImGui::EndGroup();
  235. }
  236. };
  237. //-----------------------------------------------------------------------------
  238. struct Inspector
  239. {
  240. // Inspector
  241. char _name[1024];
  242. f32 _position[3];
  243. f32 _rotation[3];
  244. f32 _scale[3];
  245. char _sprite[1024];
  246. char _material[1024];
  247. bool _visible;
  248. char _state_machine[1024];
  249. bool _open;
  250. Inspector()
  251. : _visible(true)
  252. , _open(true)
  253. {
  254. memset(_name, 0, sizeof(_name));
  255. memset(_sprite, 0, sizeof(_sprite));
  256. memset(_material, 0, sizeof(_material));
  257. memset(_position, 0, sizeof(_position));
  258. memset(_rotation, 0, sizeof(_rotation));
  259. memset(_scale, 0, sizeof(_scale));
  260. memset(_state_machine, 0, sizeof(_state_machine));
  261. }
  262. void draw()
  263. {
  264. if (!_open)
  265. return;
  266. if (ImGui::TreeNodeEx("Unit", ImGuiTreeNodeFlags_DefaultOpen))
  267. {
  268. ImGui::InputText("Name", _name, sizeof(_name));
  269. ImGui::TreePop();
  270. }
  271. if (ImGui::TreeNodeEx("Transform", ImGuiTreeNodeFlags_DefaultOpen))
  272. {
  273. ImGui::InputFloat3("Position", _position);
  274. ImGui::InputFloat3("Rotation", _rotation);
  275. ImGui::InputFloat3("Scale", _scale);
  276. ImGui::TreePop();
  277. }
  278. if (ImGui::TreeNodeEx("Renderer", ImGuiTreeNodeFlags_DefaultOpen))
  279. {
  280. ImGui::InputText("Sprite", _sprite, sizeof(_sprite));
  281. ImGui::InputText("Material", _material, sizeof(_material));
  282. ImGui::Checkbox("Visible", &_visible);
  283. ImGui::TreePop();
  284. }
  285. if (ImGui::TreeNodeEx("Animation", ImGuiTreeNodeFlags_DefaultOpen))
  286. {
  287. ImGui::InputText("State Machine", _state_machine, sizeof(_state_machine));
  288. ImGui::TreePop();
  289. }
  290. }
  291. };
  292. //-----------------------------------------------------------------------------
  293. struct SceneView
  294. {
  295. ImVec2 _origin;
  296. ImVec2 _size;
  297. ImVec2 _mouse;
  298. ImVec2 _mouse_last;
  299. bool _open;
  300. SceneView()
  301. : _open(true)
  302. {
  303. }
  304. void draw()
  305. {
  306. if (!_open)
  307. return;
  308. _origin = ImGui::GetCursorScreenPos();
  309. uint16_t w, h;
  310. device()->resolution(w, h);
  311. bgfx::TextureHandle txh = device()->_pipeline->_buffers[0];
  312. CE_ENSURE(bgfx::isValid(txh));
  313. ImGui::Image((void*)(uintptr_t)txh.idx
  314. , ImVec2(w, h)
  315. #if CROWN_PLATFORM_WINDOWS
  316. , ImVec2(0, 0)
  317. , ImVec2(1, 1)
  318. #else
  319. , ImVec2(0, 1)
  320. , ImVec2(1, 0)
  321. #endif // CROWN_PLATFORM_WINDOWS
  322. );
  323. ImVec2 mouse_pos_in_view = ImVec2(ImGui::GetIO().MousePos.x - _origin.x
  324. , ImGui::GetIO().MousePos.y - _origin.y
  325. );
  326. if (ImGui::IsWindowHovered()
  327. && mouse_pos_in_view.x > 0
  328. && mouse_pos_in_view.x < w
  329. && mouse_pos_in_view.y > 0
  330. && mouse_pos_in_view.y < h
  331. )
  332. {
  333. // Send all input to engine
  334. ImGui::CaptureMouseFromApp(false);
  335. ImGui::CaptureKeyboardFromApp(false);
  336. }
  337. else
  338. {
  339. // Send all input to imgui
  340. ImGui::CaptureMouseFromApp(true);
  341. ImGui::CaptureKeyboardFromApp(true);
  342. }
  343. _size = ImGui::GetWindowSize();
  344. _size.x -= _origin.x;
  345. }
  346. };
  347. //-----------------------------------------------------------------------------
  348. struct SceneTree
  349. {
  350. bool _open;
  351. SceneTree()
  352. : _open(true)
  353. {
  354. }
  355. void draw()
  356. {
  357. if (!_open)
  358. return;
  359. if (ImGui::TreeNodeEx("Units", ImGuiTreeNodeFlags_DefaultOpen))
  360. {
  361. if (ImGui::TreeNodeEx("Objects", ImGuiTreeNodeFlags_DefaultOpen))
  362. {
  363. for (int i = 0; i < 5; i++)
  364. if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i))
  365. {
  366. ImGui::Text("blah blah");
  367. ImGui::SameLine();
  368. if (ImGui::SmallButton("print")) printf("Child %d pressed", i);
  369. ImGui::TreePop();
  370. }
  371. ImGui::TreePop();
  372. }
  373. if (ImGui::TreeNodeEx("Lights", ImGuiTreeNodeFlags_DefaultOpen))
  374. {
  375. // 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.");
  376. static bool align_label_with_current_x_position = false;
  377. ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position);
  378. ImGui::Text("Hello!");
  379. if (align_label_with_current_x_position)
  380. ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
  381. 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.
  382. 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.
  383. ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()*3); // Increase spacing to differentiate leaves from expanded contents.
  384. for (int i = 0; i < 6; i++)
  385. {
  386. // Disable the default open on single-click behavior and pass in Selected flag according to our selection state.
  387. ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0);
  388. if (i < 3)
  389. {
  390. // Node
  391. bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i);
  392. if (ImGui::IsItemClicked())
  393. node_clicked = i;
  394. if (node_open)
  395. {
  396. ImGui::Text("Blah blah\nBlah Blah");
  397. ImGui::TreePop();
  398. }
  399. }
  400. else
  401. {
  402. // 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().
  403. ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i);
  404. if (ImGui::IsItemClicked())
  405. node_clicked = i;
  406. }
  407. }
  408. if (node_clicked != -1)
  409. {
  410. // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame.
  411. if (ImGui::GetIO().KeyCtrl)
  412. selection_mask ^= (1 << node_clicked); // Ctrl+click to toggle
  413. 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
  414. selection_mask = (1 << node_clicked); // Click to single-select
  415. }
  416. ImGui::PopStyleVar();
  417. if (align_label_with_current_x_position)
  418. ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
  419. ImGui::TreePop();
  420. }
  421. ImGui::TreePop();
  422. }
  423. }
  424. };
  425. //-----------------------------------------------------------------------------
  426. struct SpriteAnimator
  427. {
  428. bool _open;
  429. bool _add_animation_popup_open;
  430. Array<const char*> _entities;
  431. s32 _cur_entity;
  432. TextureResource* _texture;
  433. u32 _texture_width;
  434. u32 _texture_height;
  435. struct Frame
  436. {
  437. char name[512];
  438. ImVec2 pivot;
  439. ImVec4 region;
  440. };
  441. Array<Frame> _frames;
  442. char _anim_name[512];
  443. f32 _anim_time;
  444. Array<const char*> _listbox_items;
  445. s32 _listbox_item_current;
  446. Array<Frame> _anim_preview_frames;
  447. f32 _delta;
  448. u32 current;
  449. Vector<DynamicString> file_list_sprites;
  450. FilesystemDisk* _fs;
  451. SpriteAnimator(const DynamicString& src_dir)
  452. : _open(false)
  453. , _add_animation_popup_open(false)
  454. , _entities(default_allocator())
  455. , _cur_entity(0)
  456. , _texture(nullptr)
  457. , _texture_width(0)
  458. , _texture_height(0)
  459. , _frames(default_allocator())
  460. , _anim_time(0.1f)
  461. , _listbox_items(default_allocator())
  462. , _listbox_item_current(0)
  463. , _anim_preview_frames(default_allocator())
  464. , _delta(0.0f)
  465. , current(0)
  466. , file_list_sprites(default_allocator())
  467. {
  468. memset(_anim_name, 0, sizeof(_anim_name));
  469. _fs = CE_NEW(default_allocator(), FilesystemDisk)(default_allocator());
  470. _fs->set_prefix(src_dir.c_str());
  471. get_sprites_list();
  472. }
  473. ~SpriteAnimator()
  474. {
  475. CE_DELETE(default_allocator(), _fs);
  476. }
  477. ImVec2 pixel_to_uv(u32 tex_w, u32 tex_h, f32 x, f32 y)
  478. {
  479. ImVec2 uv;
  480. uv.x = (f32)x / (f32)tex_w;
  481. uv.y = (f32)y / (f32)tex_h;
  482. return uv;
  483. }
  484. void get_directory(DynamicString& dir, const char* path)
  485. {
  486. CE_ENSURE(NULL != path);
  487. const char* ls = strrchr(path, '/');
  488. u32 file_len = strlen32(ls+1);
  489. u32 dir_len = strlen32(path) - file_len;
  490. char buff[1024];
  491. memcpy(buff, path, dir_len);
  492. buff[dir_len] = '\0';
  493. path::reduce(dir, buff);
  494. }
  495. void save_sprite_animation()
  496. {
  497. TempAllocator4096 ta;
  498. StringStream ss(ta);
  499. ss << "frames = [ ";
  500. for (u32 i = 0; i < array::size(_listbox_items); i++)
  501. {
  502. ss << _listbox_items[i] + 7 << " ";
  503. }
  504. ss << "]\n";
  505. ss << "total_time = ";
  506. ss << _anim_time;
  507. DynamicString dir(ta);
  508. get_directory(dir, _entities[_cur_entity]);
  509. DynamicString file_name(ta);
  510. path::join(file_name, dir.c_str(), _anim_name);
  511. file_name += ".sprite_animation";
  512. File* f = _fs->open(file_name.c_str(), FileOpenMode::WRITE);
  513. f->write(string_stream::c_str(ss), strlen32(string_stream::c_str(ss)));
  514. f->close();
  515. }
  516. void get_files_list(Vector<DynamicString>& out, const char* path="")
  517. {
  518. TempAllocator4096 ta;
  519. Vector<DynamicString> files(ta);
  520. _fs->list_files(path, files);
  521. for (u32 i = 0; i < vector::size(files); i++)
  522. {
  523. DynamicString join(ta);
  524. path::join(join, path, files[i].c_str());
  525. join = join.c_str()[0] == '/' ? join.c_str()+1 : join.c_str();
  526. if (_fs->is_directory(join.c_str()))
  527. {
  528. get_files_list(out, join.c_str());
  529. }
  530. else
  531. {
  532. vector::push_back(out, join);
  533. }
  534. }
  535. }
  536. void get_sprites_list()
  537. {
  538. TempAllocator4096 ta;
  539. Vector<DynamicString> files(ta);
  540. get_files_list(files);
  541. for (DynamicString* f = vector::begin(files); f != vector::end(files); f++)
  542. if (f->has_suffix(".sprite"))
  543. array::push_back(_entities, (const char*) strdup(f->c_str()));
  544. }
  545. void draw()
  546. {
  547. if (!_open)
  548. return;
  549. if (_texture)
  550. {
  551. Frame f = _frames[0];
  552. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  553. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  554. ImGui::Image((void*)(uintptr_t)_texture->handle.idx
  555. , ImVec2(f.region.z, f.region.w)
  556. , start
  557. , end
  558. , ImColor(255, 255, 255, 55)
  559. );
  560. }
  561. if (ImGui::Combo("Entities", &_cur_entity, (const char* const*) array::begin(_entities), array::size(_entities)))
  562. {
  563. array::clear(_frames);
  564. const char* sprite = _entities[_cur_entity];
  565. u32 sprite_len = strlen32(sprite);
  566. char entity[1024];
  567. strncpy(entity, sprite, sizeof(entity)-1);
  568. entity[sprite_len-7] = '\0'; // remove ".sprite"
  569. ResourceManager* resman = device()->_resource_manager;
  570. _texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64(entity));
  571. File* file = _fs->open(sprite, FileOpenMode::READ);
  572. const u32 size = file->size();
  573. Buffer buf(default_allocator());
  574. array::resize(buf, size);
  575. file->read(array::begin(buf), size);
  576. _fs->close(*file);
  577. JsonObject obj(default_allocator());
  578. JsonArray list(default_allocator());
  579. sjson::parse(buf, obj);
  580. sjson::parse_array(obj["frames"], list);
  581. _texture_width = sjson::parse_int(obj["width"]);
  582. _texture_height = sjson::parse_int(obj["height"]);
  583. for (u32 i = 0; i < array::size(list); i++)
  584. {
  585. JsonObject frame(default_allocator());
  586. DynamicString name(default_allocator());
  587. JsonArray pivot(default_allocator());
  588. JsonArray region(default_allocator());
  589. sjson::parse_object(list[i], frame);
  590. sjson::parse_array(frame["pivot"], pivot);
  591. sjson::parse_array(frame["region"], region);
  592. Frame f;
  593. sjson::parse_string(frame["name"], name);
  594. strncpy(f.name, name.c_str(), name.length());
  595. f.name[name.length()] = '\0';
  596. f.pivot.x = sjson::parse_float(pivot[0]);
  597. f.pivot.y = sjson::parse_float(pivot[1]);
  598. f.region.x = sjson::parse_float(region[0]);
  599. f.region.y = sjson::parse_float(region[1]);
  600. f.region.z = sjson::parse_float(region[2]);
  601. f.region.w = sjson::parse_float(region[3]);
  602. array::push_back(_frames, f);
  603. }
  604. }
  605. if (ImGui::Button("Add animation", ImVec2(100, 25)))
  606. {
  607. _add_animation_popup_open = true;
  608. }
  609. if (_add_animation_popup_open)
  610. {
  611. ImGui::OpenPopup("Add animation");
  612. }
  613. if (ImGui::BeginPopup("Add animation"))
  614. {
  615. ImGui::InputText("Name", _anim_name, sizeof(_anim_name));
  616. ImGui::InputFloat("Time", &_anim_time, 0.1f, 0.1f);
  617. ImGui::ListBox("Animation Frames", &_listbox_item_current, (const char* const*)array::begin(_listbox_items), array::size(_listbox_items));
  618. if (ImGui::Button("Clear Frames", ImVec2(100.0f, 25.0f)))
  619. {
  620. array::clear(_listbox_items);
  621. array::clear(_anim_preview_frames);
  622. _delta = 0.0f;
  623. current = 0;
  624. }
  625. if (array::size(_anim_preview_frames) > 0)
  626. {
  627. _delta += 1.0f/60.0f;
  628. if (_delta >= _anim_time/array::size(_anim_preview_frames))
  629. {
  630. _delta = 0;
  631. current++;
  632. if (current >= array::size(_anim_preview_frames))
  633. current = 0;
  634. }
  635. Frame f = _anim_preview_frames[current];
  636. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  637. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  638. ImGui::Image(
  639. (void*)(uintptr_t)_texture->handle.idx
  640. , ImVec2(f.region.z, f.region.w)
  641. , start
  642. , end
  643. , ImColor(255, 255, 255, 55)
  644. );
  645. }
  646. ImGui::Separator();
  647. for (u32 i = 0; i < array::size(_frames); i++)
  648. {
  649. Frame f = _frames[i];
  650. ImVec2 start = pixel_to_uv(_texture_width, _texture_height, f.region.x, f.region.y);
  651. ImVec2 end = pixel_to_uv(_texture_width, _texture_height, f.region.x+f.region.z, f.region.y+f.region.w);
  652. ImGui::SameLine();
  653. if (i % 9 == 0) ImGui::NewLine();
  654. ImGui::BeginGroup();
  655. ImGui::Image(
  656. (void*)(uintptr_t)_texture->handle.idx
  657. , ImVec2(f.region.z, f.region.w)
  658. , start
  659. , end
  660. , ImColor(255, 255, 255, 55)
  661. );
  662. ImGui::NewLine();
  663. if (ImGui::Button(_frames[i].name, ImVec2(100.0f, 25.0f)))
  664. {
  665. array::push_back(_listbox_items, (const char*) strdup(_frames[i].name));
  666. array::push_back(_anim_preview_frames, _frames[i]);
  667. }
  668. ImGui::EndGroup();
  669. }
  670. if (ImGui::Button("Save", ImVec2(100, 25)))
  671. {
  672. save_sprite_animation();
  673. ImGui::CloseCurrentPopup();
  674. _add_animation_popup_open = false;
  675. }
  676. ImGui::SameLine();
  677. if (ImGui::Button("Cancel", ImVec2(100, 25)))
  678. {
  679. ImGui::CloseCurrentPopup();
  680. _add_animation_popup_open = false;
  681. }
  682. ImGui::EndPopup();
  683. }
  684. }
  685. };
  686. //-----------------------------------------------------------------------------
  687. struct LevelEditor
  688. {
  689. DynamicString _source_dir;
  690. // FX
  691. TextureResource* tool_move_texture;
  692. TextureResource* tool_place_texture;
  693. TextureResource* tool_rotate_texture;
  694. TextureResource* tool_scale_texture;
  695. TextureResource* reference_world_texture;
  696. TextureResource* reference_local_texture;
  697. TextureResource* axis_local_texture;
  698. TextureResource* axis_world_texture;
  699. TextureResource* snap_to_grid_texture;
  700. // State
  701. f32 _grid_size;
  702. f32 _rotation_snap;
  703. bool _show_grid;
  704. bool _snap_to_grid;
  705. bool _debug_render_world;
  706. bool _debug_physics_world;
  707. tool::ToolType::Enum _tool_type;
  708. tool::SnapMode::Enum _snap_mode;
  709. tool::ReferenceSystem::Enum _reference_system;
  710. ImVec2 _main_menu_pos;
  711. ImVec2 _main_menu_size;
  712. Console _console;
  713. Inspector _inspector;
  714. SceneView _scene_view;
  715. SceneTree _scene_tree;
  716. SpriteAnimator _animator;
  717. SpriteImporter _sprite_importer;
  718. LevelEditor(const DynamicString& source_dir)
  719. : _source_dir(default_allocator())
  720. , _grid_size(1.0f)
  721. , _rotation_snap(15)
  722. , _show_grid(true)
  723. , _snap_to_grid(true)
  724. , _debug_render_world(false)
  725. , _debug_physics_world(false)
  726. , _tool_type(tool::ToolType::MOVE)
  727. , _snap_mode(tool::SnapMode::RELATIVE)
  728. , _reference_system(tool::ReferenceSystem::LOCAL)
  729. , _main_menu_pos(0, 0)
  730. , _main_menu_size(0, 0)
  731. , _animator(source_dir)
  732. {
  733. ResourceManager* resman = device()->_resource_manager;
  734. tool_move_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-move"));
  735. tool_place_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-place"));
  736. tool_rotate_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-rotate"));
  737. tool_scale_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/tool-scale"));
  738. reference_world_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/reference-world"));
  739. reference_local_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/reference-local"));
  740. axis_local_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/axis-local"));
  741. axis_world_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/axis-world"));
  742. snap_to_grid_texture = (TextureResource*)resman->get(RESOURCE_TYPE_TEXTURE, StringId64("core/editors/gui/snap-to-grid"));
  743. imgui_create();
  744. ImGui::LoadDock();
  745. }
  746. ~LevelEditor()
  747. {
  748. ImGui::SaveDock();
  749. imgui_destroy();
  750. }
  751. void update(f32 dt)
  752. {
  753. CE_UNUSED(dt);
  754. static f32 last_w = 0.0f;
  755. static f32 last_h = 0.0f;
  756. if (last_w != _scene_view._size.x || last_h != _scene_view._size.y)
  757. {
  758. last_w = _scene_view._size.x;
  759. last_h = _scene_view._size.y;
  760. device()->_width = u16(_scene_view._size.x != 0.0f ? _scene_view._size.x : 128.0f);
  761. device()->_height = u16(_scene_view._size.y != 0.0f ? _scene_view._size.y : 128.0f);
  762. }
  763. u32 message_count = 0;
  764. // Receive response from engine
  765. for (;;)
  766. {
  767. u32 msg_len = 0;
  768. ReadResult rr = _console._client.read_nonblock(&msg_len, sizeof(msg_len));
  769. if (rr.error == ReadResult::WOULDBLOCK)
  770. break;
  771. if (ReadResult::SUCCESS == rr.error)
  772. {
  773. char msg[8192];
  774. rr = _console._client.read(msg, msg_len);
  775. msg[msg_len] = '\0';
  776. message_count++;
  777. // logi(LEVEL_EDITOR, "count: %d", message_count);
  778. if (ReadResult::SUCCESS == rr.error)
  779. {
  780. TempAllocator4096 ta;
  781. JsonObject obj(ta);
  782. DynamicString type(ta);
  783. json::parse(msg, obj);
  784. json::parse_string(obj["type"], type);
  785. if (type == "message")
  786. {
  787. DynamicString severity(ta);
  788. DynamicString message(ta);
  789. json::parse_string(obj["severity"], severity);
  790. json::parse_string(obj["message"], message);
  791. LogSeverity::Enum ls = LogSeverity::COUNT;
  792. if (strcmp("info", severity.c_str()) == 0)
  793. ls = LogSeverity::LOG_INFO;
  794. else if (strcmp("warning", severity.c_str()) == 0)
  795. ls = LogSeverity::LOG_WARN;
  796. else if (strcmp("error", severity.c_str()) == 0)
  797. ls = LogSeverity::LOG_ERROR;
  798. else
  799. CE_FATAL("Unknown severity");
  800. _console.add_log(ls, message.c_str());
  801. }
  802. else
  803. {
  804. _console.add_log(LogSeverity::LOG_ERROR, "Unknown message type");
  805. }
  806. console_scroll_to_bottom(_console);
  807. }
  808. }
  809. }
  810. imgui_begin_frame(VIEW_IMGUI, _width, _height);
  811. f32 offset_y = _main_menu_size.y;
  812. ImGui::RootDock(ImVec2(0, offset_y), ImVec2(_width, _height-offset_y));
  813. main_menu_bar();
  814. if (ImGui::BeginDock("Scene View"
  815. , &_scene_view._open
  816. , ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)
  817. )
  818. {
  819. // Draw toolbar
  820. ImGui::BeginGroup();
  821. if (ImGui::ImageButton((void*)(uintptr_t)tool_place_texture->handle.idx, ImVec2(16, 16)))
  822. {
  823. _tool_type = tool::ToolType::PLACE;
  824. tool_send_state();
  825. }
  826. if (ImGui::ImageButton((void*)(uintptr_t)tool_move_texture->handle.idx, ImVec2(16, 16)))
  827. {
  828. _tool_type = tool::ToolType::MOVE;
  829. tool_send_state();
  830. }
  831. if (ImGui::ImageButton((void*)(uintptr_t)tool_rotate_texture->handle.idx, ImVec2(16, 16)))
  832. {
  833. _tool_type = tool::ToolType::ROTATE;
  834. tool_send_state();
  835. }
  836. if (ImGui::ImageButton((void*)(uintptr_t)tool_scale_texture->handle.idx, ImVec2(16, 16)))
  837. {
  838. _tool_type = tool::ToolType::SCALE;
  839. tool_send_state();
  840. }
  841. ImGui::Separator();
  842. if (ImGui::ImageButton((void*)(uintptr_t)axis_local_texture->handle.idx, ImVec2(16, 16)))
  843. {
  844. _reference_system = tool::ReferenceSystem::LOCAL;
  845. tool_send_state();
  846. }
  847. if (ImGui::ImageButton((void*)(uintptr_t)axis_world_texture->handle.idx, ImVec2(16, 16)))
  848. {
  849. _reference_system = tool::ReferenceSystem::WORLD;
  850. tool_send_state();
  851. }
  852. ImGui::Separator();
  853. if (ImGui::ImageButton((void*)(uintptr_t)reference_world_texture->handle.idx, ImVec2(16, 16)))
  854. {
  855. _snap_mode = tool::SnapMode::RELATIVE;
  856. tool_send_state();
  857. }
  858. if (ImGui::ImageButton((void*)(uintptr_t)reference_local_texture->handle.idx, ImVec2(16, 16)))
  859. {
  860. _snap_mode = tool::SnapMode::ABSOLUTE;
  861. tool_send_state();
  862. }
  863. ImGui::Separator();
  864. if (ImGui::ImageButton((void*)(uintptr_t)snap_to_grid_texture->handle.idx, ImVec2(16, 16)))
  865. {
  866. _snap_to_grid = !_snap_to_grid;
  867. tool_send_state();
  868. }
  869. ImGui::EndGroup();
  870. // Draw scene view
  871. ImGui::SameLine();
  872. _scene_view.draw();
  873. }
  874. ImGui::EndDock();
  875. if (ImGui::BeginDock("Scene Tree", &_scene_tree._open))
  876. {
  877. _scene_tree.draw();
  878. }
  879. ImGui::EndDock();
  880. if (ImGui::BeginDock("Inspector", &_inspector._open))
  881. {
  882. _inspector.draw();
  883. }
  884. ImGui::EndDock();
  885. if (ImGui::BeginDock("Console", &_console._open, ImGuiWindowFlags_NoScrollbar))
  886. {
  887. console_draw(_console);
  888. }
  889. ImGui::EndDock();
  890. if (ImGui::BeginDock("Animator", &_animator._open))
  891. {
  892. _animator.draw();
  893. }
  894. ImGui::EndDock();
  895. // _sprite_importer.draw();
  896. imgui_end_frame();
  897. }
  898. void send_command(StringStream& ss)
  899. {
  900. TempAllocator4096 ta;
  901. StringStream out(ta);
  902. out << "{\"type\":\"script\",\"script\":\"";
  903. out << string_stream::c_str(ss);
  904. out << "\"}";
  905. const char* cmd = string_stream::c_str(out);
  906. const u32 size = strlen32(cmd);
  907. _console._client.write(&size, sizeof(u32));
  908. _console._client.write(cmd, size);
  909. }
  910. void tool_send_state()
  911. {
  912. TempAllocator256 ta;
  913. StringStream ss(ta);
  914. tool::set_grid_size(ss, _grid_size);
  915. tool::set_rotation_snap(ss, _rotation_snap);
  916. tool::enable_show_grid(ss, _show_grid);
  917. tool::enable_snap_to_grid(ss, _snap_to_grid);
  918. tool::enable_debug_render_world(ss, _debug_render_world);
  919. tool::enable_debug_physics_world(ss, _debug_physics_world);
  920. tool::set_tool_type(ss, _tool_type);
  921. tool::set_snap_mode(ss, _snap_mode);
  922. tool::set_reference_system(ss, _reference_system);
  923. send_command(ss);
  924. }
  925. void format_time(uint64_t time, char* str, size_t size)
  926. {
  927. #if CROWN_PLATFORM_WINDOWS
  928. // SYSTEMTIME st;
  929. // FileTimeToSystemTime(&time, &st);
  930. // sprintf(str, "%d/%d/%d %d:%d"
  931. // , st.wDay
  932. // , st.wMonth
  933. // , st.wYear
  934. // , st.wHour
  935. // , st.wMinute);
  936. #else
  937. struct tm lt;
  938. localtime_r((time_t*)&time, &lt);
  939. strftime(str, size, "%d/%m/%Y %H:%M", &lt);
  940. #endif
  941. }
  942. void main_menu_bar()
  943. {
  944. // Main Menu
  945. if (ImGui::BeginMainMenuBar())
  946. {
  947. if (ImGui::BeginMenu("File"))
  948. {
  949. if (ImGui::MenuItem("New"))
  950. {
  951. }
  952. if (ImGui::MenuItem("Open", "Ctrl+O"))
  953. {
  954. nfdchar_t *out_path = NULL;
  955. nfdresult_t result = NFD_OpenDialog(NULL, NULL, &out_path);
  956. if ( result == NFD_OKAY )
  957. {
  958. logi(LEVEL_EDITOR, "Success!");
  959. logi(LEVEL_EDITOR, out_path);
  960. free(out_path);
  961. }
  962. else if ( result == NFD_CANCEL )
  963. {
  964. logi(LEVEL_EDITOR, "User pressed cancel.");
  965. }
  966. else
  967. {
  968. loge(LEVEL_EDITOR, "Error: %s\n", NFD_GetError());
  969. }
  970. }
  971. if (ImGui::MenuItem("Save", "Ctrl+S"))
  972. {
  973. }
  974. if (ImGui::MenuItem("Save As..."))
  975. {
  976. }
  977. ImGui::Separator();
  978. if (ImGui::MenuItem("Quit", "Ctrl+Q", false, true))
  979. {
  980. TempAllocator64 ta;
  981. StringStream ss(ta);
  982. tool::device_quit(ss);
  983. send_command(ss);
  984. }
  985. ImGui::EndMenu();
  986. }
  987. if (ImGui::BeginMenu("Edit"))
  988. {
  989. if (ImGui::MenuItem("Undo", "Ctrl+Z")) {}
  990. if (ImGui::MenuItem("Redo", "Ctrl+Y")) {}
  991. ImGui::EndMenu();
  992. }
  993. if (ImGui::BeginMenu("Create"))
  994. {
  995. TempAllocator256 ta;
  996. StringStream ss(ta);
  997. if (ImGui::BeginMenu("Primitives"))
  998. {
  999. if (ImGui::MenuItem("Cube", NULL, false, true))
  1000. {
  1001. _tool_type = tool::ToolType::PLACE;
  1002. tool_send_state();
  1003. tool::set_placeable(ss, "unit", "core/units/primitives/cube");
  1004. send_command(ss);
  1005. }
  1006. if (ImGui::MenuItem("Sphere"))
  1007. {
  1008. _tool_type = tool::ToolType::PLACE;
  1009. tool_send_state();
  1010. tool::set_placeable(ss, "unit", "core/units/primitives/sphere");
  1011. send_command(ss);
  1012. }
  1013. if (ImGui::MenuItem("Cone"))
  1014. {
  1015. _tool_type = tool::ToolType::PLACE;
  1016. tool_send_state();
  1017. tool::set_placeable(ss, "unit", "core/units/primitives/cone");
  1018. send_command(ss);
  1019. }
  1020. if (ImGui::MenuItem("Cylinder"))
  1021. {
  1022. _tool_type = tool::ToolType::PLACE;
  1023. tool_send_state();
  1024. tool::set_placeable(ss, "unit", "core/units/primitives/cylinder");
  1025. send_command(ss);
  1026. }
  1027. if (ImGui::MenuItem("Plane"))
  1028. {
  1029. _tool_type = tool::ToolType::PLACE;
  1030. tool_send_state();
  1031. tool::set_placeable(ss, "unit", "core/units/primitives/plane");
  1032. send_command(ss);
  1033. }
  1034. ImGui::EndMenu();
  1035. }
  1036. if (ImGui::MenuItem("Camera"))
  1037. {
  1038. _tool_type = tool::ToolType::PLACE;
  1039. tool_send_state();
  1040. tool::set_placeable(ss, "unit", "core/units/camera");
  1041. send_command(ss);
  1042. }
  1043. if (ImGui::MenuItem("Light"))
  1044. {
  1045. _tool_type = tool::ToolType::PLACE;
  1046. tool_send_state();
  1047. tool::set_placeable(ss, "unit", "core/units/light");
  1048. send_command(ss);
  1049. }
  1050. if (ImGui::MenuItem("Sound"))
  1051. {
  1052. _tool_type = tool::ToolType::PLACE;
  1053. tool_send_state();
  1054. tool::set_placeable(ss, "sound", "core/units/camera");
  1055. send_command(ss);
  1056. }
  1057. ImGui::EndMenu();
  1058. }
  1059. if (ImGui::BeginMenu("Scene View"))
  1060. {
  1061. TempAllocator256 ta;
  1062. StringStream ss(ta);
  1063. if (ImGui::BeginMenu("Camera View"))
  1064. {
  1065. if (ImGui::MenuItem("Perspective"))
  1066. {
  1067. tool::camera_view_perspective(ss);
  1068. send_command(ss);
  1069. }
  1070. if (ImGui::MenuItem("Front"))
  1071. {
  1072. tool::camera_view_front(ss);
  1073. send_command(ss);
  1074. }
  1075. if (ImGui::MenuItem("Back"))
  1076. {
  1077. tool::camera_view_back(ss);
  1078. send_command(ss);
  1079. }
  1080. if (ImGui::MenuItem("Right"))
  1081. {
  1082. tool::camera_view_right(ss);
  1083. send_command(ss);
  1084. }
  1085. if (ImGui::MenuItem("Left"))
  1086. {
  1087. tool::camera_view_left(ss);
  1088. send_command(ss);
  1089. }
  1090. if (ImGui::MenuItem("Top"))
  1091. {
  1092. tool::camera_view_top(ss);
  1093. send_command(ss);
  1094. }
  1095. if (ImGui::MenuItem("Bottom"))
  1096. {
  1097. tool::camera_view_bottom(ss);
  1098. send_command(ss);
  1099. }
  1100. ImGui::EndMenu();
  1101. }
  1102. ImGui::Separator();
  1103. if (ImGui::MenuItem("Show Grid", NULL, _show_grid))
  1104. {
  1105. _show_grid = !_show_grid;
  1106. tool_send_state();
  1107. }
  1108. if (ImGui::SliderFloat("Grid Size", &_grid_size, 0.1f, 5.0f))
  1109. {
  1110. tool_send_state();
  1111. }
  1112. if (ImGui::SliderFloat("Snap Rot", &_rotation_snap, 1, 180))
  1113. {
  1114. tool_send_state();
  1115. }
  1116. ImGui::EndMenu();
  1117. }
  1118. if (ImGui::BeginMenu("Windows"))
  1119. {
  1120. if (ImGui::MenuItem("Scene"))
  1121. {
  1122. _scene_view._open = true;
  1123. }
  1124. if (ImGui::MenuItem("Scene Tree"))
  1125. {
  1126. _scene_tree._open = true;
  1127. }
  1128. if (ImGui::MenuItem("Inspector"))
  1129. {
  1130. _inspector._open = true;
  1131. }
  1132. if (ImGui::MenuItem("Console"))
  1133. {
  1134. _console._open = true;
  1135. }
  1136. if (ImGui::MenuItem("Animator"))
  1137. {
  1138. _animator._open = true;
  1139. }
  1140. ImGui::EndMenu();
  1141. }
  1142. if (ImGui::BeginMenu("Help"))
  1143. {
  1144. ImGui::MenuItem("About", "");
  1145. ImGui::EndMenu();
  1146. }
  1147. _main_menu_pos = ImGui::GetWindowPos();
  1148. _main_menu_size = ImGui::GetWindowSize();
  1149. ImGui::EndMainMenuBar();
  1150. }
  1151. }
  1152. };
  1153. LevelEditor* s_editor;
  1154. void tool_init()
  1155. {
  1156. const DeviceOptions& opt = device()->_device_options;
  1157. s_editor = CE_NEW(default_allocator(), LevelEditor)(opt._source_dir);
  1158. }
  1159. void tool_update(f32 dt)
  1160. {
  1161. s_editor->update(dt);
  1162. }
  1163. void tool_shutdown()
  1164. {
  1165. CE_DELETE(default_allocator(), s_editor);
  1166. }
  1167. extern bool next_event(OsEvent& ev);
  1168. bool tool_process_events()
  1169. {
  1170. ImGuiIO& io = ImGui::GetIO();
  1171. bool exit = false;
  1172. bool reset = false;
  1173. TempAllocator4096 ta;
  1174. StringStream ss(ta);
  1175. OsEvent event;
  1176. while (next_event(event))
  1177. {
  1178. if (event.type == OsEventType::NONE)
  1179. continue;
  1180. switch (event.type)
  1181. {
  1182. case OsEventType::BUTTON:
  1183. switch (event.button.device_id)
  1184. {
  1185. case crown::InputDeviceType::KEYBOARD:
  1186. io.KeyCtrl = ((event.button.button_num == crown::KeyboardButton::CTRL_LEFT)
  1187. || (event.button.button_num == crown::KeyboardButton::CTRL_RIGHT)) && event.button.pressed;
  1188. io.KeyShift = ((event.button.button_num == crown::KeyboardButton::SHIFT_LEFT)
  1189. || (event.button.button_num == crown::KeyboardButton::SHIFT_RIGHT)) && event.button.pressed;
  1190. io.KeyAlt = ((event.button.button_num == crown::KeyboardButton::ALT_LEFT)
  1191. || (event.button.button_num == crown::KeyboardButton::ALT_RIGHT)) && event.button.pressed;
  1192. io.KeySuper = ((event.button.button_num == crown::KeyboardButton::SUPER_LEFT)
  1193. || (event.button.button_num == crown::KeyboardButton::SUPER_RIGHT)) && event.button.pressed;
  1194. io.KeysDown[event.button.button_num] = event.button.pressed;
  1195. if (!io.WantCaptureKeyboard)
  1196. {
  1197. if (event.button.pressed)
  1198. {
  1199. if (event.button.button_num == crown::KeyboardButton::W)
  1200. tool::keyboard_pressed(ss, 'w');
  1201. if (event.button.button_num == crown::KeyboardButton::A)
  1202. tool::keyboard_pressed(ss, 'a');
  1203. if (event.button.button_num == crown::KeyboardButton::S)
  1204. tool::keyboard_pressed(ss, 's');
  1205. if (event.button.button_num == crown::KeyboardButton::D)
  1206. tool::keyboard_pressed(ss, 'd');
  1207. }
  1208. else
  1209. {
  1210. if (event.button.button_num == crown::KeyboardButton::W)
  1211. tool::keyboard_released(ss, 'w');
  1212. if (event.button.button_num == crown::KeyboardButton::A)
  1213. tool::keyboard_released(ss, 'a');
  1214. if (event.button.button_num == crown::KeyboardButton::S)
  1215. tool::keyboard_released(ss, 's');
  1216. if (event.button.button_num == crown::KeyboardButton::D)
  1217. tool::keyboard_released(ss, 'd');
  1218. }
  1219. }
  1220. break;
  1221. case crown::InputDeviceType::MOUSE:
  1222. io.MouseDown[0] = (event.button.button_num == crown::MouseButton::LEFT) && event.button.pressed;
  1223. io.MouseDown[1] = (event.button.button_num == crown::MouseButton::RIGHT) && event.button.pressed;
  1224. io.MouseDown[2] = (event.button.button_num == crown::MouseButton::MIDDLE) && event.button.pressed;
  1225. if (!io.WantCaptureMouse)
  1226. {
  1227. ImVec2& mouse_curr = s_editor->_scene_view._mouse;
  1228. mouse_curr.x = io.MousePos.x - s_editor->_scene_view._origin.x;
  1229. mouse_curr.y = io.MousePos.y - s_editor->_scene_view._origin.y;
  1230. tool::set_mouse_state(ss
  1231. , mouse_curr.x
  1232. , mouse_curr.y
  1233. , io.MouseDown[0]
  1234. , io.MouseDown[2]
  1235. , io.MouseDown[1]
  1236. );
  1237. if (event.button.button_num == crown::MouseButton::LEFT)
  1238. {
  1239. if (event.button.pressed)
  1240. tool::mouse_down(ss, mouse_curr.x, mouse_curr.y);
  1241. else
  1242. tool::mouse_up(ss, mouse_curr.x, mouse_curr.y);
  1243. }
  1244. }
  1245. break;
  1246. }
  1247. break;
  1248. case OsEventType::AXIS:
  1249. switch(event.axis.device_id)
  1250. {
  1251. case InputDeviceType::MOUSE:
  1252. switch(event.axis.axis_num)
  1253. {
  1254. case crown::MouseAxis::CURSOR:
  1255. io.MousePos = ImVec2(event.axis.axis_x, event.axis.axis_y);
  1256. if (!io.WantCaptureMouse)
  1257. {
  1258. ImVec2& mouse_curr = s_editor->_scene_view._mouse;
  1259. ImVec2& mouse_last = s_editor->_scene_view._mouse_last;
  1260. mouse_curr.x = io.MousePos.x - s_editor->_scene_view._origin.x;
  1261. mouse_curr.y = io.MousePos.y - s_editor->_scene_view._origin.y;
  1262. f32 delta_x = mouse_curr.x - mouse_last.x;
  1263. f32 delta_y = mouse_curr.y - mouse_last.y;
  1264. tool::mouse_move(ss, mouse_curr.x, mouse_curr.y, delta_x, delta_y);
  1265. mouse_last = mouse_curr;
  1266. }
  1267. break;
  1268. case crown::MouseAxis::WHEEL:
  1269. io.MouseWheel += event.axis.axis_y;
  1270. if (!io.WantCaptureMouse)
  1271. tool::mouse_wheel(ss, io.MouseWheel);
  1272. break;
  1273. }
  1274. }
  1275. break;
  1276. case OsEventType::TEXT:
  1277. io.AddInputCharactersUTF8((const char*) event.text.utf8);
  1278. break;
  1279. case OsEventType::RESOLUTION:
  1280. _width = event.resolution.width;
  1281. _height = event.resolution.height;
  1282. reset = true;
  1283. break;
  1284. case OsEventType::EXIT:
  1285. exit = true;
  1286. break;
  1287. default:
  1288. break;
  1289. }
  1290. }
  1291. s_editor->send_command(ss);
  1292. bool vsync = true;
  1293. if (reset)
  1294. bgfx::reset(_width, _height, (vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE));
  1295. return exit;
  1296. }
  1297. } // namespace crown
  1298. #endif // CROWN_TOOLS