yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
dungeon_object_interaction.cc
Go to the documentation of this file.
1// Related header
3#include "absl/strings/str_format.h"
5
6// C++ standard library headers
7#include <algorithm>
8#include <cmath>
9
10// Third-party library headers
11#include "imgui/imgui.h"
12
13// Project headers
18#include "app/gui/core/icons.h"
20#include "core/features.h"
23
24namespace yaze::editor {
25
26namespace {
27
28constexpr int kRoomPixelMax = 511;
29
30uint16_t EncodePotItemPosition(int pixel_x, int pixel_y) {
31 const int clamped_x = std::clamp(pixel_x, 0, kRoomPixelMax);
32 const int clamped_y = std::clamp(pixel_y, 0, kRoomPixelMax);
33 const int encoded_x = std::clamp(clamped_x / 4, 0, 255);
34 const int encoded_y = std::clamp(clamped_y / 16, 0, 255);
35 return static_cast<uint16_t>((encoded_y << 8) | encoded_x);
36}
37
38} // namespace
39
41 const ImGuiIO& io = ImGui::GetIO();
42 const bool hovered = canvas_->IsMouseHovering();
43 const bool mouse_left_down = ImGui::IsMouseDown(ImGuiMouseButton_Left);
44 const bool mouse_left_released =
45 ImGui::IsMouseReleased(ImGuiMouseButton_Left);
46
47 // Keep processing drag/release if an interaction started on the canvas but
48 // the cursor left the bounds before the mouse button was released.
49 const bool has_active_marquee = selection_.IsRectangleSelectionActive();
50 const bool should_process_without_hover =
51 has_active_marquee ||
54 (mouse_left_down || mouse_left_released)) ||
55 mouse_left_released;
56
57 if (!hovered && !should_process_without_hover) {
58 return;
59 }
60
61 const ImVec2 canvas_mouse_pos =
63 const int canvas_mouse_x = static_cast<int>(std::floor(canvas_mouse_pos.x));
64 const int canvas_mouse_y = static_cast<int>(std::floor(canvas_mouse_pos.y));
65 const bool pointer_within_room =
66 dungeon_coords::IsWithinBounds(canvas_mouse_x, canvas_mouse_y);
67
68 // Handle Escape key to cancel any active placement mode
69 if (ImGui::IsKeyPressed(ImGuiKey_Escape) &&
72 return;
73 }
74
75 if (hovered) {
76 if (pointer_within_room &&
78 return;
79 }
81 if (HandleKeyboardNudge()) {
82 return;
83 }
84 }
85
86 // Painting modes are exclusive; don't also select/drag/mutate entities.
87 if (hovered && mouse_left_down) {
88 const auto mode = mode_manager_.GetMode();
90 if (pointer_within_room) {
91 UpdateCollisionPainting(canvas_mouse_pos);
92 }
93 return;
94 }
96 if (pointer_within_room) {
97 UpdateWaterFillPainting(canvas_mouse_pos);
98 }
99 return;
100 }
101 }
102
103 if (hovered && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
104 HandleLeftClick(canvas_mouse_pos);
105 }
106
107 // Dispatch drag to coordinator (handlers gate internally via drag state).
108 if (ImGui::IsMouseDragging(ImGuiMouseButton_Left)) {
109 entity_coordinator_.HandleDrag(canvas_mouse_pos, io.MouseDelta);
110 }
111
112 // Handle mouse release - complete drag operation
113 if (mouse_left_released) {
115 }
116}
117
118void DungeonObjectInteraction::HandleLeftClick(const ImVec2& canvas_mouse_pos) {
119 int canvas_x = static_cast<int>(std::floor(canvas_mouse_pos.x));
120 int canvas_y = static_cast<int>(std::floor(canvas_mouse_pos.y));
121
122 // Try to handle click via entity coordinator (handles placement, entity selection, and object selection)
123 if (entity_coordinator_.HandleClick(canvas_x, canvas_y)) {
124 // If a selected room element was clicked, prime drag state. Plain clicks on
125 // selected mixed members preserve the whole selection; movement begins only
126 // if the mouse actually drags.
129 HandleObjectSelectionStart(canvas_mouse_pos);
130 }
131 return;
132 }
133
134 // The canvas viewport can contain blank space after panning. Overlay clicks
135 // are dispatched above, but blank space outside the translated room must not
136 // clear selection or start a marquee.
137 if (!dungeon_coords::IsWithinBounds(canvas_x, canvas_y)) {
138 return;
139 }
140
141 // Not an entity click or placement; handle empty space
142 HandleEmptySpaceClick(canvas_mouse_pos);
143}
144
146 const ImVec2& canvas_mouse_pos) {
147 auto [room_x, room_y] =
148 CanvasToRoomCoordinates(static_cast<int>(canvas_mouse_pos.x),
149 static_cast<int>(canvas_mouse_pos.y));
150 if (rooms_ && current_room_id_ >= 0 && current_room_id_ < 296) {
151 auto& room = (*rooms_)[current_room_id_];
152 auto& state = mode_manager_.GetModeState();
153
154 // Only set for valid interior tiles (0-63)
155 if (room_x >= 0 && room_x < 64 && room_y >= 0 && room_y < 64) {
156 // Start a paint stroke (single undo snapshot per stroke).
157 if (!state.is_painting) {
158 state.is_painting = true;
159 state.paint_mutation_started = false;
160 state.paint_last_tile_x = room_x;
161 state.paint_last_tile_y = room_y;
162 }
163
164 const int x0 =
165 (state.paint_last_tile_x >= 0) ? state.paint_last_tile_x : room_x;
166 const int y0 =
167 (state.paint_last_tile_y >= 0) ? state.paint_last_tile_y : room_y;
168
169 bool changed = false;
170 auto ensure_mutation = [&]() {
171 if (!state.paint_mutation_started) {
173 state.paint_mutation_started = true;
174 }
175 };
176
178 x0, y0, room_x, room_y, [&](int lx, int ly) {
180 lx, ly, state.paint_brush_radius,
181 /*min_x=*/0, /*min_y=*/0, /*max_x=*/63, /*max_y=*/63,
182 [&](int bx, int by) {
183 if (room.GetCollisionTile(bx, by) ==
184 state.paint_collision_value) {
185 return;
186 }
187 ensure_mutation();
188 room.SetCollisionTile(bx, by, state.paint_collision_value);
189 changed = true;
190 });
191 });
192
193 if (changed) {
196 }
197
198 state.paint_last_tile_x = room_x;
199 state.paint_last_tile_y = room_y;
200 }
201 }
202}
203
204void DungeonObjectInteraction::UpdateWaterFillPainting(
205 const ImVec2& canvas_mouse_pos) {
206 if (!core::FeatureFlags::get().dungeon.kSaveWaterFillZones) {
207 mode_manager_.SetMode(InteractionMode::Select);
208 return;
209 }
210
211 const ImGuiIO& io = ImGui::GetIO();
212 const bool erase = io.KeyAlt;
213
214 auto [room_x, room_y] =
215 CanvasToRoomCoordinates(static_cast<int>(canvas_mouse_pos.x),
216 static_cast<int>(canvas_mouse_pos.y));
217 if (rooms_ && current_room_id_ >= 0 && current_room_id_ < 296) {
218 auto& room = (*rooms_)[current_room_id_];
219 auto& state = mode_manager_.GetModeState();
220
221 // Only set for valid interior tiles (0-63)
222 if (room_x >= 0 && room_x < 64 && room_y >= 0 && room_y < 64) {
223 const bool new_val = !erase;
224 // Start a paint stroke (single undo snapshot per stroke).
225 if (!state.is_painting) {
226 state.is_painting = true;
227 state.paint_mutation_started = false;
228 state.paint_last_tile_x = room_x;
229 state.paint_last_tile_y = room_y;
230 }
231
232 const int x0 =
233 (state.paint_last_tile_x >= 0) ? state.paint_last_tile_x : room_x;
234 const int y0 =
235 (state.paint_last_tile_y >= 0) ? state.paint_last_tile_y : room_y;
236
237 bool changed = false;
238 auto ensure_mutation = [&]() {
239 if (!state.paint_mutation_started) {
240 interaction_context_.NotifyMutation(MutationDomain::kWaterFill);
241 state.paint_mutation_started = true;
242 }
243 };
244
245 paint_util::ForEachPointOnLine(
246 x0, y0, room_x, room_y, [&](int lx, int ly) {
247 paint_util::ForEachPointInSquareBrush(
248 lx, ly, state.paint_brush_radius,
249 /*min_x=*/0, /*min_y=*/0, /*max_x=*/63, /*max_y=*/63,
250 [&](int bx, int by) {
251 if (room.GetWaterFillTile(bx, by) == new_val) {
252 return;
253 }
254 ensure_mutation();
255 room.SetWaterFillTile(bx, by, new_val);
256 changed = true;
257 });
258 });
259
260 if (changed) {
261 interaction_context_.NotifyInvalidateCache(MutationDomain::kWaterFill);
262 }
263
264 state.paint_last_tile_x = room_x;
265 state.paint_last_tile_y = room_y;
266 }
267 }
268}
269
270void DungeonObjectInteraction::HandleObjectSelectionStart(
271 const ImVec2& canvas_mouse_pos) {
272 const bool has_object_selection = selection_.HasSelection();
273 const bool has_entity_selection = HasEntitySelection();
274 if (!has_object_selection && !has_entity_selection) {
275 return;
276 }
277
278 mode_manager_.SetMode(InteractionMode::DraggingObjects);
279 if (has_object_selection) {
280 entity_coordinator_.tile_handler().InitDrag(canvas_mouse_pos);
281 }
282 if (has_entity_selection) {
283 entity_coordinator_.BeginSelectionDrag(canvas_mouse_pos);
284 }
285}
286
287void DungeonObjectInteraction::HandleEmptySpaceClick(
288 const ImVec2& canvas_mouse_pos) {
289 const ImGuiIO& io = ImGui::GetIO();
290 const bool additive = io.KeyShift || io.KeyCtrl || io.KeySuper;
291 const bool had_selection =
292 selection_.HasSelection() || entity_coordinator_.HasEntitySelection();
293
294 // ZScream treats an empty click against an existing selection as a clear
295 // action. Rectangle selection starts from a clean canvas gesture.
296 if (!additive) {
297 ClearEntitySelection();
298 selection_.ClearSelection();
299 }
300
301 if (!had_selection) {
302 entity_coordinator_.tile_handler().BeginMarqueeSelection(canvas_mouse_pos);
303 }
304}
305
306void DungeonObjectInteraction::HandleMouseRelease() {
307 {
308 // End paint strokes on mouse release so a new left-drag creates a new undo
309 // snapshot. Keep the paint mode active (tool stays selected).
310 const auto mode = mode_manager_.GetMode();
311 if (mode == InteractionMode::PaintCollision ||
312 mode == InteractionMode::PaintWaterFill) {
313 auto& state = mode_manager_.GetModeState();
314 const bool had_mutation = state.paint_mutation_started;
315 state.is_painting = false;
316 state.paint_mutation_started = false;
317 state.paint_last_tile_x = -1;
318 state.paint_last_tile_y = -1;
319 // Emit a final invalidation after the stroke ends so domain-specific undo
320 // capture can finalize the action once we're no longer "painting".
321 if (had_mutation) {
322 interaction_context_.NotifyInvalidateCache(
323 (mode == InteractionMode::PaintCollision)
324 ? MutationDomain::kCustomCollision
325 : MutationDomain::kWaterFill);
326 }
327 }
328 }
329
330 if (mode_manager_.GetMode() == InteractionMode::DraggingObjects) {
331 mode_manager_.SetMode(InteractionMode::Select);
332 }
333 entity_coordinator_.HandleRelease();
334 // Marquee selection finalization is handled by TileObjectHandler via
335 // CheckForObjectSelection().
336}
337
338bool DungeonObjectInteraction::HandleKeyboardNudge() {
339 if (!rooms_ || current_room_id_ < 0 ||
340 current_room_id_ >= static_cast<int>(rooms_->size())) {
341 return false;
342 }
343
344 const ImGuiIO& io = ImGui::GetIO();
345 if (ImGui::IsAnyItemActive() || io.KeyCtrl || io.KeySuper || io.KeyAlt ||
346 ImGui::IsMouseDown(ImGuiMouseButton_Left) ||
347 entity_coordinator_.IsPlacementActive()) {
348 return false;
349 }
350
351 const auto mode = mode_manager_.GetMode();
352 if (mode == InteractionMode::DraggingObjects ||
353 mode == InteractionMode::PaintCollision ||
354 mode == InteractionMode::PaintWaterFill) {
355 return false;
356 }
357
358 int delta_x = 0;
359 int delta_y = 0;
360 if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow, true)) {
361 delta_x = -1;
362 } else if (ImGui::IsKeyPressed(ImGuiKey_RightArrow, true)) {
363 delta_x = 1;
364 }
365 if (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true)) {
366 delta_y = -1;
367 } else if (ImGui::IsKeyPressed(ImGuiKey_DownArrow, true)) {
368 delta_y = 1;
369 }
370
371 if (delta_x == 0 && delta_y == 0) {
372 return false;
373 }
374
375 return NudgeSelected(delta_x, delta_y);
376}
377
378bool DungeonObjectInteraction::NudgeSelected(int delta_x, int delta_y) {
379 if (!rooms_ || current_room_id_ < 0 ||
380 current_room_id_ >= static_cast<int>(rooms_->size())) {
381 return false;
382 }
383
384 bool handled = false;
385 if (selection_.HasSelection()) {
386 entity_coordinator_.tile_handler().MoveObjects(
387 current_room_id_, selection_.GetSelectedIndices(), delta_x, delta_y);
388 handled = true;
389 }
390
391 if (entity_coordinator_.HasEntitySelection()) {
392 handled = entity_coordinator_.NudgeSelected(delta_x, delta_y) || handled;
393 }
394
395 return handled;
396}
397
398void DungeonObjectInteraction::CheckForObjectSelection() {
399 // Draw/update active marquee selection for tile objects (delegated).
400 const ImGuiIO& io = ImGui::GetIO();
401 const ImVec2 mouse_pos = GetCanvasTransform().ScreenToRoomPixels(io.MousePos);
402 const bool mouse_left_released =
403 ImGui::IsMouseReleased(ImGuiMouseButton_Left);
404
405 if (mouse_left_released && selection_.IsRectangleSelectionActive()) {
406 selection_.UpdateRectangleSelection(static_cast<int>(mouse_pos.x),
407 static_cast<int>(mouse_pos.y));
408 constexpr int kMinRectPixels = 6;
409 if (!io.KeyAlt && selection_.IsRectangleLargeEnough(kMinRectPixels)) {
410 entity_coordinator_.SelectEntitiesInRect(
411 selection_.GetRectangleSelectionBounds(),
412 /*additive=*/false,
413 /*toggle=*/false);
414 }
415 }
416
417 entity_coordinator_.tile_handler().HandleMarqueeSelection(
418 mouse_pos,
419 /*mouse_left_down=*/ImGui::IsMouseDown(ImGuiMouseButton_Left),
420 /*mouse_left_released=*/mouse_left_released,
421 /*shift_down=*/io.KeyShift,
422 /*toggle_down=*/io.KeyCtrl || io.KeySuper,
423 /*alt_down=*/io.KeyAlt);
424}
425
426void DungeonObjectInteraction::DrawSelectionHighlights() {
427 if (!rooms_ || current_room_id_ < 0 || current_room_id_ >= 296)
428 return;
429
430 auto& room = (*rooms_)[current_room_id_];
431 const auto& objects = room.GetTileObjects();
432
433 // Use ObjectSelection's rendering (handles pulsing border, corner handles)
434 selection_.DrawSelectionHighlights(
435 canvas_, objects, [](const zelda3::RoomObject& obj) {
436 auto result = zelda3::DimensionService::Get().GetDimensions(obj);
437 return std::make_tuple(result.offset_x_tiles * 8,
438 result.offset_y_tiles * 8, result.width_pixels(),
439 result.height_pixels());
440 });
441
442 // Enhanced hover tooltip showing object info (always visible on hover)
443 // Skip completely in exclusive entity mode (door/sprite/item selected)
444 if (entity_coordinator_.HasEntitySelection()) {
445 return; // Entity mode active - no object tooltips or hover
446 }
447
448 if (canvas_->IsMouseHovering()) {
449 // Also skip tooltip if cursor is over a door/sprite/item entity (not selected yet)
450 ImGuiIO& io = ImGui::GetIO();
451 const auto [cursor_x, cursor_y] =
452 GetCanvasTransform().ScreenToRoomPixelCoordinates(io.MousePos);
453 auto entity_at_cursor =
454 entity_coordinator_.GetEntityAtPosition(cursor_x, cursor_y);
455 if (entity_at_cursor.has_value()) {
456 // Entity has priority - skip object tooltip, DrawHoverHighlight will also skip
457 DrawHoverHighlight(objects);
458 return;
459 }
460
461 auto hovered_index = entity_coordinator_.tile_handler().GetEntityAtPosition(
462 cursor_x, cursor_y);
463 if (hovered_index.has_value() && *hovered_index < objects.size()) {
464 const auto& object = objects[*hovered_index];
465 std::string object_name = zelda3::GetObjectName(object.id_);
466 int subtype = zelda3::GetObjectSubtype(object.id_);
467 const int layer = object.GetLayerValue();
468
469 // Get subtype name
470 const char* subtype_names[] = {"Unknown", "Type 1", "Type 2", "Type 3"};
471 const char* subtype_name =
472 (subtype >= 0 && subtype <= 3) ? subtype_names[subtype] : "Unknown";
473
474 // Build informative tooltip
475 std::string tooltip;
476 tooltip += object_name;
477 tooltip += " (" + std::string(subtype_name) + ")";
478 tooltip += "\n";
479 tooltip += "ID: 0x" + absl::StrFormat("%03X", object.id_);
480 if (zelda3::UsesRoomObjectStream(object)) {
481 static constexpr const char* kStreamNames[] = {"Primary", "BG2 overlay",
482 "BG1 overlay"};
483 const char* stream_name =
484 (layer >= 0 && layer < 3) ? kStreamNames[layer] : "Unknown";
485 tooltip += " | Object stream: " + std::string(stream_name);
486 } else {
487 const char* layer_name =
488 layer == 0 ? "Upper layer (BG1)" : "Lower layer (BG2)";
489 tooltip += " | Special layer: " + std::string(layer_name);
490 }
491 tooltip += " | Pos: (" + std::to_string(object.x_) + ", " +
492 std::to_string(object.y_) + ")";
493 tooltip += "\nSize: " + std::to_string(object.size_) + " (0x" +
494 absl::StrFormat("%02X", object.size_) + ")";
495
496 if (selection_.IsObjectSelected(*hovered_index)) {
497 tooltip += "\n" ICON_MD_MOUSE " Scroll wheel to resize";
498 tooltip += "\n" ICON_MD_DRAG_INDICATOR " Drag to move";
499 } else {
500 tooltip += "\n" ICON_MD_TOUCH_APP " Click to select";
501 }
502
503 ImGui::SetTooltip("%s", tooltip.c_str());
504 }
505 }
506
507 // Draw hover highlight for non-selected objects
508 DrawHoverHighlight(objects);
509}
510
511void DungeonObjectInteraction::DrawHoverHighlight(
512 const std::vector<zelda3::RoomObject>& objects) {
513 if (!canvas_->IsMouseHovering())
514 return;
515
516 // Skip all object hover in exclusive entity mode (door/sprite/item selected)
517 if (entity_coordinator_.HasEntitySelection())
518 return;
519
520 // Don't show object hover highlight if cursor is over a door/sprite/item entity
521 // Entities take priority over objects for interaction
522 ImGuiIO& io = ImGui::GetIO();
523 const DungeonCanvasTransform transform = GetCanvasTransform();
524 const auto [cursor_canvas_x, cursor_canvas_y] =
525 transform.ScreenToRoomPixelCoordinates(io.MousePos);
526 auto entity_at_cursor =
527 entity_coordinator_.GetEntityAtPosition(cursor_canvas_x, cursor_canvas_y);
528 if (entity_at_cursor.has_value()) {
529 return; // Entity has priority - skip object hover highlight
530 }
531
532 auto hovered_index = entity_coordinator_.tile_handler().GetEntityAtPosition(
533 cursor_canvas_x, cursor_canvas_y);
534 if (!hovered_index.has_value() || *hovered_index >= objects.size()) {
535 return;
536 }
537 const auto& object = objects[*hovered_index];
538
539 // Don't draw hover highlight if object is already selected
540 if (selection_.IsObjectSelected(*hovered_index)) {
541 return;
542 }
543
544 const auto& theme = AgentUI::GetTheme();
545 ImDrawList* draw_list = ImGui::GetWindowDrawList();
546 // Calculate object position and dimensions
547 auto [sel_x_px, sel_y_px, pixel_width, pixel_height] =
549
550 ImVec2 obj_start = transform.RoomPixelsToScreen(
551 ImVec2(static_cast<float>(sel_x_px), static_cast<float>(sel_y_px)));
552 const ImVec2 obj_size = transform.RoomSizeToScreen(ImVec2(
553 static_cast<float>(pixel_width), static_cast<float>(pixel_height)));
554 ImVec2 obj_end(obj_start.x + obj_size.x, obj_start.y + obj_size.y);
555
556 // Expand slightly for visibility
557 constexpr float margin = 2.0f;
558 obj_start.x -= margin;
559 obj_start.y -= margin;
560 obj_end.x += margin;
561 obj_end.y += margin;
562
563 // Draw subtle hover highlight with unified theme color
564 ImVec4 hover_fill = theme.selection_hover;
565 hover_fill.w *= 0.5f; // Make it more subtle for hover fill
566
567 ImVec4 hover_border = theme.selection_hover;
568
569 // Draw filled background for better visibility
570 draw_list->AddRectFilled(obj_start, obj_end, ImGui::GetColorU32(hover_fill));
571
572 // Draw dashed-style border (simulated with thinner line)
573 draw_list->AddRect(obj_start, obj_end, ImGui::GetColorU32(hover_border), 0.0f,
574 0, 1.5f);
575}
576
577void DungeonObjectInteraction::PlaceObjectAtPosition(int room_x, int room_y) {
578 entity_coordinator_.tile_handler().PlaceObjectAt(
579 current_room_id_, preview_object_, room_x, room_y);
580
581 if (object_placed_callback_) {
582 object_placed_callback_(preview_object_);
583 }
584
585 interaction_context_.NotifyInvalidateCache(MutationDomain::kTileObjects);
586 CancelPlacement();
587}
588
589std::pair<int, int> DungeonObjectInteraction::RoomToCanvasCoordinates(
590 int room_x, int room_y) const {
591 // Dungeon tiles are 8x8 pixels, convert room coordinates (tiles) to pixels
592 return {room_x * 8, room_y * 8};
593}
594
595std::pair<int, int> DungeonObjectInteraction::CanvasToRoomCoordinates(
596 int canvas_x, int canvas_y) const {
597 // Convert canvas pixels back to room coordinates (tiles)
598 return {canvas_x / 8, canvas_y / 8};
599}
600
601bool DungeonObjectInteraction::IsWithinCanvasBounds(int canvas_x, int canvas_y,
602 int margin) const {
603 return dungeon_coords::IsWithinBounds(canvas_x, canvas_y, margin);
604}
605
606void DungeonObjectInteraction::SetCurrentRoom(DungeonRoomStore* rooms,
607 int room_id) {
608 rooms_ = rooms;
609 current_room_id_ = room_id;
610 interaction_context_.rooms = rooms;
611 interaction_context_.current_room_id = room_id;
612 interaction_context_.selection = &selection_;
613 entity_coordinator_.SetContext(&interaction_context_);
614}
615
616void DungeonObjectInteraction::SetPreviewObject(
617 const zelda3::RoomObject& object, bool loaded) {
618 preview_object_ = object;
619
620 if (loaded && object.id_ >= 0) {
621 // Cancel other placement modes (doors/sprites/items) before entering object
622 // placement. We re-enable tile placement below.
623 entity_coordinator_.CancelPlacement();
624
625 // Enter object placement mode
626 mode_manager_.SetMode(InteractionMode::PlaceObject);
627 mode_manager_.GetModeState().preview_object = object;
628
629 // Ensure tile placement mode is active so ghost preview can render and
630 // clicks place the object.
631 auto& tile_handler = entity_coordinator_.tile_handler();
632 tile_handler.SetPreviewObject(preview_object_);
633 if (!tile_handler.IsPlacementActive()) {
634 tile_handler.BeginPlacement();
635 }
636 } else {
637 // Exit placement mode if not loaded
638 if (mode_manager_.GetMode() == InteractionMode::PlaceObject) {
639 CancelPlacement();
640 }
641 }
642}
643
644void DungeonObjectInteraction::ClearSelection() {
645 selection_.ClearSelection();
646 if (mode_manager_.GetMode() == InteractionMode::DraggingObjects) {
647 mode_manager_.SetMode(InteractionMode::Select);
648 }
649}
650
651void DungeonObjectInteraction::HandleDeleteSelected() {
652 auto indices = selection_.GetSelectedIndices();
653 if (!indices.empty()) {
654 entity_coordinator_.tile_handler().DeleteObjects(current_room_id_, indices);
655 selection_.ClearSelection();
656 }
657
658 if (entity_coordinator_.HasEntitySelection()) {
659 entity_coordinator_.DeleteSelectedEntity();
660 }
661}
662
663void DungeonObjectInteraction::HandleDeleteAllObjects() {
664 entity_coordinator_.tile_handler().DeleteAllObjects(current_room_id_);
665 selection_.ClearSelection();
666}
667
668void DungeonObjectInteraction::HandleCopySelected() {
669 if (!rooms_ || current_room_id_ < 0 ||
670 current_room_id_ >= static_cast<int>(rooms_->size())) {
671 return;
672 }
673
674 const auto selected_objects = selection_.GetSelectedIndices();
675 const bool has_object_selection = !selected_objects.empty();
676 const bool has_entity_selection = entity_coordinator_.HasEntitySelection();
677 if (!has_object_selection && !has_entity_selection) {
678 return;
679 }
680
681 entity_clipboard_.Clear();
682 bool clipboard_origin_set = false;
683
684 if (has_object_selection) {
685 entity_coordinator_.tile_handler().CopyObjectsToClipboard(current_room_id_,
686 selected_objects);
687 const auto& objects = (*rooms_)[current_room_id_].GetTileObjects();
688 for (size_t index : selected_objects) {
689 if (index >= objects.size()) {
690 continue;
691 }
692 entity_clipboard_.origin_tile_x = objects[index].x_;
693 entity_clipboard_.origin_tile_y = objects[index].y_;
694 entity_clipboard_.origin_pixel_x =
695 entity_clipboard_.origin_tile_x * dungeon_coords::kTileSize;
696 entity_clipboard_.origin_pixel_y =
697 entity_clipboard_.origin_tile_y * dungeon_coords::kTileSize;
698 clipboard_origin_set = true;
699 break;
700 }
701 } else {
702 entity_coordinator_.tile_handler().ClearClipboard();
703 }
704
705 CopySelectedEntitiesToClipboard(clipboard_origin_set);
706}
707
708void DungeonObjectInteraction::CopySelectedEntitiesToClipboard(
709 bool clipboard_origin_set) {
710 if (!rooms_ || current_room_id_ < 0 ||
711 current_room_id_ >= static_cast<int>(rooms_->size())) {
712 return;
713 }
714
715 const auto& room = (*rooms_)[current_room_id_];
716 auto selected_entities = entity_coordinator_.GetSelectedEntities();
717 if (selected_entities.empty() && entity_coordinator_.HasEntitySelection()) {
718 const SelectedEntity selected = entity_coordinator_.GetSelectedEntity();
719 if (selected.type != EntityType::None) {
720 selected_entities.push_back(selected);
721 }
722 }
723
724 for (const auto entity : selected_entities) {
725 switch (entity.type) {
726 case EntityType::Sprite: {
727 const auto& sprites = room.GetSprites();
728 if (entity.index >= sprites.size()) {
729 break;
730 }
731 const auto& sprite = sprites[entity.index];
732 if (!clipboard_origin_set && !entity_clipboard_.HasData()) {
733 entity_clipboard_.origin_pixel_x =
734 sprite.x() * dungeon_coords::kSpriteTileSize;
735 entity_clipboard_.origin_pixel_y =
736 sprite.y() * dungeon_coords::kSpriteTileSize;
737 entity_clipboard_.origin_tile_x =
738 entity_clipboard_.origin_pixel_x / dungeon_coords::kTileSize;
739 entity_clipboard_.origin_tile_y =
740 entity_clipboard_.origin_pixel_y / dungeon_coords::kTileSize;
741 }
742 entity_clipboard_.sprites.push_back(sprite);
743 break;
744 }
745 case EntityType::Item: {
746 const auto& items = room.GetPotItems();
747 if (entity.index >= items.size()) {
748 break;
749 }
750 const auto& item = items[entity.index];
751 if (!clipboard_origin_set && !entity_clipboard_.HasData()) {
752 entity_clipboard_.origin_pixel_x = item.GetPixelX();
753 entity_clipboard_.origin_pixel_y = item.GetPixelY();
754 entity_clipboard_.origin_tile_x =
755 entity_clipboard_.origin_pixel_x / dungeon_coords::kTileSize;
756 entity_clipboard_.origin_tile_y =
757 entity_clipboard_.origin_pixel_y / dungeon_coords::kTileSize;
758 }
759 entity_clipboard_.items.push_back(item);
760 break;
761 }
762 case EntityType::Door:
763 case EntityType::Object:
764 case EntityType::None:
765 default:
766 break;
767 }
768 }
769}
770
771std::vector<SelectedEntity> DungeonObjectInteraction::PasteEntityClipboardAt(
772 int target_pixel_x, int target_pixel_y) {
773 std::vector<SelectedEntity> pasted_entities;
774 if (!entity_clipboard_.HasData() || !rooms_ || current_room_id_ < 0 ||
775 current_room_id_ >= static_cast<int>(rooms_->size())) {
776 return pasted_entities;
777 }
778
779 auto& room = (*rooms_)[current_room_id_];
780 const int delta_pixel_x = target_pixel_x - entity_clipboard_.origin_pixel_x;
781 const int delta_pixel_y = target_pixel_y - entity_clipboard_.origin_pixel_y;
782
783 if (!entity_clipboard_.sprites.empty()) {
784 interaction_context_.NotifyMutation(MutationDomain::kSprites);
785 auto& sprites = room.GetSprites();
786 for (auto sprite : entity_clipboard_.sprites) {
787 const int next_x = std::clamp(
788 (sprite.x() * dungeon_coords::kSpriteTileSize + delta_pixel_x) /
789 dungeon_coords::kSpriteTileSize,
790 0, dungeon_coords::kSpriteGridMax);
791 const int next_y = std::clamp(
792 (sprite.y() * dungeon_coords::kSpriteTileSize + delta_pixel_y) /
793 dungeon_coords::kSpriteTileSize,
794 0, dungeon_coords::kSpriteGridMax);
795 sprite.set_x(next_x);
796 sprite.set_y(next_y);
797 sprites.push_back(sprite);
798 pasted_entities.push_back(
799 SelectedEntity{EntityType::Sprite, sprites.size() - 1});
800 }
801 room.MarkSpritesDirty();
802 interaction_context_.NotifyInvalidateCache(MutationDomain::kSprites);
803 }
804
805 if (!entity_clipboard_.items.empty()) {
806 interaction_context_.NotifyMutation(MutationDomain::kItems);
807 auto& items = room.GetPotItems();
808 for (auto item : entity_clipboard_.items) {
809 item.position = EncodePotItemPosition(item.GetPixelX() + delta_pixel_x,
810 item.GetPixelY() + delta_pixel_y);
811 items.push_back(item);
812 pasted_entities.push_back(
813 SelectedEntity{EntityType::Item, items.size() - 1});
814 }
815 room.MarkPotItemsDirty();
816 interaction_context_.NotifyInvalidateCache(MutationDomain::kItems);
817 }
818
819 if (!pasted_entities.empty()) {
820 interaction_context_.NotifyEntityChanged();
821 }
822 return pasted_entities;
823}
824
825void DungeonObjectInteraction::HandlePasteObjects() {
826 if (!HasClipboardData()) {
827 return;
828 }
829
830 if (!rooms_ || current_room_id_ < 0 ||
831 current_room_id_ >= static_cast<int>(rooms_->size())) {
832 return;
833 }
834
835 auto& handler = entity_coordinator_.tile_handler();
836 const ImGuiIO& io = ImGui::GetIO();
837 const auto [canvas_mouse_x, canvas_mouse_y] =
838 GetCanvasTransform().ScreenToRoomPixelCoordinates(io.MousePos);
839 auto [paste_x, paste_y] =
840 CanvasToRoomCoordinates(canvas_mouse_x, canvas_mouse_y);
841 int paste_pixel_x = paste_x * dungeon_coords::kTileSize;
842 int paste_pixel_y = paste_y * dungeon_coords::kTileSize;
843
844 if (!IsWithinCanvasBounds(canvas_mouse_x, canvas_mouse_y, 0)) {
845 const int fallback_delta = entity_clipboard_.sprites.empty()
846 ? dungeon_coords::kTileSize
847 : dungeon_coords::kSpriteTileSize;
848 paste_pixel_x =
849 std::clamp(entity_clipboard_.origin_pixel_x + fallback_delta, 0,
850 dungeon_coords::kRoomPixelWidth - dungeon_coords::kTileSize);
851 paste_pixel_y = std::clamp(
852 entity_clipboard_.origin_pixel_y + fallback_delta, 0,
853 dungeon_coords::kRoomPixelHeight - dungeon_coords::kTileSize);
854 paste_x = paste_pixel_x / dungeon_coords::kTileSize;
855 paste_y = paste_pixel_y / dungeon_coords::kTileSize;
856 }
857
858 std::vector<size_t> new_indices;
859 if (handler.HasClipboardData()) {
860 new_indices = handler.PasteFromClipboard(
861 current_room_id_, paste_x - entity_clipboard_.origin_tile_x,
862 paste_y - entity_clipboard_.origin_tile_y);
863 }
864 auto new_entities = PasteEntityClipboardAt(paste_pixel_x, paste_pixel_y);
865
866 if (!new_indices.empty() || !new_entities.empty()) {
867 selection_.ClearSelection();
868 for (size_t idx : new_indices) {
869 selection_.SelectObject(idx, ObjectSelection::SelectionMode::Add);
870 }
871 entity_coordinator_.SetSelectedEntities(std::move(new_entities));
872 }
873}
874
875void DungeonObjectInteraction::DrawGhostPreview() {
876 entity_coordinator_.DrawGhostPreviews();
877}
878
879void DungeonObjectInteraction::HandleScrollWheelResize() {
880 const ImGuiIO& io = ImGui::GetIO();
881 entity_coordinator_.HandleMouseWheel(io.MouseWheel);
882}
883
884bool DungeonObjectInteraction::SetObjectId(size_t index, int16_t id) {
885 entity_coordinator_.tile_handler().UpdateObjectsId(current_room_id_, {index},
886 id);
887 return true;
888}
889
890bool DungeonObjectInteraction::SetObjectSize(size_t index, uint8_t size) {
891 entity_coordinator_.tile_handler().UpdateObjectsSize(current_room_id_,
892 {index}, size);
893 return true;
894}
895
896bool DungeonObjectInteraction::SetObjectLayer(
897 size_t index, zelda3::RoomObject::LayerType layer) {
898 return entity_coordinator_.tile_handler().UpdateObjectsLayer(
899 current_room_id_, {index}, static_cast<int>(layer));
900}
901
902std::pair<int, int> DungeonObjectInteraction::CalculateObjectBounds(
903 const zelda3::RoomObject& object) {
905}
906
907bool DungeonObjectInteraction::CanAssignSelectedObjectsToLayer(
908 int target_layer) const {
909 if (!rooms_ || current_room_id_ < 0 ||
910 current_room_id_ >= static_cast<int>(rooms_->size()) ||
911 target_layer < 0 || target_layer > 2) {
912 return false;
913 }
914
915 const auto selected = selection_.GetSelectedIndices();
916 if (selected.empty()) {
917 return false;
918 }
919
920 const auto& objects = (*rooms_)[current_room_id_].GetTileObjects();
921 for (const size_t index : selected) {
922 if (index >= objects.size() ||
923 (target_layer == 2 && !zelda3::UsesRoomObjectStream(objects[index]))) {
924 return false;
925 }
926 }
927 return true;
928}
929
930bool DungeonObjectInteraction::SendSelectedToLayer(int target_layer) {
931 if (!CanAssignSelectedObjectsToLayer(target_layer)) {
932 return false;
933 }
934 return entity_coordinator_.tile_handler().UpdateObjectsLayer(
935 current_room_id_, selection_.GetSelectedIndices(), target_layer);
936}
937
938void DungeonObjectInteraction::SendSelectedToFront() {
939 entity_coordinator_.tile_handler().SendToFront(
940 current_room_id_, selection_.GetSelectedIndices());
941}
942
943void DungeonObjectInteraction::SendSelectedToBack() {
944 entity_coordinator_.tile_handler().SendToBack(
945 current_room_id_, selection_.GetSelectedIndices());
946}
947
948void DungeonObjectInteraction::BringSelectedForward() {
949 entity_coordinator_.tile_handler().MoveForward(
950 current_room_id_, selection_.GetSelectedIndices());
951}
952
953void DungeonObjectInteraction::SendSelectedBackward() {
954 entity_coordinator_.tile_handler().MoveBackward(
955 current_room_id_, selection_.GetSelectedIndices());
956}
957
958void DungeonObjectInteraction::HandleLayerKeyboardShortcuts() {
959 // Only process if we have selected objects
960 if (!selection_.HasSelection())
961 return;
962
963 // Only when not typing in a text field
964 if (ImGui::IsAnyItemActive())
965 return;
966
967 // Check for stored placement shortcuts (1, 2, 3 keys). The third room
968 // object stream is intentionally unavailable to torches/pushable blocks.
969 if (ImGui::IsKeyPressed(ImGuiKey_1)) {
970 SendSelectedToLayer(0); // Primary stream / upper layer (BG1)
971 } else if (ImGui::IsKeyPressed(ImGuiKey_2)) {
972 SendSelectedToLayer(1); // BG2 overlay / lower layer (BG2)
973 } else if (ImGui::IsKeyPressed(ImGuiKey_3)) {
974 SendSelectedToLayer(2); // BG1 overlay stream
975 }
976
977 // Object ordering shortcuts
978 // Ctrl+Shift+] = Bring to Front, Ctrl+Shift+[ = Send to Back
979 // Ctrl+] = Bring Forward, Ctrl+[ = Send Backward
980 auto& io = ImGui::GetIO();
981 if (io.KeyCtrl && io.KeyShift) {
982 if (ImGui::IsKeyPressed(ImGuiKey_RightBracket)) {
983 SendSelectedToFront();
984 } else if (ImGui::IsKeyPressed(ImGuiKey_LeftBracket)) {
985 SendSelectedToBack();
986 }
987 } else if (io.KeyCtrl) {
988 if (ImGui::IsKeyPressed(ImGuiKey_RightBracket)) {
989 BringSelectedForward();
990 } else if (ImGui::IsKeyPressed(ImGuiKey_LeftBracket)) {
991 SendSelectedBackward();
992 }
993 }
994}
995
996// ============================================================================
997// Door Placement Methods
998// ============================================================================
999
1000void DungeonObjectInteraction::SetDoorPlacementMode(bool enabled,
1001 zelda3::DoorType type) {
1002 if (enabled) {
1003 mode_manager_.SetMode(InteractionMode::PlaceDoor);
1004 entity_coordinator_.door_handler().SetDoorType(type);
1005 entity_coordinator_.door_handler().BeginPlacement();
1006 } else {
1007 entity_coordinator_.door_handler().CancelPlacement();
1008 if (mode_manager_.GetMode() == InteractionMode::PlaceDoor)
1009 mode_manager_.SetMode(InteractionMode::Select);
1010 }
1011}
1012
1013// ============================================================================
1014// Sprite Placement Methods
1015// ============================================================================
1016
1017void DungeonObjectInteraction::SetSpritePlacementMode(bool enabled,
1018 uint8_t sprite_id) {
1019 if (enabled) {
1020 mode_manager_.SetMode(InteractionMode::PlaceSprite);
1021 entity_coordinator_.sprite_handler().SetSpriteId(sprite_id);
1022 entity_coordinator_.sprite_handler().BeginPlacement();
1023 } else {
1024 entity_coordinator_.sprite_handler().CancelPlacement();
1025 if (mode_manager_.GetMode() == InteractionMode::PlaceSprite)
1026 mode_manager_.SetMode(InteractionMode::Select);
1027 }
1028}
1029
1030// ============================================================================
1031// Item Placement Methods
1032// ============================================================================
1033
1034void DungeonObjectInteraction::SetItemPlacementMode(bool enabled,
1035 uint8_t item_id) {
1036 if (enabled) {
1037 mode_manager_.SetMode(InteractionMode::PlaceItem);
1038 entity_coordinator_.item_handler().SetItemId(item_id);
1039 entity_coordinator_.item_handler().BeginPlacement();
1040 } else {
1041 entity_coordinator_.item_handler().CancelPlacement();
1042 if (mode_manager_.GetMode() == InteractionMode::PlaceItem)
1043 mode_manager_.SetMode(InteractionMode::Select);
1044 }
1045}
1046
1047// ============================================================================
1048// Entity Selection Methods (Doors, Sprites, Items)
1049// ============================================================================
1050
1051void DungeonObjectInteraction::SelectEntity(EntityType type, size_t index) {
1052 selection_.ClearSelection();
1053 entity_coordinator_.SelectEntity(type, index);
1054}
1055
1056void DungeonObjectInteraction::ClearEntitySelection() {
1057 entity_coordinator_.ClearEntitySelection();
1058}
1059
1060void DungeonObjectInteraction::CancelPlacement() {
1061 entity_coordinator_.CancelPlacement();
1062 if (mode_manager_.IsPlacementActive()) {
1063 mode_manager_.SetMode(InteractionMode::Select);
1064 }
1065}
1066
1067void DungeonObjectInteraction::DrawEntitySelectionHighlights() {
1068 entity_coordinator_.DrawSelectionHighlights();
1069 entity_coordinator_.DrawPostPlacementOverlays();
1070}
1071
1072void DungeonObjectInteraction::DrawDoorSnapIndicators() {
1073 // Door snap indicators are now managed by DoorInteractionHandler
1074 // through the entity coordinator. No-op here for backward compatibility.
1075}
1076
1077} // namespace yaze::editor
static Flags & get()
Definition features.h:119
std::pair< int, int > ScreenToRoomPixelCoordinates(ImVec2 screen) const
ImVec2 ScreenToRoomPixels(ImVec2 screen) const
ImVec2 RoomSizeToScreen(ImVec2 room_size) const
DungeonCanvasTransform GetCanvasTransform() const
void HandleObjectSelectionStart(const ImVec2 &canvas_mouse_pos)
void HandleLeftClick(const ImVec2 &canvas_mouse_pos)
void UpdateWaterFillPainting(const ImVec2 &canvas_mouse_pos)
std::pair< int, int > CanvasToRoomCoordinates(int canvas_x, int canvas_y) const
void HandleEmptySpaceClick(const ImVec2 &canvas_mouse_pos)
void UpdateCollisionPainting(const ImVec2 &canvas_mouse_pos)
bool IsPlacementActive() const
Check if any placement mode is active.
bool HandleClick(int canvas_x, int canvas_y)
Handle click at canvas position.
void HandleDrag(ImVec2 current_pos, ImVec2 delta)
Handle drag operation.
InteractionMode GetMode() const
Get current interaction mode.
ModeState & GetModeState()
Get mutable reference to mode state.
bool IsRectangleSelectionActive() const
Check if a rectangle selection is in progress.
bool HasSelection() const
Check if any objects are selected.
bool IsMouseHovering() const
Definition canvas.h:340
static DimensionService & Get()
std::tuple< int, int, int, int > GetSelectionBoundsPixels(const RoomObject &obj) const
DimensionResult GetDimensions(const RoomObject &obj) const
std::pair< int, int > GetPixelDimensions(const RoomObject &obj) const
#define ICON_MD_DRAG_INDICATOR
Definition icons.h:624
#define ICON_MD_TOUCH_APP
Definition icons.h:2000
#define ICON_MD_MOUSE
Definition icons.h:1251
bool IsWithinBounds(int canvas_x, int canvas_y, int margin=0)
Check if coordinates are within room bounds.
void ForEachPointInSquareBrush(int cx, int cy, int radius, int min_x, int min_y, int max_x, int max_y, Fn &&fn)
Definition paint_util.h:40
void ForEachPointOnLine(int x0, int y0, int x1, int y1, Fn &&fn)
Definition paint_util.h:13
Editors are the view controllers for the application.
EntityType
Type of entity that can be selected in the dungeon editor.
DoorType
Door types from ALTTP.
Definition door_types.h:33
int GetObjectSubtype(int object_id)
bool UsesRoomObjectStream(const RoomObject &object)
std::string GetObjectName(int object_id)
void NotifyInvalidateCache(MutationDomain domain=MutationDomain::kUnknown) const
Notify that cache invalidation is needed.
void NotifyMutation(MutationDomain domain=MutationDomain::kUnknown) const
Notify that a mutation is about to happen.
Represents a selected entity in the dungeon editor.