yaze 0.2.0
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
asset_browser.cc
Go to the documentation of this file.
1#include "asset_browser.h"
2
3#include "absl/strings/str_format.h"
4
5namespace yaze {
6namespace app {
7namespace gui {
8
9using namespace ImGui;
10
11const ImGuiTableSortSpecs* AssetObject::s_current_sort_specs = NULL;
12
14 const std::array<gfx::Bitmap, kNumGfxSheets>& bmp_manager) {
15 PushItemWidth(GetFontSize() * 10);
16 SeparatorText("Contents");
17 Checkbox("Show Type Overlay", &ShowTypeOverlay);
18 SameLine();
19 Checkbox("Allow Sorting", &AllowSorting);
20 SameLine();
21 Checkbox("Stretch Spacing", &StretchSpacing);
22 SameLine();
23 Checkbox("Allow dragging unselected item", &AllowDragUnselected);
24 SameLine();
25 Checkbox("Allow box-selection", &AllowBoxSelect);
26 SameLine();
27 SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f");
28 SameLine();
29 SliderInt("Icon Spacing", &IconSpacing, 0, 32);
30 SameLine();
31 SliderInt("Icon Hit Spacing", &IconHitSpacing, 0, 32);
32 PopItemWidth();
33
34 // Filter by types
35 static bool filter_type[4] = {true, true, true, true};
36 Text("Filter by type:");
37 SameLine();
38 Checkbox("Unsorted", &filter_type[0]);
39 SameLine();
40 Checkbox("Dungeon", &filter_type[1]);
41 SameLine();
42 Checkbox("Overworld", &filter_type[2]);
43 SameLine();
44 Checkbox("Sprite", &filter_type[3]);
45
46 // Show a table with ONLY one header row to showcase the idea/possibility of
47 // using this to provide a sorting UI
48 if (AllowSorting) {
49 PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
50 ImGuiTableFlags table_flags_for_sort_specs =
51 ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti |
52 ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders;
53 if (BeginTable("for_sort_specs_only", 2, table_flags_for_sort_specs,
54 ImVec2(0.0f, GetFrameHeight()))) {
55 TableSetupColumn("Index");
56 TableSetupColumn("Type");
57 TableHeadersRow();
58 if (ImGuiTableSortSpecs* sort_specs = TableGetSortSpecs())
59 if (sort_specs->SpecsDirty || RequestSort) {
60 AssetObject::SortWithSortSpecs(sort_specs, Items.Data, Items.Size);
61 sort_specs->SpecsDirty = RequestSort = false;
62 }
63 EndTable();
64 }
65 PopStyleVar();
66 }
67
68 ImGuiIO& io = GetIO();
69 SetNextWindowContentSize(ImVec2(
70 0.0f, LayoutOuterPadding +
72 if (BeginChild("Assets", ImVec2(0.0f, -GetTextLineHeightWithSpacing()),
73 ImGuiChildFlags_Border, ImGuiWindowFlags_NoMove)) {
74 ImDrawList* draw_list = GetWindowDrawList();
75
76 const float avail_width = GetContentRegionAvail().x;
77 UpdateLayoutSizes(avail_width);
78
79 // Calculate and store start position.
80 ImVec2 start_pos = GetCursorScreenPos();
81 start_pos = ImVec2(start_pos.x + LayoutOuterPadding,
82 start_pos.y + LayoutOuterPadding);
83 SetCursorScreenPos(start_pos);
84
85 // Multi-select
86 ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape |
87 ImGuiMultiSelectFlags_ClearOnClickVoid;
88
89 // - Enable box-select (in 2D mode, so that changing box-select rectangle
90 // X1/X2 boundaries will affect clipped items)
91 if (AllowBoxSelect) ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d;
92
93 // - This feature allows dragging an unselected item without selecting it
94 // (rarely used)
96 ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease;
97
98 // - Enable keyboard wrapping on X axis
99 // (FIXME-MULTISELECT: We haven't designed/exposed a general nav wrapping
100 // api yet, so this flag is provided as a courtesy to avoid doing:
101 // NavMoveRequestTryWrapping(GetCurrentWindow(),
102 // ImGuiNavMoveFlags_WrapX);
103 // When we finish implementing a more general API for this, we will
104 // obsolete this flag in favor of the new system)
105 ms_flags |= ImGuiMultiSelectFlags_NavWrapX;
106
107 ImGuiMultiSelectIO* ms_io =
108 BeginMultiSelect(ms_flags, Selection.Size, Items.Size);
109
110 // Use custom selection adapter: store ID in selection (recommended)
111 Selection.UserData = this;
112 Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_,
113 int idx) {
114 GfxSheetAssetBrowser* self = (GfxSheetAssetBrowser*)self_->UserData;
115 return self->Items[idx].ID;
116 };
117 Selection.ApplyRequests(ms_io);
118
119 const bool want_delete =
120 (Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) &&
121 (Selection.Size > 0)) ||
123 const int item_curr_idx_to_focus =
124 want_delete ? Selection.ApplyDeletionPreLoop(ms_io, Items.Size) : -1;
125 RequestDelete = false;
126
127 // Push LayoutSelectableSpacing (which is LayoutItemSpacing minus
128 // hit-spacing, if we decide to have hit gaps between items) Altering
129 // style ItemSpacing may seem unnecessary as we position every items using
130 // SetCursorScreenPos()... But it is necessary for two reasons:
131 // - Selectables uses it by default to visually fill the space between two
132 // items.
133 // - The vertical spacing would be measured by Clipper to calculate line
134 // height if we didn't provide it explicitly (here we do).
135 PushStyleVar(ImGuiStyleVar_ItemSpacing,
137
138 // Rendering parameters
139 const ImU32 icon_type_overlay_colors[5] = {
140 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255),
141 IM_COL32(70, 70, 200, 255), IM_COL32(200, 200, 200, 255)};
142 const ImU32 icon_bg_color = GetColorU32(ImGuiCol_MenuBarBg);
143 const ImVec2 icon_type_overlay_size = ImVec2(5.0f, 5.0f);
144 const bool display_label = (LayoutItemSize.x >= CalcTextSize("999").x);
145
146 const int column_count = LayoutColumnCount;
147 ImGuiListClipper clipper;
148 clipper.Begin(LayoutLineCount, LayoutItemStep.y);
149
150 // Ensure focused item line is not clipped.
151 if (item_curr_idx_to_focus != -1)
152 clipper.IncludeItemByIndex(item_curr_idx_to_focus / column_count);
153
154 // Ensure RangeSrc item line is not clipped.
155 if (ms_io->RangeSrcItem != -1)
156 clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem / column_count);
157
158 while (clipper.Step()) {
159 for (int line_idx = clipper.DisplayStart; line_idx < clipper.DisplayEnd;
160 line_idx++) {
161 const int item_min_idx_for_current_line = line_idx * column_count;
162 const int item_max_idx_for_current_line =
163 IM_MIN((line_idx + 1) * column_count, Items.Size);
164 for (int item_idx = item_min_idx_for_current_line;
165 item_idx < item_max_idx_for_current_line; ++item_idx) {
166 AssetObject* item_data = &Items[item_idx];
167 PushID((int)item_data->ID);
168
169 // Position item
170 ImVec2 pos =
171 ImVec2(start_pos.x + (item_idx % column_count) * LayoutItemStep.x,
172 start_pos.y + line_idx * LayoutItemStep.y);
173 SetCursorScreenPos(pos);
174
175 SetNextItemSelectionUserData(item_idx);
176 bool item_is_selected = Selection.Contains((ImGuiID)item_data->ID);
177 bool item_is_visible = IsRectVisible(LayoutItemSize);
178 Selectable("", item_is_selected, ImGuiSelectableFlags_None,
180
181 // Update our selection state immediately (without waiting for
182 // EndMultiSelect() requests) because we use this to alter the color
183 // of our text/icon.
184 if (IsItemToggledSelection()) item_is_selected = !item_is_selected;
185
186 // Focus (for after deletion)
187 if (item_curr_idx_to_focus == item_idx) SetKeyboardFocusHere(-1);
188
189 // Drag and drop
190 if (BeginDragDropSource()) {
191 // Create payload with full selection OR single unselected item.
192 // (the later is only possible when using
193 // ImGuiMultiSelectFlags_SelectOnClickRelease)
194 if (GetDragDropPayload() == NULL) {
195 ImVector<ImGuiID> payload_items;
196 void* it = NULL;
197 ImGuiID id = 0;
198 if (!item_is_selected)
199 payload_items.push_back(item_data->ID);
200 else
201 while (Selection.GetNextSelectedItem(&it, &id))
202 payload_items.push_back(id);
203 SetDragDropPayload("ASSETS_BROWSER_ITEMS", payload_items.Data,
204 (size_t)payload_items.size_in_bytes());
205 }
206
207 // Display payload content in tooltip, by extracting it from the
208 // payload data (we could read from selection, but it is more
209 // correct and reusable to read from payload)
210 const ImGuiPayload* payload = GetDragDropPayload();
211 const int payload_count =
212 (int)payload->DataSize / (int)sizeof(ImGuiID);
213 Text("%d assets", payload_count);
214
215 EndDragDropSource();
216 }
217
218 // Render icon (a real app would likely display an image/thumbnail
219 // here) Because we use ImGuiMultiSelectFlags_BoxSelect2d, clipping
220 // vertical may occasionally be larger, so we coarse-clip our
221 // rendering as well.
222 if (item_is_visible) {
223 ImVec2 box_min(pos.x - 1, pos.y - 1);
224 ImVec2 box_max(box_min.x + LayoutItemSize.x + 2,
225 box_min.y + LayoutItemSize.y + 2); // Dubious
226 draw_list->AddRectFilled(box_min, box_max,
227 icon_bg_color); // Background color
228
229 if (display_label) {
230 ImU32 label_col = GetColorU32(
231 item_is_selected ? ImGuiCol_Text : ImGuiCol_TextDisabled);
232 draw_list->AddImage((void*)bmp_manager[item_data->ID].texture(),
233 box_min, box_max, ImVec2(0, 0), ImVec2(1, 1),
234 GetColorU32(ImVec4(1, 1, 1, 1)));
235 draw_list->AddText(ImVec2(box_min.x, box_max.y - GetFontSize()),
236 label_col,
237 absl::StrFormat("%X", item_data->ID).c_str());
238 }
239 if (ShowTypeOverlay && item_data->Type != 0) {
240 ImU32 type_col = icon_type_overlay_colors
241 [item_data->Type % IM_ARRAYSIZE(icon_type_overlay_colors)];
242 draw_list->AddRectFilled(
243 ImVec2(box_max.x - 2 - icon_type_overlay_size.x,
244 box_min.y + 2),
245 ImVec2(box_max.x - 2,
246 box_min.y + 2 + icon_type_overlay_size.y),
247 type_col);
248 }
249 }
250
251 PopID();
252 }
253 }
254 }
255 clipper.End();
256 PopStyleVar(); // ImGuiStyleVar_ItemSpacing
257
258 // Context menu
259 if (BeginPopupContextWindow()) {
260 Text("Selection: %d items", Selection.Size);
261 Separator();
262 if (BeginMenu("Set Type")) {
263 if (MenuItem("Unsorted")) {
264 void* it = NULL;
265 ImGuiID id = 0;
266 while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 0;
267 }
268 if (MenuItem("Dungeon")) {
269 void* it = NULL;
270 ImGuiID id = 0;
271 while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 1;
272 }
273 if (MenuItem("Overworld")) {
274 void* it = NULL;
275 ImGuiID id = 0;
276 while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 2;
277 }
278 if (MenuItem("Sprite")) {
279 void* it = NULL;
280 ImGuiID id = 0;
281 while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 3;
282 }
283 EndMenu();
284 }
285 Separator();
286 if (MenuItem("Delete", "Del", false, Selection.Size > 0))
287 RequestDelete = true;
288 EndPopup();
289 }
290
291 ms_io = EndMultiSelect();
292 Selection.ApplyRequests(ms_io);
293 if (want_delete)
294 Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus);
295
296 // Zooming with CTRL+Wheel
297 if (IsWindowAppearing()) ZoomWheelAccum = 0.0f;
298 if (IsWindowHovered() && io.MouseWheel != 0.0f &&
299 IsKeyDown(ImGuiMod_Ctrl) && IsAnyItemActive() == false) {
300 ZoomWheelAccum += io.MouseWheel;
301 if (fabsf(ZoomWheelAccum) >= 1.0f) {
302 // Calculate hovered item index from mouse location
303 // FIXME: Locking aiming on 'hovered_item_idx' (with a cool-down
304 // timer) would ensure zoom keeps on it.
305 const float hovered_item_nx =
306 (io.MousePos.x - start_pos.x + LayoutItemSpacing * 0.5f) /
308 const float hovered_item_ny =
309 (io.MousePos.y - start_pos.y + LayoutItemSpacing * 0.5f) /
311 const int hovered_item_idx =
312 ((int)hovered_item_ny * LayoutColumnCount) + (int)hovered_item_nx;
313 // SetTooltip("%f,%f -> item %d", hovered_item_nx,
314 // hovered_item_ny, hovered_item_idx); // Move those 4 lines in block
315 // above for easy debugging
316
317 // Zoom
318 IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum);
319 IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f);
321 UpdateLayoutSizes(avail_width);
322
323 // Manipulate scroll to that we will land at the same Y location of
324 // currently hovered item.
325 // - Calculate next frame position of item under mouse
326 // - Set new scroll position to be used in next BeginChild()
327 // call.
328 float hovered_item_rel_pos_y =
329 ((float)(hovered_item_idx / LayoutColumnCount) +
330 fmodf(hovered_item_ny, 1.0f)) *
332 hovered_item_rel_pos_y += GetStyle().WindowPadding.y;
333 float mouse_local_y = io.MousePos.y - GetWindowPos().y;
334 SetScrollY(hovered_item_rel_pos_y - mouse_local_y);
335 }
336 }
337 }
338 EndChild();
339
340 Text("Selected: %d/%d items", Selection.Size, Items.Size);
341}
342
343} // namespace gui
344} // namespace app
345} // namespace yaze
#define IM_CLAMP(V, MN, MX)
#define IM_MIN(A, B)
Definition input.cc:17
Definition common.cc:21
static const ImGuiTableSortSpecs * s_current_sort_specs
static void SortWithSortSpecs(ImGuiTableSortSpecs *sort_specs, AssetObject *items, int items_count)
void ApplyDeletionPostLoop(ImGuiMultiSelectIO *ms_io, ImVector< ITEM_TYPE > &items, int item_curr_idx_to_select)
int ApplyDeletionPreLoop(ImGuiMultiSelectIO *ms_io, int items_count)
void Draw(const std::array< gfx::Bitmap, kNumGfxSheets > &bmp_manager)
ExampleSelectionWithDeletion Selection
void UpdateLayoutSizes(float avail_width)