11#include "absl/cleanup/cleanup.h"
12#include "absl/strings/str_format.h"
44using ImGui::BeginTable;
47using ImGui::Selectable;
48using ImGui::Separator;
49using ImGui::TableHeadersRow;
50using ImGui::TableNextColumn;
51using ImGui::TableNextRow;
52using ImGui::TableSetupColumn;
57void CopyStringToBuffer(
const std::string& src,
char (&dest)[N]) {
58 std::strncpy(dest, src.c_str(), N - 1);
68 long value = std::strtol(text.c_str(), &end, 0);
69 if (end == text.c_str() || errno == ERANGE) {
72 return static_cast<int>(value);
84 std::make_unique<VanillaSpriteEditorPanel>([
this]() {
89 ImGui::TextDisabled(tr(
"Load a ROM to view vanilla sprites"));
93 window_manager->RegisterWindowContent(
94 std::make_unique<CustomSpriteEditorPanel>([
this]() {
98 window_manager->RegisterWindowContent(
120 return absl::OkStatus();
129 float current_time = ImGui::GetTime();
151 const ImGuiIO& io = ImGui::GetIO();
152 if (!panel_focused || io.WantTextInput) {
157 if (ImGui::IsKeyPressed(ImGuiKey_Space,
false)) {
162 const bool bare_keys = !io.KeyCtrl && !io.KeyAlt && !io.KeySuper;
164 const int frame_count =
static_cast<int>(sprite->editor.Frames.size());
166 if (ImGui::IsKeyPressed(ImGuiKey_LeftBracket,
false)) {
168 }
else if (ImGui::IsKeyPressed(ImGuiKey_RightBracket,
false)) {
180 if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_UpArrow,
false)) {
185 if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_DownArrow,
false)) {
195 return absl::FailedPreconditionError(
196 "Autosave paused: untitled sprite assets are retained; use Sprite "
197 "Save As to choose their destinations");
208 absl::Cleanup restore = [
this, selected, frame] {
214 for (
const int index : pending) {
225 return absl::CancelledError(
"Sprite Save As was cancelled");
227 return absl::OkStatus();
229 return absl::OkStatus();
241 if (sprite_id < 0 || sprite_id >= 256)
259 if (ImGui::BeginTable(
"##SpriteCanvasTable", 3, ImGuiTableFlags_Resizable,
261 TableSetupColumn(
"Sprites List", ImGuiTableColumnFlags_WidthFixed, 256);
262 TableSetupColumn(
"Canvas", ImGuiTableColumnFlags_WidthStretch,
263 ImGui::GetContentRegionAvail().x);
264 TableSetupColumn(
"Tile Selector", ImGuiTableColumnFlags_WidthFixed, 256);
273 ImGui::TextWrapped(
"Select a sprite from the list to open its preview.");
284 if (sprite_id < 0 || sprite_id >= 256) {
290 absl::StrFormat(
"%02X %s###SpriteTab%02X", sprite_id,
293 ? ImGuiTabItemFlags_SetSelected
294 : ImGuiTabItemFlags_None;
295 const bool selected = ImGui::BeginTabItem(label.c_str(), &open, flags);
297 absl::StrFormat(
"SpriteTab%02X", sprite_id));
326 if (ImGui::BeginChild(
gui::GetID(
"##SpriteCanvas"),
327 ImGui::GetContentRegionAvail(),
true)) {
333 ImGui::SetCursorPos(ImVec2(10, 10));
337 "No static OAM layout for sprite $%02X. Open or import a ZSM in "
338 "Custom Sprites to preview authored frames.",
340 }
else if (layout->graphics_resource) {
342 "%s ($%02X) requires external graphics (%s). This editor does not "
343 "yet preview that graphics source.",
344 layout->name, layout->sprite_id, layout->graphics_resource);
351 ImGui::TextWrapped(
"Preview unavailable: %s",
352 std::string(error.message()).c_str());
356 Text(tr(
"Sprite: %s (0x%02X)"), layout->name, layout->sprite_id);
357 Text(tr(
"Tiles: %zu"), layout->tiles.size());
360 [](uint8_t pixel) { return (pixel & 0x0F) != 0; })) {
362 "The selected sheets contain no visible pixels for this layout. "
363 "Choose the sprite's spriteset or graphics sheets.");
367 "Uses the selected sheets and palette. Animation, behavior, and "
368 "runtime graphics changes are not simulated.");
371 if (ImGui::Button(layout ? tr(
"Edit preview copy")
372 : tr(
"Create empty sprite template")))
376 ?
"Creates a detached static pose. Bind any external graphics "
377 "in Custom Sprites > Graphics sources."
378 :
"This ID has no decoded static layout. The template starts "
379 "with an empty frame for authoring; game OAM is not imported.");
388 bool use_asset_binding) {
389 if (
game_data() ==
nullptr || spriteset < 0 ||
398 std::copy(slots.begin(), slots.end(),
404 std::copy(slots.begin(), slots.end(), binding.sheets.begin());
413 current_frame_ >=
static_cast<int>(sprite->editor.Frames.size())) {
414 return absl::FailedPreconditionError(
"Select a sprite frame");
417 return absl::FailedPreconditionError(
418 "Load a ROM before editing sprite pixels");
422 std::any_of(binding->graphics_sources.begin(),
423 binding->graphics_sources.end(),
424 [](
const auto& source) { return source.kind !=
"sheet"; }))
425 return absl::FailedPreconditionError(
426 "This asset uses BIN or raw ROM graphics. Edit BIN pixels in Graphics "
427 "Scratch, export the BIN, then Reload graphics sources here. Raw ROM "
428 "bindings are read-only preview ranges.");
436 std::array<uint8_t, 8> slots;
440 const std::string source =
442 ? absl::StrFormat(
"room %03X CGRAM rows 8-15; sprite slots %02X",
446 "sprite asset binding; preview spriteset %02X",
448 : absl::StrFormat(
"preview spriteset %02X",
452 sprite->sprName, source);
456 context->render_preview = [frame, slots, palettes, owner]() {
462 return absl::FailedPreconditionError(
"Editor manager unavailable");
466 context->return_to_source = [
this, manager, sprite_index, frame_index,
468 if (sprite_index >= 0 &&
482 auto* editor_set = manager->GetCurrentEditorSet();
483 if (!editor_set || !editor_set->GetGraphicsEditor()) {
484 return absl::FailedPreconditionError(
"Graphics editor unavailable");
489 status = editor_set->GetGraphicsEditor()->OpenInContext(std::move(*
context));
493 return absl::OkStatus();
497 if (!ImGui::CollapsingHeader(tr(
"Spriteset preview"),
498 ImGuiTreeNodeFlags_DefaultOpen)) {
502 ImGui::TextDisabled(tr(
"Load a ROM to preview against spritesets."));
521 "Slots 0-3 take the static sprite sheets, slots 4-7 this spriteset's "
522 "values + 0x73 (OAM tiles 0x100-0x1FF).");
528 "Values %02X %02X %02X %02X -> sheets %02X %02X %02X %02X", values[0],
529 values[1], values[2], values[3], slots[4], slots[5], slots[6], slots[7]);
533 auto hex_list = [](
const std::vector<int>& ids) {
535 return std::string(
"-");
538 for (
size_t i = 0; i < ids.size() && i < 24; ++i) {
539 out += absl::StrFormat(
"%s%02X", i == 0 ?
"" :
" ", ids[i]);
541 if (ids.size() > 24) {
542 out += absl::StrFormat(
" (+%zu)", ids.size() - 24);
546 for (
int state = 0; state < 3; ++state) {
547 ImGui::TextWrapped(
"OW areas, state %d: %s", state,
548 hex_list(usage.ow_areas_by_state[state]).c_str());
550 ImGui::TextWrapped(
"Rooms: %s", hex_list(usage.rooms).c_str());
554 ImGui::InputScalar(
"Room", ImGuiDataType_U16, &
preview_room_,
nullptr,
555 nullptr,
"%03X", ImGuiInputTextFlags_CharsHexadecimal);
571 HOVER_HINT(
"Use the room's header spriteset (+0x40) and its sprite palette");
572 if (ImGui::Checkbox(tr(
"Room palette (CGRAM rows 8-15)"),
579 "Off: palette rows from the sprite binding (Sprite Asset panel). On: "
580 "the rows the game loads for the room above.");
582 if (use_asset_binding)
590 current_frame_ >=
static_cast<int>(sprite->editor.Frames.size())) {
595 const auto before = tiles.size();
597 std::remove_if(tiles.begin(), tiles.end(),
599 const int slot = zelda3::SpriteSlotForTile(tile);
600 return slot >= 0 && slot < 8 &&
601 binding->graphics_sources[slot].kind !=
"sheet";
604 if (tiles.size() != before)
606 "%zu tiles use BIN/raw ROM sources; ROM sheet usage checks apply "
607 "only to the remaining tiles.",
608 before - tiles.size());
612 std::array<uint8_t, 8> slots;
617 for (uint8_t sheet : slots) {
618 key += absl::StrFormat(
"%02X", sheet);
620 for (
int tile : tiles) {
621 key += absl::StrFormat(
",%X", tile);
623 for (uint16_t sheet : options.reserved_sheets) {
624 key += absl::StrFormat(
"r%X", sheet);
641 " Frame %d: %zu of %zu 8x8 tiles need "
644 for (
size_t i = 0; i <
tile_issues_.size() && i < 8; ++i) {
651 :
"sheet unreadable");
652 ImGui::BulletText(
"tile 0x%03X, slot %d (sheet 0x%02X): %s", issue.tile,
653 issue.slot, issue.sheet, what);
656 ImGui::TextDisabled(
"... %zu more",
tile_issues_.size() - 8);
661 if (ImGui::BeginChild(
gui::GetID(
"sheet_label"),
662 ImVec2(ImGui::GetContentRegionAvail().x, 0),
true,
663 ImGuiWindowFlags_NoDecoration)) {
667 bool sheets_changed =
false;
671 for (
int i = 0; i < 8; i++) {
672 std::string sheet_label = absl::StrFormat(
"Sheet %d", i);
674 sheets_changed =
true;
681 if (sheets_changed) {
696 for (
int i = 0; i < 8; i++) {
697 const auto* binding =
699 if (binding && binding->graphics_sources[i].kind !=
"sheet") {
702 const std::vector<uint8_t> pixels(
705 const bool create = !sheet.is_active();
706 bool palette_changed =
false;
709 palette_changed = sheet.palette().
size() != palette.size();
710 if (!palette_changed)
711 for (
size_t color = 0; color < palette.size(); ++color)
713 sheet.palette()[color].snes() != palette[color].snes();
715 if (create || sheet.vector() != pixels || palette_changed) {
717 sheet.Create(128, 32, 8, pixels);
719 sheet.set_data(pixels);
733 if (sheet.is_active() && !sheet.texture())
734 sheet.CreateTexture();
744 if (ImGui::BeginChild(
gui::GetID(
"##SpritesList"),
745 ImVec2(ImGui::GetContentRegionAvail().x, 0),
true,
746 ImGuiWindowFlags_NoDecoration)) {
752 if (ImGui::IsItemClicked()) {
766 if (BeginTable(
"##CustomSpritesTable", 3,
767 ImGuiTableFlags_Resizable | ImGuiTableFlags_Borders,
769 TableSetupColumn(
"Sprite Data", ImGuiTableColumnFlags_WidthFixed, 300);
770 TableSetupColumn(
"Canvas", ImGuiTableColumnFlags_WidthStretch);
771 TableSetupColumn(
"Tilesheets", ImGuiTableColumnFlags_WidthFixed, 280);
778 if (ImGui::BeginChild(
"##SpriteMetadata", ImVec2(0, 0)))
802 if (!file_path.empty()) {
810 if (zsm_path.empty()) {
825 Text(tr(
"Loaded Sprites:"));
826 const float avail_y = std::max(0.0f, ImGui::GetContentRegionAvail().y);
827 const float metadata_reserve = std::min(160.0f, avail_y * 0.45f);
828 const float list_budget = std::max(0.0f, avail_y - metadata_reserve);
829 const float preferred_list = std::clamp(avail_y * 0.35f, 180.0f, 280.0f);
830 const float list_height = std::min(preferred_list, list_budget);
831 if (ImGui::BeginChild(
"SpriteList", ImVec2(0, list_height),
true)) {
836 ImGui::PushID(
static_cast<int>(i));
863 if (ImGui::BeginTabItem(tr(
"Properties"))) {
867 if (ImGui::BeginTabItem(tr(
"Animations"))) {
871 if (ImGui::BeginTabItem(tr(
"Behavior"))) {
875 if (ImGui::BeginTabItem(tr(
"Routines"))) {
882 Text(tr(
"No sprite selected"));
890 return absl::FailedPreconditionError(
891 "Select a custom sprite frame to copy");
894 if (current_frame_ < 0 || current_frame_ >=
static_cast<int>(frames.size()))
895 return absl::FailedPreconditionError(
"Select a frame to copy");
897 return absl::OkStatus();
903 if (sprite.editor.Frames.size() <= 1)
904 return absl::FailedPreconditionError(
905 "Cannot cut the last frame; copied it instead");
909 static_cast<int>(sprite.editor.Frames.size()) - 1);
913 return absl::OkStatus();
919 return absl::FailedPreconditionError(
920 "Copy a frame and select a destination sprite");
923 return absl::OutOfRangeError(
"ZSM animations address at most 256 frames");
926 current_frame_ =
static_cast<int>(sprite.editor.Frames.size()) - 1;
930 return absl::OkStatus();
937 new_sprite.
sprName =
"New Sprite";
943 new_sprite.
animations.emplace_back(0, 0, 1,
"Idle");
1004 binding.zsm_path = path;
1008 std::find_if(assets.begin(), assets.end(), [&](
const auto& asset) {
1009 return project()->GetAbsolutePath(asset.zsm_path) == path;
1011 if (found == assets.end())
1012 assets.push_back(binding);
1027 if (!path.empty()) {
1041 Text(tr(
"Sprite Info"));
1044 static char name_buf[256];
1045 CopyStringToBuffer(sprite.sprName, name_buf);
1046 if (ImGui::InputText(tr(
"Name"), name_buf,
sizeof(name_buf))) {
1047 sprite.sprName = name_buf;
1048 sprite.property_sprname.Text = name_buf;
1052 static char id_buf[32];
1053 CopyStringToBuffer(sprite.property_sprid.Text, id_buf);
1054 if (ImGui::InputText(tr(
"Sprite ID"), id_buf,
sizeof(id_buf))) {
1055 sprite.property_sprid.Text = id_buf;
1072 int prize = ParseIntOrDefault(sprite.property_prize.Text);
1073 if (ImGui::InputInt(tr(
"Prize"), &prize)) {
1074 sprite.property_prize.Text = std::to_string(std::clamp(prize, 0, 255));
1078 int palette = ParseIntOrDefault(sprite.property_palette.Text);
1079 if (ImGui::InputInt(tr(
"Palette"), &palette)) {
1080 sprite.property_palette.Text = std::to_string(std::clamp(palette, 0, 7));
1084 int oamnbr = ParseIntOrDefault(sprite.property_oamnbr.Text);
1085 if (ImGui::InputInt(tr(
"OAM Count"), &oamnbr)) {
1086 sprite.property_oamnbr.Text = std::to_string(std::clamp(oamnbr, 0, 255));
1090 int hitbox = ParseIntOrDefault(sprite.property_hitbox.Text);
1091 if (ImGui::InputInt(tr(
"Hitbox"), &hitbox)) {
1092 sprite.property_hitbox.Text = std::to_string(std::clamp(hitbox, 0, 255));
1096 int health = ParseIntOrDefault(sprite.property_health.Text);
1097 if (ImGui::InputInt(tr(
"Health"), &health)) {
1098 sprite.property_health.Text = std::to_string(std::clamp(health, 0, 255));
1102 int damage = ParseIntOrDefault(sprite.property_damage.Text);
1103 if (ImGui::InputInt(tr(
"Damage"), &damage)) {
1104 sprite.property_damage.Text = std::to_string(std::clamp(damage, 0, 255));
1112 Text(tr(
"Behavior Flags"));
1115 if (ImGui::BeginTable(
"BoolProps", 2, ImGuiTableFlags_None)) {
1117 ImGui::TableNextColumn();
1118 if (ImGui::Checkbox(tr(
"Blockable"), &sprite.property_blockable.IsChecked))
1120 if (ImGui::Checkbox(tr(
"Can Fall"), &sprite.property_canfall.IsChecked))
1122 if (ImGui::Checkbox(tr(
"Collision Layer"),
1123 &sprite.property_collisionlayer.IsChecked))
1125 if (ImGui::Checkbox(tr(
"Custom Death"),
1126 &sprite.property_customdeath.IsChecked))
1128 if (ImGui::Checkbox(tr(
"Damage Sound"),
1129 &sprite.property_damagesound.IsChecked))
1131 if (ImGui::Checkbox(tr(
"Deflect Arrows"),
1132 &sprite.property_deflectarrows.IsChecked))
1134 if (ImGui::Checkbox(tr(
"Deflect Projectiles"),
1135 &sprite.property_deflectprojectiles.IsChecked))
1137 if (ImGui::Checkbox(tr(
"Fast"), &sprite.property_fast.IsChecked))
1139 if (ImGui::Checkbox(tr(
"Harmless"), &sprite.property_harmless.IsChecked))
1141 if (ImGui::Checkbox(tr(
"Impervious"),
1142 &sprite.property_impervious.IsChecked))
1146 ImGui::TableNextColumn();
1147 if (ImGui::Checkbox(tr(
"Impervious Arrow"),
1148 &sprite.property_imperviousarrow.IsChecked))
1150 if (ImGui::Checkbox(tr(
"Impervious Melee"),
1151 &sprite.property_imperviousmelee.IsChecked))
1153 if (ImGui::Checkbox(tr(
"Interaction"),
1154 &sprite.property_interaction.IsChecked))
1156 if (ImGui::Checkbox(tr(
"Is Boss"), &sprite.property_isboss.IsChecked))
1158 if (ImGui::Checkbox(tr(
"Persist"), &sprite.property_persist.IsChecked))
1160 if (ImGui::Checkbox(tr(
"Shadow"), &sprite.property_shadow.IsChecked))
1162 if (ImGui::Checkbox(tr(
"Small Shadow"),
1163 &sprite.property_smallshadow.IsChecked))
1165 if (ImGui::Checkbox(tr(
"Stasis"), &sprite.property_statis.IsChecked))
1167 if (ImGui::Checkbox(tr(
"Statue"), &sprite.property_statue.IsChecked))
1169 if (ImGui::Checkbox(tr(
"Water Sprite"),
1170 &sprite.property_watersprite.IsChecked))
1184 if (ImGui::Button(tr(
"Copy draw tables (ASM)"))) {
1188 ImGui::SetClipboardText(tables->c_str());
1191 "Copy a draw-table candidate. Does not register or patch a sprite.");
1222 (
int)sprite.editor.Frames.size() - 1);
1227 Text(tr(
"Animations"));
1228 if (ImGui::Button(
ICON_MD_ADD " Add Animation")) {
1229 int frame_count =
static_cast<int>(sprite.editor.Frames.size());
1230 sprite.animations.emplace_back(0, std::clamp(frame_count - 1, 0, 255), 1,
1236 if (ImGui::BeginChild(
"AnimList", ImVec2(0, 120),
true)) {
1237 for (
size_t i = 0; i < sprite.animations.size(); i++) {
1238 auto& anim = sprite.animations[i];
1239 std::string label = anim.frame_name.empty() ?
"Unnamed" : anim.frame_name;
1240 ImGui::PushID(
static_cast<int>(i));
1258 Text(tr(
"Animation Properties"));
1260 static char anim_name[128];
1261 CopyStringToBuffer(anim.frame_name, anim_name);
1262 if (ImGui::InputText(tr(
"Name##Anim"), anim_name,
sizeof(anim_name))) {
1263 anim.frame_name = anim_name;
1267 int start = anim.frame_start;
1268 int end = anim.frame_end;
1269 int speed = anim.frame_speed;
1271 if (ImGui::SliderInt(
1272 tr(
"Start Frame"), &start, 0,
1273 std::clamp((
int)sprite.editor.Frames.size() - 1, 0, 255))) {
1274 anim.frame_start =
static_cast<uint8_t
>(start);
1275 anim.frame_end = std::max(anim.frame_start, anim.frame_end);
1276 end = anim.frame_end;
1279 if (ImGui::SliderInt(
1280 tr(
"End Frame"), &end, 0,
1281 std::clamp((
int)sprite.editor.Frames.size() - 1, 0, 255))) {
1282 anim.frame_end =
static_cast<uint8_t
>(end);
1283 anim.frame_start = std::min(anim.frame_start, anim.frame_end);
1286 if (ImGui::SliderInt(tr(
"Ticks per frame (60 Hz)"), &speed, 1, 255)) {
1287 anim.frame_speed =
static_cast<uint8_t
>(speed);
1293 bool used_by_action =
1294 std::any_of(actions.begin(), actions.end(), [&](
const auto& action) {
1295 return action.animation == current_animation_index_;
1297 ImGui::BeginDisabled(used_by_action);
1298 if (ImGui::Button(tr(
"Delete Animation")) && sprite.animations.size() > 1) {
1299 for (
auto& action : actions)
1302 sprite.animations.erase(sprite.animations.begin() +
1308 ImGui::EndDisabled();
1310 ImGui::TextDisabled(
1311 "Assign another animation to referencing actions before deleting.");
1325 current_frame_ =
static_cast<int>(sprite.editor.Frames.size()) - 1;
1342 HOVER_HINT(
"Delete the current frame and repair animation ranges");
1343 if (ImGui::Button(tr(
"Duplicate Frame")) &&
current_frame_ >= 0 &&
1345 current_frame_ =
static_cast<int>(sprite.editor.Frames.size()) - 1;
1349 ImGui::TextDisabled(
"Up to 256 frames; duplicate appends a frame.");
1352 if (ImGui::BeginChild(
"FrameList", ImVec2(0, 80),
true,
1353 ImGuiWindowFlags_HorizontalScrollbar)) {
1354 for (
size_t i = 0; i < sprite.editor.Frames.size(); i++) {
1355 ImGui::PushID(
static_cast<int>(i));
1356 std::string label = absl::StrFormat(
"F%d", i);
1358 ImGuiSelectableFlags_None, ImVec2(40, 40))) {
1377 frame.Tiles.emplace_back();
1386 if (ImGui::BeginChild(
"TileList", ImVec2(0, 100),
true)) {
1387 for (
size_t i = 0; i < frame.Tiles.size(); i++) {
1388 auto& tile = frame.Tiles[i];
1389 std::string label = absl::StrFormat(
"Tile %d (ID: %d)", i, tile.id);
1402 int tile_id = tile.id;
1403 if (ImGui::InputInt(tr(
"Tile ID"), &tile_id)) {
1404 tile.id =
static_cast<uint16_t
>(std::clamp(tile_id, 0, 511));
1411 if (ImGui::InputInt(tr(
"X offset"), &x)) {
1412 tile.x =
static_cast<uint8_t
>(std::clamp(x, -128, 127) +
1417 if (ImGui::InputInt(tr(
"Y offset"), &y)) {
1418 tile.y =
static_cast<uint8_t
>(std::clamp(y, -112, 143) +
1424 int pal = tile.palette;
1425 if (ImGui::SliderInt(tr(
"Palette##Tile"), &pal, 0, 7)) {
1426 tile.palette =
static_cast<uint8_t
>(pal);
1431 int priority = tile.priority;
1432 if (ImGui::SliderInt(tr(
"BG priority"), &priority, 0, 3)) {
1433 tile.priority =
static_cast<uint8_t
>(priority);
1436 ImGui::TextDisabled(
1437 "BG priority is stored; preview has no background layers.");
1438 if (ImGui::Checkbox(tr(
"16x16"), &tile.size)) {
1443 if (ImGui::Checkbox(tr(
"Flip X"), &tile.mirror_x)) {
1448 if (ImGui::Checkbox(tr(
"Flip Y"), &tile.mirror_y)) {
1453 if (ImGui::Button(tr(
"Edit selected OAM pixels"))) {
1461 if (ImGui::Button(tr(
"Duplicate Tile"))) {
1462 const auto copy = tile;
1463 frame.Tiles.push_back(copy);
1467 if (ImGui::Button(tr(
"Delete Tile"))) {
1506 sprite.userRoutines.emplace_back(
"New Routine",
"; ASM code here\n");
1512 if (ImGui::BeginChild(
"RoutineList", ImVec2(0, 100),
true)) {
1513 for (
size_t i = 0; i < sprite.userRoutines.size(); i++) {
1514 auto& routine = sprite.userRoutines[i];
1529 static char routine_name[128];
1530 CopyStringToBuffer(routine.name, routine_name);
1531 if (ImGui::InputText(tr(
"Routine Name"), routine_name,
1532 sizeof(routine_name))) {
1533 routine.name = routine_name;
1537 Text(tr(
"ASM Code:"));
1540 static char code_buffer[16384];
1541 CopyStringToBuffer(routine.code, code_buffer);
1542 if (ImGui::InputTextMultiline(
"##RoutineCode", code_buffer,
1543 sizeof(code_buffer), ImVec2(-1, 200))) {
1544 routine.code = code_buffer;
1548 if (ImGui::Button(tr(
"Delete Routine"))) {
1549 sprite.userRoutines.erase(sprite.userRoutines.begin() +
1564 const auto palette_revision =
1575 for (
int slot = 0; slot < 8; ++slot) {
1576 const auto revision =
1585 for (
int slot = 0; slot < 8; ++slot) {
1608 const auto directory =
1610 ? std::filesystem::path(
project()->filepath).parent_path()
1611 : std::filesystem::path{};
1612 for (
int sheet_idx = 0; sheet_idx < 8; sheet_idx++) {
1613 const auto source = binding ? binding->graphics_sources[sheet_idx]
1620 absl::Status(pixels.status().code(),
1621 absl::StrFormat(
"Graphics sheet/source in slot %d: %s",
1622 sheet_idx, pixels.status().message()));
1625 std::copy(pixels->begin(), pixels->end(),
1647 "Load ROM graphics and palettes before previewing sprites");
1663 if (global.empty() && aux1.empty() && aux2.empty() && aux3.empty() &&
1666 "Sprite palette colors are unavailable in this ROM session");
1668 if (
const auto* binding =
1716 origin_x, origin_y);
1726 for (
size_t col_idx = 0; col_idx < 16 && col_idx < sub_pal.size();
1728 combined_palette.
AddColor(sub_pal[col_idx]);
1731 while (combined_palette.
size() < (pal_idx + 1) * 16) {
1757 if (frame_index < 0 || frame_index >= (
int)sprite.editor.Frames.size()) {
1761 auto& frame = sprite.editor.Frames[frame_index];
1792 for (
size_t col_idx = 0; col_idx < 16 && col_idx < sub_pal.size();
1794 combined_palette.
AddColor(sub_pal[col_idx]);
1797 while (combined_palette.
size() < (pal_idx + 1) * 16) {
1819 for (
size_t i = 0; i < frame.Tiles.size(); i++) {
1820 const auto& tile = frame.Tiles[i];
1821 int tile_size = tile.size ? 16 : 8;
1827 int canvas_x = 128 + signed_x;
1828 int canvas_y = 128 + signed_y;
1832 ? ImVec4(0.0f, 1.0f, 0.0f, 0.8f)
1833 : ImVec4(1.0f, 1.0f, 0.0f, 0.3f);
1837 tile_size * 2, color);
1843 if (ImGui::BeginChild(
gui::GetID(
"##ZSpriteCanvas"),
1844 ImGui::GetContentRegionAvail(),
true)) {
1853 ImGui::SetCursorPos(ImVec2(10, 34));
1857 ImGui::TextWrapped(
"Preview unavailable: %s",
1858 std::string(error.message()).c_str());
1861 ImGui::SetCursorPos(ImVec2(10, 10));
1863 "Open a ZSM or import a draw copy to preview its frames.");
1872 ImGui::SetCursorPos(ImVec2(10, 10));
1874 std::snprintf(label,
sizeof(label), tr(
"Frame: %d | Tiles: %d"),
1880 const ImVec2 position = ImGui::GetCursorScreenPos();
1881 const ImVec2 size = ImGui::CalcTextSize(label);
1883 ImGui::GetWindowDrawList()->AddRectFilled(
1884 ImVec2(position.x - 3, position.y - 2),
1885 ImVec2(position.x + size.x + 3, position.y + size.y + 2),
1886 IM_COL32(24, 24, 24, 255), 3.0f);
1887 ImGui::TextColored(ImVec4(1, 1, 1, 1),
"%s", label);
1955 std::move(restore_fn)));
1973 static const std::string kEmptyPath;
project::ResourceLabelManager * resource_label()
The EditorManager controls the main editor window and manages the various editor classes.
EditorContext context() const
UndoManager undo_manager_
zelda3::GameData * game_data() const
EditorDependencies dependencies_
void SetPalettes(const gfx::PaletteGroup *palettes)
Set the palette group for color mapping.
void ClearBitmap(gfx::Bitmap &bitmap)
Clear the bitmap with transparent color.
void DrawFrame(gfx::Bitmap &bitmap, const zsprite::Frame &frame, int origin_x, int origin_y)
Draw all tiles in a ZSM frame.
bool IsReady() const
Check if drawer is ready to render.
void SetGraphicsBuffer(const uint8_t *buffer)
Set the graphics buffer for tile lookup.
std::array< gfx::Bitmap, 8 > external_sheet_previews_
ImVector< int > active_sprites_
absl::Status OpenSpriteAsset(const std::string &path)
int current_custom_sprite_index_
void UpdateAnimationPlayback(float delta_time)
std::vector< project::SpriteAssetBinding > custom_sprite_bindings_
absl::Status ReloadProjectSpriteAssets()
std::vector< zelda3::SpriteTileIssue > tile_issues_
void LoadSpriteGraphicsBuffer(bool use_asset_binding=true)
absl::Status OpenSelectedOamGraphics()
void DrawAnimationPanel()
void EnsureCustomSpritePaths()
void DrawSpriteAssetBindings()
const zsprite::ZSprite * current_custom_sprite() const
std::set< int > dirty_sprite_indices_
void BeginUndoTransaction()
void RefreshSpritePreviewGraphics(bool use_asset_binding)
std::array< uint64_t, 8 > loaded_preview_revisions_
void RenderZSpriteFrame(int frame_index)
absl::Status Paste() override
std::array< uint8_t, 8 > loaded_preview_sheets_
bool preview_use_room_palette_
absl::StatusOr< std::string > ExportCurrentSpriteDraw()
absl::Status SaveForAutosave()
bool preview_needs_update_
void DrawZSpriteOnCanvas()
void LoadSpritePalettes(bool use_asset_binding=true)
std::optional< zsprite::Frame > frame_clipboard_
bool vanilla_preview_needs_update_
absl::Status Update() override
bool preview_uses_asset_graphics_
uint64_t preview_palette_revision_
void DrawSpriteBehaviorPanel()
void HandleEditorShortcuts()
gfx::PaletteGroup sprite_palettes_
void LoadZsmFile(const std::string &path)
bool sprite_mutated_this_frame_
void ApplyCurrentSpriteBinding()
void DrawUserRoutinesPanel()
absl::Status Cut() override
void RenderVanillaSprite(const zelda3::SpriteOamLayout &layout)
absl::Status CreateSpriteAssetFromVanilla(int sprite_id)
absl::Status palette_binding_status_
void DrawCurrentSheets(bool use_asset_binding)
void Initialize() override
void DrawFrameTileWarnings()
void DrawVanillaSpriteEditor()
int selected_routine_index_
std::string behavior_candidate_
uint8_t vanilla_sheets_[8]
std::optional< std::map< int, zelda3::RoomGfxInfo > > usage_rooms_
const std::string & GetCurrentZsmPath() const
uint8_t current_sheets_[8]
SpriteDrawer sprite_drawer_
absl::Status asset_load_status_
gui::Canvas graphics_sheet_canvas_
int room_palette_cache_room_
void RestoreFromSnapshot(const SpriteSnapshot &snapshot)
bool undo_snapshot_pending_
std::vector< zsprite::ZSprite > custom_sprites_
std::vector< uint8_t > sprite_gfx_buffer_
gfx::Bitmap sprite_preview_bitmap_
project::YazeProject * project() const
absl::Status ReloadSpriteCatalog()
int current_animation_index_
void DrawSpritesetPicker(bool use_asset_binding)
const project::SpriteAssetBinding * current_sprite_binding() const
void DrawBooleanProperties()
void DrawSpritePropertiesPanel()
void SetCurrentZsmPath(const std::string &path)
bool sprite_bindings_pending_
absl::Status Copy() override
const zelda3::GameData * preview_graphics_owner_
absl::Status Save() override
std::optional< std::map< int, zelda3::OverworldAreaGfxInfo > > usage_areas_
void DrawCustomSpritesMetadata()
SpriteSnapshot undo_before_snapshot_
void SaveZsmFile(const std::string &path)
gui::Canvas sprite_canvas_
void CommitUndoTransaction()
void ApplySpritesetToSheets(int spriteset, bool use_asset_binding)
SpriteSnapshot CaptureCurrentSpriteSnapshot() const
void DrawStatProperties()
absl::Status graphics_binding_status_
absl::Status graphics_context_status_
std::optional< gfx::PaletteGroup > room_palette_cache_
absl::Status CheckCurrentSpriteSource()
absl::Status Load() override
std::vector< std::string > custom_sprite_paths_
void SelectVanillaSprite(int sprite_id)
std::string tile_check_key_
absl::Status draw_export_status_
gfx::Bitmap vanilla_preview_bitmap_
const zelda3::SpriteOamLayout * CurrentPreviewLayout() const
void Push(std::unique_ptr< UndoAction > action)
void RegisterWindowContent(std::unique_ptr< WindowContent > window)
Register a WindowContent instance for central drawing.
void QueueTextureCommand(TextureCommandType type, Bitmap *bitmap)
GraphicsSheets & gfx_sheets()
const std::vector< uint8_t > & vector() const
void SetPalette(const SnesPalette &palette)
Set the palette for the bitmap using SNES palette format.
uint64_t ColorRevision(const zelda3::GameData *game_data) const
static PaletteManager & Get()
Get the singleton instance.
RAII timer for automatic timing management.
Represents a palette of colors for the Super Nintendo Entertainment System (SNES).
void AddColor(const SnesColor &color)
void DrawBitmap(Bitmap &bitmap, int border_offset, float scale)
bool DrawTileSelector(int size, int size_y=0)
void DrawRect(int x, int y, int w, int h, ImVec4 color)
CanvasConfig & GetConfig()
void DrawBackground(ImVec2 canvas_size=ImVec2(0, 0), std::optional< ImVec2 > viewport_size=std::nullopt)
void DrawGrid(float grid_step=64.0f, int tile_id_offset=8)
static float GetHexInputWidth()
static std::string ShowSaveFileDialog(const std::string &default_name="", const std::string &default_extension="")
ShowSaveFileDialog opens a save file dialog and returns the selected filepath. Uses global feature fl...
static std::string ShowOpenFileDialog()
ShowOpenFileDialog opens a file dialog and returns the selected filepath. Uses global feature flag to...
uint64_t Revision(uint16_t sheet) const
static const SpriteOamLayout * GetLayout(uint8_t sprite_id)
Get the OAM layout for a sprite ID.
static const SpriteOamLayout * GetPreviewOverride(uint8_t sprite_id, std::string_view hack_name)
#define ICON_MD_MEETING_ROOM
#define ICON_MD_FOLDER_OPEN
#define ICON_MD_PLAY_ARROW
#define ICON_MD_SKIP_NEXT
#define ICON_MD_SKIP_PREVIOUS
#define HOVER_HINT(string)
zelda3::GfxSheetInventoryOptions BuildGfxSheetInventoryOptions(const project::YazeProject *project)
int ParseIntOrDefault(const std::string &text, int fallback=0)
void EnsureSpritePreviewBitmapReady(gfx::Bitmap &bmp, int width, int height, int depth, const std::vector< uint8_t > &gfx_buffer)
int StepFrameIndex(int current, int delta, int frame_count)
void PublishSpritePreviewPixels(gfx::Bitmap &bmp)
std::vector< int > FrameTiles8x8(const zsprite::Frame &frame)
gfx::PaletteGroup SpritePalettesFromCgram(const std::array< SDL_Color, 256 > &cgram)
gfx::PaletteGroup DefaultSpritePreviewPalettes(const gfx::PaletteGroup &global, const gfx::PaletteGroup &aux1, const gfx::PaletteGroup &aux2, const gfx::PaletteGroup &aux3)
int OffsetX(const zsprite::OamTile &tile)
bool Advance(const zsprite::AnimationGroup &animation, size_t frame_count, float delta, int &frame, float &remainder)
absl::StatusOr< gfx::PaletteGroup > BindPaletteRows(const project::SpriteAssetBinding &binding, const gfx::PaletteGroup &defaults, const gfx::PaletteGroup &global, const gfx::PaletteGroup &aux1, const gfx::PaletteGroup &aux2, const gfx::PaletteGroup &aux3)
int OffsetY(const zsprite::OamTile &tile)
constexpr size_t kMaxFrames
bool AppendFrame(zsprite::ZSprite &sprite, int copy_from=-1)
zsprite::Frame CopyVanillaLayout(const zelda3::SpriteOamLayout &layout)
bool DeleteFrame(zsprite::ZSprite &sprite, int index)
absl::StatusOr< GraphicsEditContext > Make(const zsprite::Frame &frame, int frame_index, int oam_index, const std::array< uint8_t, 8 > &slots, const gfx::PaletteGroup &palettes, const zelda3::GameData *owner, const std::string &source_label, const std::string &sheet_source)
absl::StatusOr< usage_preview::PreviewImage > RenderCapturedFrame(const zsprite::Frame &frame, const std::array< uint8_t, 8 > &slots, const gfx::PaletteGroup &palettes, const zelda3::GameData *owner)
absl::StatusOr< std::vector< uint8_t > > Resolve(const project::SpriteGraphicsSource &source, uint16_t sheet, const zelda3::GameData *data, const Rom *rom, const std::filesystem::path &project_directory)
constexpr ImGuiTabItemFlags kSpriteTabFlags
constexpr ImGuiTabBarFlags kSpriteTabBarFlags
ImGuiID GetID(const std::string &id)
void AutoRegisterLastItem(const std::string &widget_type, const std::string &explicit_label, const std::string &description)
Automatically register the last ImGui item.
bool BeginThemedTabBar(const char *id, ImGuiTabBarFlags flags)
A stylized tab bar with "Mission Control" branding.
bool InputHexByte(const char *label, uint8_t *data, float input_width, bool no_step)
std::string HexByte(uint8_t byte, HexStringParams params)
constexpr int kNumDungeonRooms
GfxGroupUsage FindSpritesetUsage(int spriteset, const std::map< int, OverworldAreaGfxInfo > &areas, const std::map< int, RoomGfxInfo > &rooms)
Room LoadRoomHeaderFromRom(Rom *rom, int room_id)
std::map< int, OverworldAreaGfxInfo > CollectOverworldAreaGfx(Rom &rom, GameData *game_data)
constexpr uint16_t kDungeonSpritesetBase
std::map< int, RoomGfxInfo > CollectRoomGfx(const Rom &rom)
const std::string kSpriteDefaultNames[256]
constexpr uint32_t kNumSpritesets
constexpr bool IsUnderworldSpriteset(int spriteset)
Dungeon rooms use spritesets 0x40-0x8F (room header value + 0x40).
std::array< uint8_t, 8 > SpriteSheetSlots(const std::array< uint8_t, 4 > &spriteset_values, bool underworld)
The eight sheets for a spriteset's four values.
std::array< SDL_Color, 256 > BuildDungeonSpriteRenderPalette(const Room &room, const GameData *game_data)
std::vector< SpriteTileIssue > CheckSpriteTiles(const Rom &rom, const std::vector< int > &tiles, const std::array< uint8_t, 8 > &slots, const std::set< uint16_t > &reserved_sheets)
#define RETURN_IF_ERROR(expr)
WorkspaceWindowManager * window_manager
Snapshot of a custom ZSprite's editable state for undo/redo.
project::SpriteAssetBinding binding
zsprite::ZSprite sprite_data
int current_animation_index
std::vector< Frame > Frames
void Reset()
Reset all sprite data to defaults.
absl::Status Load(const std::string &filename)
Load a ZSM file from disk.
std::vector< AnimationGroup > animations
PaletteGroup sprites_aux1
PaletteGroup sprites_aux2
PaletteGroup sprites_aux3
PaletteGroup global_sprites
auto palette(int i) const
const SnesPalette & palette_ref(int i) const
void SelectableLabelWithNameEdit(bool selected, const std::string &type, const std::string &key, const std::string &defaultValue)
std::array< uint8_t, 8 > sheets
std::vector< SpriteAssetBinding > sprite_assets
std::string GetAbsolutePath(const std::string &relative_path) const
std::array< std::array< uint8_t, 4 >, kNumSpritesets > spriteset_ids
gfx::PaletteGroupMap palette_groups
GraphicsSheetStore sheet_store
Complete OAM layout for a vanilla sprite.