yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
polyhedral_editor_panel.cc
Go to the documentation of this file.
2
3#include <algorithm>
4#include <cmath>
5#include <string>
6#include <vector>
7
8#include "absl/status/status.h"
9#include "absl/status/statusor.h"
10#include "absl/strings/str_format.h"
11#include "app/gui/core/icons.h"
14#include "imgui/imgui.h"
15#include "implot.h"
16#include "rom/snes.h"
17#include "util/macro.h"
18
19namespace yaze {
20namespace editor {
21
22namespace {
23
24constexpr uint32_t kPolyTableSnes = 0x09FF8C;
25constexpr uint32_t kPolyEntrySize = 6;
26constexpr uint32_t kPolyRegionSize = 0x74; // 116 bytes, $09:FF8C-$09:FFFF
27constexpr uint8_t kPolyBank = 0x09;
28
29constexpr ImVec4 kVertexColor(0.3f, 0.8f, 1.0f, 1.0f);
30constexpr ImVec4 kSelectedVertexColor(1.0f, 0.75f, 0.2f, 1.0f);
31
32template <typename T>
33T Clamp(T value, T min_v, T max_v) {
34 return std::max(min_v, std::min(max_v, value));
35}
36
37std::string ShapeNameForIndex(int index) {
38 switch (index) {
39 case 0:
40 return "Crystal";
41 case 1:
42 return "Triforce";
43 default:
44 return absl::StrFormat("Shape %d", index);
45 }
46}
47
48uint32_t ToPc(uint16_t bank_offset) {
49 return SnesToPc((kPolyBank << 16) | bank_offset);
50}
51
52} // namespace
53
55 return SnesToPc(kPolyTableSnes);
56}
57
60 dirty_ = false;
61 return absl::OkStatus();
62}
63
65 if (!rom_ || !rom_->is_loaded()) {
66 return absl::FailedPreconditionError("ROM is not loaded");
67 }
68
69 // Read the whole 3D object region to keep parsing bounds explicit.
70 ASSIGN_OR_RETURN(auto region,
71 rom_->ReadByteVector(TablePc(), kPolyRegionSize));
72
73 shapes_.clear();
74
75 // Two entries live in the table (crystal, triforce). Stop if we run out of
76 // room rather than reading garbage.
77 for (int i = 0; i < 2; ++i) {
78 size_t base = i * kPolyEntrySize;
79 if (base + kPolyEntrySize > region.size()) {
80 break;
81 }
82
83 PolyShape shape;
84 shape.name = ShapeNameForIndex(i);
85 shape.vertex_count = region[base];
86 shape.face_count = region[base + 1];
87 shape.vertex_ptr =
88 static_cast<uint16_t>(region[base + 2] | (region[base + 3] << 8));
89 shape.face_ptr =
90 static_cast<uint16_t>(region[base + 4] | (region[base + 5] << 8));
91
92 // Vertices (signed bytes, XYZ triples)
93 const uint32_t vertex_pc = ToPc(shape.vertex_ptr);
94 const size_t vertex_bytes = static_cast<size_t>(shape.vertex_count) * 3;
95 ASSIGN_OR_RETURN(auto vertex_blob,
96 rom_->ReadByteVector(vertex_pc, vertex_bytes));
97
98 shape.vertices.reserve(shape.vertex_count);
99 for (size_t idx = 0; idx + 2 < vertex_blob.size(); idx += 3) {
100 PolyVertex v;
101 v.x = static_cast<int8_t>(vertex_blob[idx]);
102 v.y = static_cast<int8_t>(vertex_blob[idx + 1]);
103 v.z = static_cast<int8_t>(vertex_blob[idx + 2]);
104 shape.vertices.push_back(v);
105 }
106
107 // Faces (count byte, indices[count], shade byte)
108 uint32_t face_pc = ToPc(shape.face_ptr);
109 shape.faces.reserve(shape.face_count);
110 for (int f = 0; f < shape.face_count; ++f) {
111 ASSIGN_OR_RETURN(auto count_byte, rom_->ReadByte(face_pc++));
112 PolyFace face;
113 face.vertex_indices.reserve(count_byte);
114
115 for (int j = 0; j < count_byte; ++j) {
116 ASSIGN_OR_RETURN(auto idx_byte, rom_->ReadByte(face_pc++));
117 face.vertex_indices.push_back(idx_byte);
118 }
119
120 ASSIGN_OR_RETURN(auto shade_byte, rom_->ReadByte(face_pc++));
121 face.shade = shade_byte;
122 shape.faces.push_back(std::move(face));
123 }
124
125 shapes_.push_back(std::move(shape));
126 }
127
128 selected_shape_ = 0;
130 data_loaded_ = true;
131 return absl::OkStatus();
132}
133
135 for (auto& shape : shapes_) {
136 shape.vertex_count = static_cast<uint8_t>(shape.vertices.size());
137 shape.face_count = static_cast<uint8_t>(shape.faces.size());
139 }
140 dirty_ = false;
141 return absl::OkStatus();
142}
143
145 // Vertices
146 std::vector<uint8_t> vertex_blob;
147 vertex_blob.reserve(shape.vertices.size() * 3);
148 for (const auto& v : shape.vertices) {
149 vertex_blob.push_back(static_cast<uint8_t>(static_cast<int8_t>(v.x)));
150 vertex_blob.push_back(static_cast<uint8_t>(static_cast<int8_t>(v.y)));
151 vertex_blob.push_back(static_cast<uint8_t>(static_cast<int8_t>(v.z)));
152 }
153
155 rom_->WriteVector(ToPc(shape.vertex_ptr), std::move(vertex_blob)));
156
157 // Faces
158 std::vector<uint8_t> face_blob;
159 for (const auto& face : shape.faces) {
160 face_blob.push_back(static_cast<uint8_t>(face.vertex_indices.size()));
161 for (auto idx : face.vertex_indices) {
162 face_blob.push_back(idx);
163 }
164 face_blob.push_back(face.shade);
165 }
166
167 return rom_->WriteVector(ToPc(shape.face_ptr), std::move(face_blob));
168}
169
170void PolyhedralEditorPanel::Draw(bool* p_open) {
171 // EditorPanel interface - delegate to existing Update() logic
172 if (!rom_ || !rom_->is_loaded()) {
173 ImGui::TextUnformatted("Load a ROM to edit 3D objects.");
174 return;
175 }
176
177 if (!data_loaded_) {
178 auto status = LoadShapes();
179 if (!status.ok()) {
180 ImGui::TextColored(ImVec4(1.0f, 0.3f, 0.3f, 1.0f),
181 "Failed to load shapes: %s", status.message().data());
182 return;
183 }
184 }
185
187
188 ImGui::Text("ALTTP polyhedral data @ $09:%04X (PC $%05X), %u bytes",
189 static_cast<uint16_t>(kPolyTableSnes & 0xFFFF), TablePc(),
190 kPolyRegionSize);
191 ImGui::TextUnformatted(
192 "Shapes: 0 = Crystal, 1 = Triforce (IDs used by POLYSHAPE)");
193
194 // Shape selector
195 if (!shapes_.empty()) {
196 ImGui::SetNextItemWidth(gui::LayoutHelpers::GetStandardInputWidth());
197 if (ImGui::BeginCombo("Shape", shapes_[selected_shape_].name.c_str())) {
198 for (size_t i = 0; i < shapes_.size(); ++i) {
199 bool selected = static_cast<int>(i) == selected_shape_;
200 if (ImGui::Selectable(shapes_[i].name.c_str(), selected)) {
201 selected_shape_ = static_cast<int>(i);
203 }
204 }
205 ImGui::EndCombo();
206 }
207 }
208
209 if (ImGui::Button(ICON_MD_REFRESH " Reload from ROM")) {
210 auto status = LoadShapes();
211 if (!status.ok()) {
212 ImGui::TextColored(ImVec4(1.0f, 0.3f, 0.3f, 1.0f), "Reload failed: %s",
213 status.message().data());
214 }
215 }
216 ImGui::SameLine();
217 ImGui::BeginDisabled(!dirty_);
218 if (ImGui::Button(ICON_MD_SAVE " Save 3D objects")) {
219 auto status = SaveShapes();
220 if (!status.ok()) {
221 ImGui::TextColored(ImVec4(1.0f, 0.3f, 0.3f, 1.0f), "Save failed: %s",
222 status.message().data());
223 }
224 }
225 ImGui::EndDisabled();
226
227 if (shapes_.empty()) {
228 ImGui::TextUnformatted("No polyhedral shapes found.");
229 return;
230 }
231
232 ImGui::Separator();
234}
235
237 if (!rom_ || !rom_->is_loaded()) {
238 ImGui::TextUnformatted("Load a ROM to edit 3D objects.");
239 return absl::OkStatus();
240 }
241
242 if (!data_loaded_) {
244 }
245
247
248 ImGui::Text("ALTTP polyhedral data @ $09:%04X (PC $%05X), %u bytes",
249 static_cast<uint16_t>(kPolyTableSnes & 0xFFFF), TablePc(),
250 kPolyRegionSize);
251 ImGui::TextUnformatted(
252 "Shapes: 0 = Crystal, 1 = Triforce (IDs used by POLYSHAPE)");
253
254 // Shape selector
255 if (!shapes_.empty()) {
256 ImGui::SetNextItemWidth(gui::LayoutHelpers::GetStandardInputWidth());
257 if (ImGui::BeginCombo("Shape", shapes_[selected_shape_].name.c_str())) {
258 for (size_t i = 0; i < shapes_.size(); ++i) {
259 bool selected = static_cast<int>(i) == selected_shape_;
260 if (ImGui::Selectable(shapes_[i].name.c_str(), selected)) {
261 selected_shape_ = static_cast<int>(i);
263 }
264 }
265 ImGui::EndCombo();
266 }
267 }
268
269 if (ImGui::Button(ICON_MD_REFRESH " Reload from ROM")) {
271 }
272 ImGui::SameLine();
273 ImGui::BeginDisabled(!dirty_);
274 if (ImGui::Button(ICON_MD_SAVE " Save 3D objects")) {
276 }
277 ImGui::EndDisabled();
278
279 if (shapes_.empty()) {
280 ImGui::TextUnformatted("No polyhedral shapes found.");
281 return absl::OkStatus();
282 }
283
284 ImGui::Separator();
286 return absl::OkStatus();
287}
288
290 ImGui::Text("Vertices: %u Faces: %u", shape.vertex_count, shape.face_count);
291 ImGui::Text("Vertex data @ $09:%04X (PC $%05X)", shape.vertex_ptr,
292 ToPc(shape.vertex_ptr));
293 ImGui::Text("Face data @ $09:%04X (PC $%05X)", shape.face_ptr,
294 ToPc(shape.face_ptr));
295
296 ImGui::Spacing();
297
298 if (ImGui::BeginTable(
299 "##poly_editor", 2,
300 ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingStretchProp)) {
301 ImGui::TableSetupColumn("Data", ImGuiTableColumnFlags_WidthStretch, 0.45f);
302 ImGui::TableSetupColumn("Plots", ImGuiTableColumnFlags_WidthStretch, 0.55f);
303
304 ImGui::TableNextColumn();
305 DrawVertexList(shape);
306 ImGui::Spacing();
307 DrawFaceList(shape);
308
309 ImGui::TableNextColumn();
310 DrawPlot("XY (X vs Y)", PlotPlane::kXY, shape);
311 DrawPlot("XZ (X vs Z)", PlotPlane::kXZ, shape);
312 ImGui::Spacing();
313 DrawPreview(shape);
314 ImGui::EndTable();
315 }
316}
317
319 if (shape.vertices.empty()) {
320 ImGui::TextUnformatted("No vertices");
321 return;
322 }
323
324 for (size_t i = 0; i < shape.vertices.size(); ++i) {
325 ImGui::PushID(static_cast<int>(i));
326 const bool is_selected = static_cast<int>(i) == selected_vertex_;
327 std::string label = absl::StrFormat("Vertex %zu", i);
328 if (ImGui::Selectable(label.c_str(), is_selected)) {
329 selected_vertex_ = static_cast<int>(i);
330 }
331
332 ImGui::SameLine();
333 ImGui::SetNextItemWidth(
335 int coords[3] = {shape.vertices[i].x, shape.vertices[i].y,
336 shape.vertices[i].z};
337 if (ImGui::InputInt3("##coords", coords)) {
338 shape.vertices[i].x = Clamp(coords[0], -127, 127);
339 shape.vertices[i].y = Clamp(coords[1], -127, 127);
340 shape.vertices[i].z = Clamp(coords[2], -127, 127);
341 dirty_ = true;
342 }
343 ImGui::PopID();
344 }
345}
346
348 if (shape.faces.empty()) {
349 ImGui::TextUnformatted("No faces");
350 return;
351 }
352
353 ImGui::TextUnformatted("Faces (vertex indices + shade)");
354 for (size_t i = 0; i < shape.faces.size(); ++i) {
355 ImGui::PushID(static_cast<int>(i));
356 ImGui::Text("Face %zu", i);
357 ImGui::SameLine();
358 int shade = shape.faces[i].shade;
359 ImGui::SetNextItemWidth(gui::LayoutHelpers::GetCompactInputWidth());
360 if (ImGui::InputInt("Shade##face", &shade, 0, 0)) {
361 shape.faces[i].shade = static_cast<uint8_t>(Clamp(shade, 0, 0xFF));
362 dirty_ = true;
363 }
364
365 ImGui::SameLine();
366 ImGui::TextUnformatted("Vertices:");
367 const int max_idx = shape.vertices.empty()
368 ? 0
369 : static_cast<int>(shape.vertices.size() - 1);
370 for (size_t v = 0; v < shape.faces[i].vertex_indices.size(); ++v) {
371 ImGui::SameLine();
372 int idx = shape.faces[i].vertex_indices[v];
373 ImGui::SetNextItemWidth(
375 if (ImGui::InputInt(absl::StrFormat("##v%zu", v).c_str(), &idx, 0, 0)) {
376 idx = Clamp(idx, 0, max_idx);
377 shape.faces[i].vertex_indices[v] = static_cast<uint8_t>(idx);
378 dirty_ = true;
379 }
380 }
381 ImGui::PopID();
382 }
383}
384
385void PolyhedralEditorPanel::DrawPlot(const char* label, PlotPlane plane,
386 PolyShape& shape) {
387 if (shape.vertices.empty()) {
388 return;
389 }
390
391 ImVec2 plot_size = ImVec2(-1, 220);
392 ImPlotFlags flags = ImPlotFlags_NoLegend | ImPlotFlags_Equal;
393 if (ImPlot::BeginPlot(label, plot_size, flags)) {
394 const char* x_label = (plane == PlotPlane::kYZ) ? "Y" : "X";
395 const char* y_label = (plane == PlotPlane::kXY) ? "Y" : "Z";
396 ImPlot::SetupAxes(x_label, y_label, ImPlotAxisFlags_AutoFit,
397 ImPlotAxisFlags_AutoFit);
398 ImPlot::SetupAxisLimits(ImAxis_X1, -80, 80, ImGuiCond_Once);
399 ImPlot::SetupAxisLimits(ImAxis_Y1, -80, 80, ImGuiCond_Once);
400
401 for (size_t i = 0; i < shape.vertices.size(); ++i) {
402 double x = shape.vertices[i].x;
403 double y = 0.0;
404 switch (plane) {
405 case PlotPlane::kXY:
406 y = shape.vertices[i].y;
407 break;
408 case PlotPlane::kXZ:
409 y = shape.vertices[i].z;
410 break;
411 case PlotPlane::kYZ:
412 x = shape.vertices[i].y;
413 y = shape.vertices[i].z;
414 break;
415 }
416
417 const bool is_selected = static_cast<int>(i) == selected_vertex_;
418 ImVec4 color = is_selected ? kSelectedVertexColor : kVertexColor;
419 // ImPlot::DragPoint wants an int ID, so compose one from vertex index and plane.
420 int point_id = static_cast<int>(i * 10 + static_cast<size_t>(plane));
421 if (ImPlot::DragPoint(point_id, &x, &y, color, 6.0f)) {
422 // Round so we keep integer coordinates in ROM
423 int rounded_x = Clamp(static_cast<int>(std::lround(x)), -127, 127);
424 int rounded_y = Clamp(static_cast<int>(std::lround(y)), -127, 127);
425
426 switch (plane) {
427 case PlotPlane::kXY:
428 shape.vertices[i].x = rounded_x;
429 shape.vertices[i].y = rounded_y;
430 break;
431 case PlotPlane::kXZ:
432 shape.vertices[i].x = rounded_x;
433 shape.vertices[i].z = rounded_y;
434 break;
435 case PlotPlane::kYZ:
436 shape.vertices[i].y = rounded_x;
437 shape.vertices[i].z = rounded_y;
438 break;
439 }
440
441 dirty_ = true;
442 if (!is_selected) {
443 selected_vertex_ = static_cast<int>(i);
444 }
445 }
446 }
447 ImPlot::EndPlot();
448 }
449}
450
452 if (shape.vertices.empty() || shape.faces.empty()) {
453 return;
454 }
455
456 static float rot_x = 0.35f;
457 static float rot_y = -0.4f;
458 static float rot_z = 0.0f;
459 static float zoom = 1.0f;
460
461 ImGui::TextUnformatted("Preview (orthographic)");
462 ImGui::SetNextItemWidth(gui::LayoutHelpers::GetComboWidth());
463 ImGui::SliderFloat("Rot X", &rot_x, -3.14f, 3.14f, "%.2f");
464 ImGui::SameLine();
465 ImGui::SetNextItemWidth(gui::LayoutHelpers::GetComboWidth());
466 ImGui::SliderFloat("Rot Y", &rot_y, -3.14f, 3.14f, "%.2f");
467 ImGui::SameLine();
468 ImGui::SetNextItemWidth(gui::LayoutHelpers::GetComboWidth());
469 ImGui::SliderFloat("Rot Z", &rot_z, -3.14f, 3.14f, "%.2f");
470 ImGui::SameLine();
471 ImGui::SetNextItemWidth(gui::LayoutHelpers::GetSliderWidth());
472 ImGui::SliderFloat("Zoom", &zoom, 0.5f, 3.0f, "%.2f");
473
474 // Precompute rotated vertices
475 struct RotV {
476 double x;
477 double y;
478 double z;
479 };
480 std::vector<RotV> rotated(shape.vertices.size());
481
482 const double cx = std::cos(rot_x);
483 const double sx = std::sin(rot_x);
484 const double cy = std::cos(rot_y);
485 const double sy = std::sin(rot_y);
486 const double cz = std::cos(rot_z);
487 const double sz = std::sin(rot_z);
488
489 for (size_t i = 0; i < shape.vertices.size(); ++i) {
490 const auto& v = shape.vertices[i];
491 double x = v.x;
492 double y = v.y;
493 double z = v.z;
494
495 // Rotate around X
496 double y1 = y * cx - z * sx;
497 double z1 = y * sx + z * cx;
498 // Rotate around Y
499 double x2 = x * cy + z1 * sy;
500 double z2 = -x * sy + z1 * cy;
501 // Rotate around Z
502 double x3 = x2 * cz - y1 * sz;
503 double y3 = x2 * sz + y1 * cz;
504
505 rotated[i] = {x3 * zoom, y3 * zoom, z2 * zoom};
506 }
507
508 struct FaceDepth {
509 double depth;
510 size_t idx;
511 };
512 std::vector<FaceDepth> order;
513 order.reserve(shape.faces.size());
514 for (size_t i = 0; i < shape.faces.size(); ++i) {
515 double accum = 0.0;
516 for (auto idx : shape.faces[i].vertex_indices) {
517 if (idx < rotated.size()) {
518 accum += rotated[idx].z;
519 }
520 }
521 double avg =
522 shape.faces[i].vertex_indices.empty()
523 ? 0.0
524 : accum / static_cast<double>(shape.faces[i].vertex_indices.size());
525 order.push_back({avg, i});
526 }
527
528 std::sort(order.begin(), order.end(),
529 [](const FaceDepth& a, const FaceDepth& b) {
530 return a.depth < b.depth; // back to front
531 });
532
533 ImVec2 preview_size(-1, 260);
534 ImPlotFlags flags = ImPlotFlags_NoLegend | ImPlotFlags_Equal;
535 if (ImPlot::BeginPlot("PreviewXY", preview_size, flags)) {
536 ImPlot::SetupAxes(nullptr, nullptr, ImPlotAxisFlags_NoDecorations,
537 ImPlotAxisFlags_NoDecorations);
538 ImPlot::SetupAxisLimits(ImAxis_X1, -120, 120, ImGuiCond_Always);
539 ImPlot::SetupAxisLimits(ImAxis_Y1, -120, 120, ImGuiCond_Always);
540
541 ImDrawList* dl = ImPlot::GetPlotDrawList();
542 ImVec4 base_color = ImVec4(0.8f, 0.9f, 1.0f, 0.55f);
543
544 for (const auto& fd : order) {
545 const auto& face = shape.faces[fd.idx];
546 if (face.vertex_indices.size() < 3) {
547 continue;
548 }
549
550 std::vector<ImVec2> pts;
551 pts.reserve(face.vertex_indices.size());
552
553 for (auto idx : face.vertex_indices) {
554 if (idx >= rotated.size()) {
555 continue;
556 }
557 ImVec2 p = ImPlot::PlotToPixels(rotated[idx].x, rotated[idx].y);
558 pts.push_back(p);
559 }
560
561 if (pts.size() < 3) {
562 continue;
563 }
564
565 ImU32 fill_col = ImGui::GetColorU32(base_color);
566 ImU32 line_col = ImGui::GetColorU32(ImVec4(0.2f, 0.4f, 0.6f, 1.0f));
567 dl->AddConvexPolyFilled(pts.data(), static_cast<int>(pts.size()),
568 fill_col);
569 dl->AddPolyline(pts.data(), static_cast<int>(pts.size()), line_col,
570 ImDrawFlags_Closed, 2.0f);
571 }
572
573 // Draw vertices as dots
574 for (size_t i = 0; i < rotated.size(); ++i) {
575 ImVec2 p = ImPlot::PlotToPixels(rotated[i].x, rotated[i].y);
576 ImU32 col = ImGui::GetColorU32(kVertexColor);
577 dl->AddCircleFilled(p, 4.0f, col);
578 }
579
580 ImPlot::EndPlot();
581 }
582}
583
584} // namespace editor
585} // namespace yaze
absl::StatusOr< std::vector< uint8_t > > ReadByteVector(uint32_t offset, uint32_t length) const
Definition rom.cc:431
absl::StatusOr< uint8_t > ReadByte(int offset) const
Definition rom.cc:408
absl::Status WriteVector(int addr, std::vector< uint8_t > data)
Definition rom.cc:548
bool is_loaded() const
Definition rom.h:132
void Draw(bool *p_open) override
Draw the polyhedral editor UI (EditorPanel interface)
void DrawPlot(const char *label, PlotPlane plane, PolyShape &shape)
absl::Status WriteShape(const PolyShape &shape)
absl::Status Update()
Legacy Update method for backward compatibility.
static float GetSliderWidth()
static float GetCompactInputWidth()
static float GetStandardInputWidth()
#define ICON_MD_REFRESH
Definition icons.h:1572
#define ICON_MD_SAVE
Definition icons.h:1644
#define ASSIGN_OR_RETURN(type_variable_name, expression)
Definition macro.h:62
constexpr ImVec4 kSelectedVertexColor(1.0f, 0.75f, 0.2f, 1.0f)
constexpr ImVec4 kVertexColor(0.3f, 0.8f, 1.0f, 1.0f)
uint32_t SnesToPc(uint32_t addr) noexcept
Definition snes.h:8
#define RETURN_IF_ERROR(expr)
Definition snes.cc:22
std::vector< uint8_t > vertex_indices
std::vector< PolyFace > faces
std::vector< PolyVertex > vertices