-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathWL4EditorWindow.cpp
2488 lines (2256 loc) · 92.1 KB
/
WL4EditorWindow.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "WL4EditorWindow.h"
#include "SettingsUtils.h"
#include "Themes.h"
#include "ROMUtils.h"
#include "FileIOUtils.h"
#include "Operation.h"
#include "Dialog/SpritesEditorDialog.h"
#include "Dialog/PatchManagerDialog.h"
#include "Dialog/GraphicManagerDialog.h"
#include "Dialog/AnimatedTileGroupEditorDialog.h"
#include "Dialog/WallPaintEditorDialog.h"
#include "ui_WL4EditorWindow.h"
#include <cstdio>
#include <deque>
#include <QCloseEvent>
#include <QFileDialog>
#include <QGraphicsScene>
#include <QMessageBox>
#include <QTextEdit>
#include <QSizePolicy>
#include <algorithm>
// Variables used by WL4EditorWindow
bool editModeWidgetInitialized = false;
// Global variables
struct DialogParams::PassageAndLevelIndex selectedLevel = { 0, 0 };
WL4EditorWindow *singleton;
/// <summary>
/// Construct the instance of the WL4EditorWindow.
/// </summary>
/// <remarks>
/// The graphics view is hardcoded to scale at 2x size.
/// </remarks>
/// <param name="parent">
/// The parent QWidget.
/// </param>
WL4EditorWindow::WL4EditorWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::WL4EditorWindow)
{
// Render Themes
int themeId = SettingsUtils::GetKey(SettingsUtils::IniKeys::EditorThemeId).toInt();
QApplication::setStyle("fusion");
QApplication::setPalette(namedColorSchemePalette(static_cast<ThemeColorType>(themeId)));
ui->setupUi(this);
singleton = this;
// MainWindow UI Initialization
ui->graphicsView->scale(graphicViewScalerate, graphicViewScalerate);
statusBarLabel = new QLabel(tr("Open a ROM file"));
statusBarLabel_MousePosition = new QLabel();
statusBarLabel_rectselectMode = new QLabel(tr("Rect Select: Off"));
statusBarLabel_Scalerate = new QLabel(tr("scale rate: ") + QString::number(graphicViewScalerate) + "00%");
statusBarLabel->setMargin(3);
statusBarLabel_MousePosition->setMargin(3);
statusBarLabel_rectselectMode->setMargin(3);
statusBarLabel_Scalerate->setMargin(3);
ui->statusBar->addWidget(statusBarLabel);
ui->statusBar->addWidget(statusBarLabel_rectselectMode);
ui->statusBar->addWidget(statusBarLabel_Scalerate);
ui->statusBar->addWidget(statusBarLabel_MousePosition);
switch (themeId) {
case 0:
{ ui->actionLight->setChecked(true); break; }
case 1:
{ ui->actionDark->setChecked(true); break; }
}
ui->actionRolling_Save->setChecked(SettingsUtils::GetKey(SettingsUtils::IniKeys::RollingSaveLimit).toInt());
// Create DockWidgets
EditModeWidget = new EditModeDockWidget();
Tile16SelecterWidget = new Tile16DockWidget();
EntitySetWidget = new EntitySetDockWidget();
CameraControlWidget = new CameraControlDockWidget();
OutputWidget = new OutputDockWidget();
// Add Recent ROM QAction according to the INI file
InitRecentFileMenuEntries();
InitRecentFileMenuEntries(true);
// Memory Initialization
memset(ROMUtils::animatedTileGroups, 0, sizeof(ROMUtils::animatedTileGroups) / sizeof(ROMUtils::animatedTileGroups[0]));
memset(ROMUtils::singletonTilesets, 0, sizeof(ROMUtils::singletonTilesets) / sizeof(ROMUtils::singletonTilesets[0]));
memset(ROMUtils::entitiessets, 0, sizeof(ROMUtils::entitiessets) / sizeof(ROMUtils::entitiessets[0]));
memset(ROMUtils::entities, 0, sizeof(ROMUtils::entities) / sizeof(ROMUtils::entities[0]));
}
/// <summary>
/// Deconstruct the WL4EditorWindow and clean up its instance objects on the heap.
/// </summary>
WL4EditorWindow::~WL4EditorWindow()
{
// Clean up heap instance objects
delete ui;
delete Tile16SelecterWidget;
delete EditModeWidget;
delete OutputWidget;
delete EntitySetWidget;
delete CameraControlWidget;
delete statusBarLabel;
delete statusBarLabel_MousePosition;
delete statusBarLabel_rectselectMode;
delete statusBarLabel_Scalerate;
// Decomstruct all Tileset singletons
for(int i = 0; i < (sizeof(ROMUtils::animatedTileGroups) / sizeof(ROMUtils::animatedTileGroups[0])); i++)
{
delete ROMUtils::animatedTileGroups[i];
ROMUtils::animatedTileGroups[i] = nullptr;
}
for(int i = 0; i < (sizeof(ROMUtils::singletonTilesets) / sizeof(ROMUtils::singletonTilesets[0])); i++)
{
delete ROMUtils::singletonTilesets[i];
ROMUtils::singletonTilesets[i] = nullptr;
}
for(int i = 0; i < (sizeof(ROMUtils::entitiessets) / sizeof(ROMUtils::entitiessets[0])); i++)
{
delete ROMUtils::entitiessets[i];
ROMUtils::entitiessets[i] = nullptr;
}
for(int i = 0; i < (sizeof(ROMUtils::entities) / sizeof(ROMUtils::entities[0])); i++)
{
delete ROMUtils::entities[i];
ROMUtils::entities[i] = nullptr;
}
ResetUndoHistory();
DeleteUndoHistoryGlobal();
if (CurrentLevel)
{
delete CurrentLevel;
}
if (ROMUtils::ROMFileMetadata->ROMDataPtr)
{
delete[] ROMUtils::ROMFileMetadata->ROMDataPtr;
}
}
/// <summary>
/// Set the text of the status bar.
/// </summary>
/// <remarks>
/// The QLabel for the status bar is on the heap, and the old one is deleted when changing the text.
/// </remarks>
/// <param name="str">
/// The string contents to put in the status bar.
/// </param>
void WL4EditorWindow::SetStatusBarText(char *str)
{
QLabel *old = (QLabel *) ui->statusBar->children()[0];
QLabel *newStr = new QLabel(str);
ui->statusBar->removeWidget(old);
ui->statusBar->addWidget(newStr);
delete old;
}
/// <summary>
/// Perform the UI operations which must be done after loading a room.
/// </summary>
/// <remarks>
/// Set the text for the selected room.
/// Set the text for the selected level in the status bar.
/// Fully re-render the screen.
/// </remarks>
void WL4EditorWindow::LoadRoomUIUpdate()
{
// Set the text for which room is currently loaded, near the top of the editor window
char tmpStr[30];
unsigned int currentroomid = ui->spinBox_RoomID->value();
// Set the text for which level is loaded, near the bottom of the editor window
sprintf(tmpStr, "Level ID: %d-%d", selectedLevel._PassageIndex, selectedLevel._LevelIndex);
statusBarLabel->setText(tmpStr);
ui->roomDecreaseButton->setEnabled(currentroomid);
ui->roomIncreaseButton->setEnabled(CurrentLevel->GetRooms().size() > currentroomid + 1);
// Set the max and min for room id spinbox
ui->spinBox_RoomID->setMinimum(0);
ui->spinBox_RoomID->setMaximum(CurrentLevel->GetRooms().size() - 1);
// Render the screen
RenderScreenFull();
SetEditModeDockWidgetLayerEditability();
}
int WL4EditorWindow::GetCurrentRoomId()
{
return ui->spinBox_RoomID->value();
}
/// <summary>
/// Present the user with an "open file" dialog, and perform necessary level loading actions if a ROM in successfully
/// loaded.
/// </summary>
/// <remarks>
/// Load the ROM file into CurrentFile.
/// Set the title of the main window.
/// Load level 0-0.
/// Render room 0 of the level.
/// On first successful ROM load, add and update UI that requires a ROM to have been loaded.
/// </remarks>
void WL4EditorWindow::OpenROM()
{
// Check for unsaved operations
if (!UnsavedChangesPrompt(tr("There are unsaved changes. Discard changes and load ROM anyway?")))
return;
// Select a ROM file to open
QString openROMFileInitPath = SettingsUtils::GetKey(SettingsUtils::IniKeys::OpenRomInitPath);
QString qFilePath =
QFileDialog::getOpenFileName(this, tr("Open ROM file"), openROMFileInitPath, tr("GBA ROM files (*.gba)"));
if (!qFilePath.compare(""))
{
return;
}
LoadROMDataFromFile(qFilePath);
}
/// <summary>
/// Load ROM data from a file into the editor's data structures
/// </summary>
/// <remarks>
/// This is a helper function to prevent duplication of code from multiple ways a ROM file can be loaded
/// </remarks>
/// <param name="filePath">
/// The path of the ROM file
/// </param>
void WL4EditorWindow::LoadROMDataFromFile(QString qFilePath)
{
// Load the ROM file
std::string filePath = qFilePath.toStdString();
if (QString errorMessage = FileIOUtils::LoadROMFile(qFilePath); !errorMessage.isEmpty())
{
QMessageBox::critical(nullptr, QString(tr("Load Error")), QString(errorMessage));
return;
}
dialogInitialPath = QFileInfo(qFilePath).dir().path();
SettingsUtils::SetKey(SettingsUtils::IniKeys::OpenRomInitPath, dialogInitialPath);
// Clean-up
if (CurrentLevel)
{
delete CurrentLevel;
// Decomstruct all LevelComponents singletons
for(int i = 0; i < (sizeof(ROMUtils::animatedTileGroups) / sizeof(ROMUtils::animatedTileGroups[0])); i++)
{
delete ROMUtils::animatedTileGroups[i];
ROMUtils::animatedTileGroups[i] = nullptr;
}
for(int i = 0; i < (sizeof(ROMUtils::singletonTilesets) / sizeof(ROMUtils::singletonTilesets[0])); i++)
{
delete ROMUtils::singletonTilesets[i];
ROMUtils::singletonTilesets[i] = nullptr;
}
for(int i = 0; i < (sizeof(ROMUtils::entitiessets) / sizeof(ROMUtils::entitiessets[0])); i++)
{
delete ROMUtils::entitiessets[i];
ROMUtils::entitiessets[i] = nullptr;
}
for(int i = 0; i < (sizeof(ROMUtils::entities) / sizeof(ROMUtils::entities[0])); i++)
{
delete ROMUtils::entities[i];
ROMUtils::entities[i] = nullptr;
}
ResetUndoHistory();
DeleteUndoHistoryGlobal();
ResetGlobalElementOperationIndexes();
}
// Load the Project settings
SettingsUtils::LoadProjectSettings();
// Set the program title
std::string fileName = filePath.substr(filePath.rfind('/') + 1);
setWindowTitle(fileName.c_str());
// Load all LevelComponents singletons
for(int i = 0; i < (sizeof(ROMUtils::animatedTileGroups) / sizeof(ROMUtils::animatedTileGroups[0])); i++)
{
int animatedTileGroupHeaderAddr = WL4Constants::AnimatedTileHeaderTable + i * 8;
ROMUtils::animatedTileGroups[i] = new LevelComponents::AnimatedTile8x8Group(animatedTileGroupHeaderAddr, i);
}
for(int i = 0; i < (sizeof(ROMUtils::singletonTilesets) / sizeof(ROMUtils::singletonTilesets[0])); i++)
{
int tilesetPtr = WL4Constants::TilesetDataTable + i * 36;
ROMUtils::singletonTilesets[i] = new LevelComponents::Tileset(tilesetPtr, i);
}
for (unsigned int i = 0; i < sizeof(ROMUtils::entities) / sizeof(ROMUtils::entities[0]); ++i)
{
// TODO: the palette param should be loaded differently for different passages for gem palette
ROMUtils::entities[i] = new LevelComponents::Entity(i, WL4Constants::UniversalSpritesPalette);
}
for (unsigned int i = 0; i < sizeof(ROMUtils::entitiessets) / sizeof(ROMUtils::entitiessets[0]); ++i)
{
ROMUtils::entitiessets[i] = new LevelComponents::EntitySet(i);
}
UnsavedChanges = false;
UIStartUp();
}
/// <summary>
/// Print Mouse Pos in the status bar
/// </summary>
/// <param name="x">
/// Mouse x position in scaled pixels
/// </param>
/// <param name="y">
/// Mouse y position in scaled pixels
/// </param>
void WL4EditorWindow::PrintMousePos(int x, int y)
{
int selectedLayer = EditModeWidget->GetEditModeParams().selectedLayer;
LevelComponents::Layer *layer = CurrentLevel->GetRooms()[ui->spinBox_RoomID->value()]->GetLayer(selectedLayer);
int tileSize;
if(layer->GetMappingType() == LevelComponents::LayerMappingType::LayerDisabled)
{
statusBarLabel_MousePosition->setText(tr("Selected layer is disabled!"));
return;
}
int is8x8 = layer->GetMappingType() == LevelComponents::LayerMappingType::LayerTile8x8;
tileSize = is8x8 ? 8 : 16;
int xBound = (x /= tileSize) < layer->GetLayerWidth();
int yBound = (y /= tileSize) < layer->GetLayerHeight();
QString offset_text = "";
if(!is8x8)
{
offset_text = tr(" Positional offset (y * width + x): 0x%1").arg(layer->GetLayerWidth() * y + x, 4, 16, QChar('0'));
}
if(xBound && yBound)
{
statusBarLabel_MousePosition->setText(QString("Mouse position (Hex): Layer %0 (%1, %2, %3)").arg(
QString::number(selectedLayer),
QString(is8x8 ? "Tile8x8" : "Map16"),
"0x" + QString::number(x, 16),
"0x" + QString::number(y, 16)) + offset_text);
}
else
{
statusBarLabel_MousePosition->setText(tr("Mouse out of range!"));
}
}
/// <summary>
/// Set graphicView scalerate.
/// </summary>
void WL4EditorWindow::SetGraphicViewScalerate(uint scalerate)
{
ui->graphicsView->scale((qreal)scalerate / (qreal)graphicViewScalerate, (qreal)scalerate / (qreal)graphicViewScalerate);
graphicViewScalerate = scalerate;
statusBarLabel_MousePosition->setText(tr("Move your mouse to show position again!"));
statusBarLabel_Scalerate->setText(tr("Scale rate: ") + QString::number(graphicViewScalerate) + "00%");
}
/// <summary>
/// Show the rect select state in the main graphic view.
/// </summary>
/// <param name="state">
/// The toggle state of rect select
/// </param>
void WL4EditorWindow::RefreshRectSelectHint(bool state)
{
statusBarLabel_rectselectMode->setText(QString(tr("Rectangle Select: ")) + (state ? tr("On") : tr("Off")));
}
/// <summary>
/// Unset the rect select state in the main graphic view.
/// </summary>
/// <param name="state">
/// The toggle state of rect select
/// </param>
void WL4EditorWindow::SetRectSelectMode(bool state)
{
ui->actionRect_Select_Mode->setChecked(state);
}
/// <summary>
/// Get the pointer of the main graphic view.
/// </summary>
QGraphicsView *WL4EditorWindow::Getgraphicview()
{
return ui->graphicsView;
}
/// <summary>
/// Set enable for buttons to go to a different room.
/// </summary>
/// <param name="state">
/// The toggle state of rect select
/// </param>
void WL4EditorWindow::SetChangeCurrentRoomEnabled(bool state)
{
if (state) {
unsigned int currentroomid = ui->spinBox_RoomID->value();
if (currentroomid)
ui->roomDecreaseButton->setEnabled(state);
if (currentroomid < (CurrentLevel->GetRooms().size() - 1))
ui->roomIncreaseButton->setEnabled(state);
} else {
ui->roomDecreaseButton->setEnabled(state);
ui->roomIncreaseButton->setEnabled(state);
}
}
/// <summary>
/// Set current room.
/// </summary>
/// <param name="roomid">
/// The new room's id.
/// </param>
void WL4EditorWindow::SetCurrentRoomId(int roomid, bool call_from_spinbox_valuechange)
{
// enable or disable those buttons
if (!roomid)
ui->roomDecreaseButton->setEnabled(false);
else
ui->roomDecreaseButton->setEnabled(true);
int currentRoomMaxId = CurrentLevel->GetRooms().size() - 1;
if (roomid == currentRoomMaxId)
ui->roomIncreaseButton->setEnabled(false);
else if (roomid < currentRoomMaxId)
ui->roomIncreaseButton->setEnabled(true);
// Deselect rect
// SetRectSelectMode(ui->actionRect_Select_Mode->isChecked());
// Deselect Door and Entity
ui->graphicsView->DeselectDoorAndEntity(false);
ui->graphicsView->ResetRectPixmaps();
ui->graphicsView->ResetRect();
// Load the room
if (call_from_spinbox_valuechange == false) ui->spinBox_RoomID->setValue(roomid);
LoadRoomUIUpdate();
int tmpTilesetID = CurrentLevel->GetRooms()[roomid]->GetTilesetID();
Tile16SelecterWidget->SetTileset(tmpTilesetID);
ResetEntitySetDockWidget();
ResetCameraControlDockWidget();
}
/// <summary>
/// Helper function to edit current Tileset by opening a Tileset Editor dialog
/// </summary>
void WL4EditorWindow::EditCurrentTileset(DialogParams::TilesetEditParams *_newTilesetEditParams)
{
// Show the dialog
TilesetEditDialog dialog(this, _newTilesetEditParams);
if (dialog.exec() == QDialog::Accepted)
{
int currentTilesetId = _newTilesetEditParams->currentTilesetIndex;
int tilesetPtr = WL4Constants::TilesetDataTable + currentTilesetId * 36;
DialogParams::TilesetEditParams *_oldRoomTilesetEditParams = new DialogParams::TilesetEditParams();
_oldRoomTilesetEditParams->currentTilesetIndex = currentTilesetId;
_oldRoomTilesetEditParams->newTileset = ROMUtils::singletonTilesets[currentTilesetId];
_newTilesetEditParams->newTileset->setTilesetPtr(tilesetPtr);
_newTilesetEditParams->newTileset->SetChanged(true);
// Execute Operation and add changes into the operation history
OperationParams *operation = new OperationParams;
operation->type = ChangeTilesetOperation;
operation->TilesetChange = true;
operation->lastTilesetEditParams = _oldRoomTilesetEditParams;
operation->newTilesetEditParams = _newTilesetEditParams;
ExecuteOperationGlobal(operation); // Set UnsavedChanges bool inside
}
else
{
delete _newTilesetEditParams->newTileset;
delete _newTilesetEditParams;
}
}
/// <summary>
/// Update the UI after loading a ROM.
/// </summary>
void WL4EditorWindow::UIStartUp()
{
// Only modify UI on the first time a ROM is loaded
if (!firstROMLoaded)
{
firstROMLoaded = true;
// Enable UI that requires a ROM file to be loaded
ui->actionSave_ROM->setEnabled(true);
if (!SettingsUtils::GetKey(SettingsUtils::IniKeys::RollingSaveLimit).toInt())
{
ui->actionSave_As->setEnabled(true);
}
ui->actionSave_Room_s_graphic->setEnabled(true);
ui->menuImport_from_ROM->setEnabled(true);
ui->actionUndo->setEnabled(true);
ui->actionRedo->setEnabled(true);
ui->actionUndo_global->setEnabled(true);
ui->actionRedo_global->setEnabled(true);
ui->actionLevel_Config->setEnabled(true);
ui->actionRoom_Config->setEnabled(true);
ui->actionEdit_Animated_Tile_Groups->setEnabled(true);
ui->actionEdit_Tileset->setEnabled(true);
ui->actionEdit_Credits->setEnabled(true);
ui->menuAdd->setEnabled(true);
ui->menuDuplicate->setEnabled(true);
ui->menuEntity_lists_2->setEnabled(true);
ui->menuSwap->setEnabled(true);
ui->menuClear->setEnabled(true);
ui->menu_clear_Layer->setEnabled(true);
ui->menu_clear_Entity_list->setEnabled(true);
ui->actionClear_all->setEnabled(true);
ui->actionPatch_Manager->setEnabled(true);
ui->actionGraphic_Manager->setEnabled(true);
ui->actionEdit_Entity_EntitySet->setEnabled(true);
ui->actionRun_from_file->setEnabled(true);
ui->menuRecent_Script->setEnabled(true);
ui->loadLevelButton->setEnabled(true);
ui->actionReload_project_settings->setEnabled(true);
ui->actionEdit_Wall_Paints->setEnabled(true);
ui->spinBox_RoomID->setEnabled(true);
// Load Dock widget
addDockWidget(Qt::RightDockWidgetArea, EditModeWidget);
addDockWidget(Qt::RightDockWidgetArea, Tile16SelecterWidget);
addDockWidget(Qt::RightDockWidgetArea, EntitySetWidget);
addDockWidget(Qt::RightDockWidgetArea, CameraControlWidget);
addDockWidget(Qt::BottomDockWidgetArea, OutputWidget);
CameraControlWidget->setVisible(false);
EntitySetWidget->setVisible(false);
}
// Modify Recent ROM menu
ManageRecentFilesOrScripts(ROMUtils::ROMFileMetadata->FilePath);
// Load the first level and render the screen, also set up the UI
selectedLevel._PassageIndex = SettingsUtils::GetKey(static_cast<SettingsUtils::IniKeys>(SettingsUtils::IniKeys::RecentROM_0_RecentPassage_id)).toInt();
selectedLevel._LevelIndex = SettingsUtils::GetKey(static_cast<SettingsUtils::IniKeys>(SettingsUtils::IniKeys::RecentROM_0_RecentLevel_id)).toInt();
CurrentLevel = new LevelComponents::Level(static_cast<enum LevelComponents::__passage>(selectedLevel._PassageIndex),
static_cast<enum LevelComponents::__stage>(selectedLevel._LevelIndex));
ui->spinBox_RoomID->setValue(SettingsUtils::GetKey(static_cast<SettingsUtils::IniKeys>(SettingsUtils::IniKeys::RecentROM_0_RecentRoom_id)).toInt());
unsigned int currentroomid = ui->spinBox_RoomID->value();
int tmpTilesetID = CurrentLevel->GetRooms()[currentroomid]->GetTilesetID();
auto currentroom = CurrentLevel->GetRooms()[currentroomid];
EntitySetWidget->ResetEntitySet(currentroom);
Tile16SelecterWidget->SetTileset(tmpTilesetID);
CameraControlWidget->PopulateCameraControlInfo(currentroom);
// UI update
LoadRoomUIUpdate();
}
/// <summary>
/// Set whether the the UI elements for WL4Editor are enabled, based on layer properties.
/// </summary>
void WL4EditorWindow::SetEditModeDockWidgetLayerEditability()
{
auto currentroom = CurrentLevel->GetRooms()[ui->spinBox_RoomID->value()];
bool layer0enable = currentroom->GetLayer(0)->IsEnabled();
EditModeWidget->SetLayersCheckBoxEnabled(0, layer0enable);
EditModeWidget->SetLayersCheckBoxEnabled(1, currentroom->GetLayer(1)->IsEnabled());
EditModeWidget->SetLayersCheckBoxEnabled(2, currentroom->GetLayer(2)->IsEnabled());
EditModeWidget->SetLayersCheckBoxEnabled(3, currentroom->GetLayer(3)->IsEnabled());
EditModeWidget->SetLayersCheckBoxEnabled(7, currentroom->IsLayer0ColorBlendingEnabled());
}
/// <summary>
/// Deselect doors or entities that are currently selected.
/// </summary>
void WL4EditorWindow::Graphicsview_UnselectDoorAndEntity() { ui->graphicsView->DeselectDoorAndEntity(true); }
/// <summary>
/// Reset the Room with a new/old RoomConfigParams.
/// </summary>
/// <param name="currentroomconfig">
/// The current RoomConfigParams which can be made by the current Room.
/// </param>
/// <param name="nextroomconfig">
/// The next RoomConfigParams which you want to apply to the current Room.
/// </param>
void WL4EditorWindow::RoomConfigReset(DialogParams::RoomConfigParams *currentroomconfig,
DialogParams::RoomConfigParams *nextroomconfig)
{
// Apply the selected parameters to the current room
// reset the Tileset instance in Room class
LevelComponents::Room *currentRoom = CurrentLevel->GetRooms()[ui->spinBox_RoomID->value()];
if (nextroomconfig->CurrentTilesetIndex != currentroomconfig->CurrentTilesetIndex)
{
currentRoom->SetTileset(ROMUtils::singletonTilesets[nextroomconfig->CurrentTilesetIndex], nextroomconfig->CurrentTilesetIndex);
Tile16SelecterWidget->SetTileset(nextroomconfig->CurrentTilesetIndex);
}
// update the Layer 0. 1. 2, 3 instances
// Layer 0
if (nextroomconfig->Layer0MappingTypeParam > 0xF && nextroomconfig->Layer0MappingTypeParam < 0x20)
{
currentRoom->GetLayer(0)->SetWidthHeightData(nextroomconfig->Layer0Width, nextroomconfig->Layer0Height, nextroomconfig->LayerData[0]);
}
else if (nextroomconfig->Layer0MappingTypeParam < 0x10)
{
currentRoom->GetLayer(0)->SetDisabled();
}
else // if (currentroomconfig->Layer0MappingTypeParam > 0x1F)
{
LevelComponents::Layer *currentLayer0 = currentRoom->GetLayer(0);
delete currentLayer0;
currentLayer0 = new LevelComponents::Layer(nextroomconfig->Layer0DataPtr, LevelComponents::LayerTile8x8);
currentRoom->SetLayer(0, currentLayer0);
}
// Layer 1
currentRoom->GetLayer(1)->SetWidthHeightData(nextroomconfig->RoomWidth, nextroomconfig->RoomHeight, nextroomconfig->LayerData[1]);
// Layer 2
if (nextroomconfig->Layer2MappingTypeParam > 0xF)
{
currentRoom->GetLayer(2)->SetWidthHeightData(nextroomconfig->RoomWidth, nextroomconfig->RoomHeight, nextroomconfig->LayerData[2]);
} else // if (currentroomconfig->Layer2MappingTypeParam < 0x10)
{
currentRoom->GetLayer(2)->SetDisabled();
}
// Layer 3
if (nextroomconfig->BackgroundLayerEnable)
{
LevelComponents::Layer *currentLayer3 = currentRoom->GetLayer(3);
delete currentLayer3;
currentLayer3 = new LevelComponents::Layer(nextroomconfig->BackgroundLayerDataPtr, LevelComponents::LayerTile8x8);
currentRoom->SetLayer(3, currentLayer3);
}
else if (!nextroomconfig->BackgroundLayerEnable)
{
currentRoom->GetLayer(3)->SetDisabled();
}
// Need to modify the inside doors, entities, camera boxes when Room size changed
if (nextroomconfig->RoomWidth != currentroomconfig->RoomWidth ||
nextroomconfig->RoomHeight != currentroomconfig->RoomHeight)
{
// Deal with out-of-range Doors, Entities, Camera limitators
// TODO: support Undo/Redo on these elements
// -- Door --
int nxtRoomWidth = nextroomconfig->RoomWidth, nxtRoomHeight = nextroomconfig->RoomHeight;
LevelComponents::LevelDoorVector &allDoor = CurrentLevel->GetDoorListRef();
int doornum = allDoor.size();
for (int i = doornum - 1; i > 0; i--)
{
auto curDoor = allDoor.GetDoor(i);
if (curDoor.RoomID == currentRoom->GetRoomID()) // if the door is in the current Room
{
// if the Door top left Tile is out of bound
if (curDoor.x1 > (nxtRoomWidth - 1) || curDoor.y1 > (nxtRoomHeight - 1))
{
if (curDoor.DoorTypeByte == LevelComponents::_Portal)
{
allDoor.SetDoorPlace(i, 2, 2, 2, 2); // move the portal Door to the top left corner of the Room
}
else
{
CurrentLevel->DeleteDoorByGlobalID(i); // delete all the out-of-bound non-portal Door
}
}
}
}
// -- Entity --
for (uint i = 0; i < 3; i++)
{
std::vector<struct LevelComponents::EntityRoomAttribute> entitylist = currentRoom->GetEntityListData(i);
size_t entitynum = entitylist.size();
for (uint j = entitynum; j > 0; j--)
{
if ((entitylist[j - 1].XPos > (nxtRoomWidth - 1)) || (entitylist[j - 1].YPos > (nxtRoomHeight - 1)))
{
currentRoom->DeleteEntity(i, j - 1);
currentRoom->SetEntityListDirty(i, true);
}
}
}
// -- Camera limitator --
std::vector<struct LevelComponents::__CameraControlRecord *> limitatorlist =
currentRoom->GetCameraControlRecords(false);
size_t limitatornum = limitatorlist.size();
size_t k = limitatornum - 1;
uint *deleteLimitatorIdlist = new uint[limitatornum](); // set them all 0, index the limitator from 1
for (uint i = 0; i < limitatornum; i++)
{
int x2_prime =
(limitatorlist[i]->ChangeValueOffset == 1) ? (limitatorlist[i]->ChangedValue) : (limitatorlist[i]->x2);
int y2_prime =
(limitatorlist[i]->ChangeValueOffset == 3) ? (limitatorlist[i]->ChangedValue) : (limitatorlist[i]->y2);
if ((x2_prime >= nxtRoomWidth) || (y2_prime >= nxtRoomHeight))
{
deleteLimitatorIdlist[k--] = i + 1; // the id list will be something like: 0 0 0 8 4 2
}
}
for (uint i = 0; i < limitatornum; i++)
{
if (deleteLimitatorIdlist[i] != 0)
{
currentRoom->DeleteCameraLimitator(deleteLimitatorIdlist[i] - 1);
}
}
delete[] deleteLimitatorIdlist;
}
// reset all the Parameters in Room class, except new layer data pointers, generate them on saving
currentRoom->SetLayer0MappingParam(nextroomconfig->Layer0MappingTypeParam);
currentRoom->SetRenderEffectFlag(nextroomconfig->LayerPriorityAndAlphaAttr);
currentRoom->SetLayer2MappingType(nextroomconfig->Layer2MappingTypeParam);
currentRoom->SetBGLayerEnabled(nextroomconfig->BackgroundLayerEnable);
currentRoom->SetBGLayerScrollFlag(nextroomconfig->BGLayerScrollFlag);
currentRoom->SetLayerGFXEffect01(nextroomconfig->RasterType);
currentRoom->SetLayerGFXEffect02(nextroomconfig->Water);
currentRoom->SetBgmvolume(nextroomconfig->BGMVolume);
// Mark the layers as dirty
for (unsigned int i = 0; i < 3; ++i)
currentRoom->GetLayer(i)->SetDirty(true);
}
/// <summary>
/// Delete a Door from the current Level.
/// </summary>
/// <param name="globalDoorIndex">
/// The global Door id given by current Level.
/// </param>
bool WL4EditorWindow::DeleteDoor(int globalDoorIndex)
{
if (!CurrentLevel->DeleteDoorByGlobalID(globalDoorIndex))
{
OutputWidget->PrintString(tr("Cannot Delete the current Door!\nYou cannot delete a portal Door or the last Door in a Room!"));
return false;
}
return true;
}
/// <summary>
/// Slot function to load a ROM.
/// </summary>
void WL4EditorWindow::openRecentROM()
{
// Check for unsaved operations
if(!UnsavedChangesPrompt(tr("There are unsaved changes. Discard changes and load ROM anyway?"))) return;
QString filepath;
QAction *action = qobject_cast<QAction *>(sender());
if(action)
{
filepath = action->text();
}
// check if the file loaded from the recent file record still exist
// manage the QAction list if it needs changes
if (!OpenRecentFile(filepath)) return;
LoadROMDataFromFile(filepath);
}
/// <summary>
/// Slot function to load and execute a js script.
/// </summary>
void WL4EditorWindow::openRecentScript()
{
QString filepath;
QAction *action = qobject_cast<QAction *>(sender());
if(action)
{
filepath = action->text();
}
// check if the file loaded from the recent file record still exist
// manage the QAction list if it needs changes
if (!OpenRecentFile(filepath, true)) return;
// Modify Recent Script menu
ManageRecentFilesOrScripts(filepath, true);
QFile file(filepath);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::critical(this, tr("Error"), tr("Can't open file."));
return;
}
QString code = QString::fromUtf8(file.readAll());
OutputWidget->ExecuteJSScript(code);
}
/// <summary>
/// Call the OpenROM function when the action for it is triggered in the main window.
/// </summary>
void WL4EditorWindow::on_actionOpen_ROM_triggered()
{
OpenROM();
}
/// <summary>
/// Perform a full render of the currently selected room.
/// </summary>
void WL4EditorWindow::RenderScreenFull()
{
// Delete the old scene, if it exists
QGraphicsScene *oldScene = ui->graphicsView->scene();
if (oldScene)
{
delete oldScene;
}
ui->graphicsView->ClearRectPointer();
// Perform a full render of the screen
struct LevelComponents::RenderUpdateParams renderParams(LevelComponents::FullRender);
renderParams.mode = EditModeWidget->GetEditModeParams();
renderParams.SelectedDoorID = (unsigned int) ui->graphicsView->GetSelectedDoorID();
LevelComponents::Room *curRoom = this->GetCurrentRoom();
renderParams.localDoors = CurrentLevel->GetRoomDoorVec(curRoom->GetRoomID());
QGraphicsScene *scene = curRoom->RenderGraphicsScene(ui->graphicsView->scene(), &renderParams);
ui->graphicsView->setScene(scene);
ui->graphicsView->setAlignment(Qt::AlignTop | Qt::AlignLeft);
}
/// <summary>
/// Perform a re-render of the currently selected room, if only layer visibility has been toggled.
/// </summary>
void WL4EditorWindow::RenderScreenVisibilityChange()
{
struct LevelComponents::RenderUpdateParams renderParams(LevelComponents::LayerEnable);
renderParams.mode = EditModeWidget->GetEditModeParams();
LevelComponents::Room *curRoom = this->GetCurrentRoom();
renderParams.localDoors = CurrentLevel->GetRoomDoorVec(curRoom->GetRoomID());
QGraphicsScene *scene = curRoom->RenderGraphicsScene(ui->graphicsView->scene(), &renderParams);
ui->graphicsView->setScene(scene);
ui->graphicsView->setAlignment(Qt::AlignTop | Qt::AlignLeft);
}
/// <summary>
/// Perform a re-render of the Door/Camera limitation rectangle/Entity layer.
/// </summary>
void WL4EditorWindow::RenderScreenElementsLayersUpdate(unsigned int DoorId, int EntityId)
{
struct LevelComponents::RenderUpdateParams renderParams(LevelComponents::ElementsLayersUpdate);
renderParams.mode = EditModeWidget->GetEditModeParams();
renderParams.SelectedDoorID = DoorId;
renderParams.SelectedEntityID = EntityId;
LevelComponents::Room *curRoom = this->GetCurrentRoom();
renderParams.localDoors = CurrentLevel->GetRoomDoorVec(curRoom->GetRoomID());
QGraphicsScene *scene = curRoom->RenderGraphicsScene(ui->graphicsView->scene(), &renderParams);
ui->graphicsView->setScene(scene);
ui->graphicsView->setAlignment(Qt::AlignTop | Qt::AlignLeft);
}
/// <summary>
/// Perform a re-render of multiple tiles changes.
/// </summary>
void WL4EditorWindow::RenderScreenTilesChange(QVector<LevelComponents::Tileinfo> tilelist, int LayerID)
{
struct LevelComponents::RenderUpdateParams renderParams(LevelComponents::TileChanges);
renderParams.mode = EditModeWidget->GetEditModeParams();
renderParams.mode.selectedLayer = LayerID;
renderParams.tilechangelist = tilelist;
LevelComponents::Room *curRoom = this->GetCurrentRoom();
renderParams.localDoors = CurrentLevel->GetRoomDoorVec(curRoom->GetRoomID());
curRoom->RenderGraphicsScene(ui->graphicsView->scene(), &renderParams);
}
/// <summary>
/// Override the close window functionality so that a save prompt is offered if there are unsaved changes.
/// </summary>
/// <param name="event">
/// Close window event information.
/// </param>
void WL4EditorWindow::closeEvent(QCloseEvent *event)
{
if (UnsavedChanges)
{
// Show save prompt
QMessageBox savePrompt;
savePrompt.setWindowTitle(tr("Unsaved changes"));
savePrompt.setText(tr("There are unsaved changes. Discard changes and quit anyway?"));
QPushButton *quitButton = savePrompt.addButton(tr("Discard"), QMessageBox::DestructiveRole);
QPushButton *cancelButton = savePrompt.addButton(tr("Cancel"), QMessageBox::NoRole);
QPushButton *saveButton = savePrompt.addButton(tr("Save"), QMessageBox::ApplyRole);
QPushButton *saveAsButton = savePrompt.addButton(tr("Save As"), QMessageBox::ApplyRole);
savePrompt.setDefaultButton(cancelButton);
savePrompt.exec();
if (savePrompt.clickedButton() == quitButton)
{
event->accept();
return;
}
else if (savePrompt.clickedButton() == saveButton)
{
// Do not exit if there was an issue saving the file
if (!SaveCurrentFile())
{
event->ignore();
return;
}
}
else if (savePrompt.clickedButton() == saveAsButton)
{
// Do not exit if the file cannot be saved, or the user cancels the save prompt
if (!SaveCurrentFileAs())
{
event->ignore();
return;
}
}
else
{
// If cancel is clicked, or X is clicked on the save prompt, then do nothing
event->ignore();
return;
}
}
// No unsaved changes (quit)
event->accept();
}
bool WL4EditorWindow::SaveCurrentFile()
{
bool result = ROMUtils::SaveLevel(ROMUtils::ROMFileMetadata->FilePath);
if (result)
{
int array_recent_room_start_id = SettingsUtils::IniKeys::RecentROM_0_RecentRoom_id;
int array_recent_level_start_id = SettingsUtils::IniKeys::RecentROM_0_RecentLevel_id;
int array_recent_passage_start_id = SettingsUtils::IniKeys::RecentROM_0_RecentPassage_id;
SettingsUtils::SetKey(static_cast<SettingsUtils::IniKeys>(array_recent_level_start_id), QString::number(selectedLevel._LevelIndex));
SettingsUtils::SetKey(static_cast<SettingsUtils::IniKeys>(array_recent_room_start_id), QString::number(ui->spinBox_RoomID->value()));
SettingsUtils::SetKey(static_cast<SettingsUtils::IniKeys>(array_recent_passage_start_id), QString::number(selectedLevel._PassageIndex));
}
return result;
}
/// <summary>
/// Present the user with an "open level" dialog, in which a level can be selected to load.
/// </summary>
/// <remarks>
/// The newly loaded level will start by loading room 0 into the editor.
/// </remarks>
void WL4EditorWindow::on_loadLevelButton_clicked()
{
// Check for unsaved operations
if (!UnsavedChangesPrompt(tr("There are unsaved changes. Discard changes and load level anyway?")))
return;
// Deselect Door and Entity and deselect rect
ui->graphicsView->DeselectDoorAndEntity(false);
ui->graphicsView->ResetRectPixmaps();
ui->graphicsView->ResetRect();
// Load the selected level and render the screen
ChooseLevelDialog tmpdialog(selectedLevel);
if (tmpdialog.exec() == QDialog::Accepted)
{
selectedLevel = tmpdialog.GetResult();
if (CurrentLevel)
delete CurrentLevel;
CurrentLevel =
new LevelComponents::Level(static_cast<enum LevelComponents::__passage>(selectedLevel._PassageIndex),
static_cast<enum LevelComponents::__stage>(selectedLevel._LevelIndex));
ui->spinBox_RoomID->setValue(0);
LoadRoomUIUpdate();
int tmpTilesetID = CurrentLevel->GetRooms()[ui->spinBox_RoomID->value()]->GetTilesetID();
Tile16SelecterWidget->SetTileset(tmpTilesetID);
ResetEntitySetDockWidget();
ResetCameraControlDockWidget();
// Set program control changes
UnsavedChanges = false;
ResetUndoHistory();
}
}
/// <summary>
/// Provide the user with a choice whether or not to save the ROM if there are unsaved changes.
/// </summary>
/// <param name="str">
/// The message to display in the save prompt.
/// </param>
/// <returns>
/// True if the user chose to continue with the save prompt.
/// </returns>
bool WL4EditorWindow::UnsavedChangesPrompt(QString str)
{
if (UnsavedChanges)
{
// Show save prompt
QMessageBox savePrompt;
savePrompt.setWindowTitle(tr("Unsaved changes"));
savePrompt.setText(str);
QPushButton *discardButton = savePrompt.addButton(tr("Discard"), QMessageBox::DestructiveRole);
QPushButton *cancelButton = savePrompt.addButton(tr("Cancel"), QMessageBox::NoRole);
QPushButton *saveButton = savePrompt.addButton(tr("Save"), QMessageBox::ApplyRole);
savePrompt.setDefaultButton(cancelButton);
savePrompt.exec();
if (savePrompt.clickedButton() == saveButton)
{