-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
3167 lines (2738 loc) · 129 KB
/
Form1.cs
File metadata and controls
3167 lines (2738 loc) · 129 KB
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
// Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml.Linq;
using System.Xml;
using Formatting = Newtonsoft.Json.Formatting;
namespace mnmVis
{
public partial class Form1 : Form
{
private const string REGISTRY_KEY = @"Software\mnmVis";
private const string REGISTRY_VALUE_DRIVE = "SelectedDrive";
private GameDataManager gameDataManager;
private string streamingAssetsPath = @"E:\SteamLibrary\steamapps\common\Heroes of Might & Magic Olden Era Demo\HeroesOE_Data\StreamingAssets";
private bool isMapView = false;
private List<GameEntity> mapEntities = new List<GameEntity>();
// Navigation history
private List<NavigationEntry> navigationHistory = new List<NavigationEntry>();
private int navigationIndex = -1;
private bool isNavigating = false;
// Search functionality
private List<TreeNode> searchResults = new List<TreeNode>();
private int currentSearchIndex = -1;
// Text search results
private List<TextSearchResult> textSearchResults = new List<TextSearchResult>();
private int currentTextSearchIndex = -1;
private bool isTextSearchMode = false;
// Edit mode
private bool isEditMode = false;
private GameEntity currentEditEntity = null;
private JObject currentEditJObject = null;
private string currentEditFilePath = null;
private string editModeSnapshot = null; // Snapshot of content when entering edit mode
private ListBox autocompleteListBox;
private string lastAutocompleteWord = "";
private class NavigationEntry
{
public TreeNode Node { get; set; }
public string[] NodePath { get; set; } // Path of node texts from root to target
public object NodeTag { get; set; } // The tag (GameEntity, JObject, etc.)
public bool WasMapView { get; set; } // Which view was active
}
public Form1()
{
InitializeComponent();
PopulateDrives();
InitializeAutocomplete();
// Initialize button states - all edit buttons disabled at start
btnEditToggle.Enabled = false;
btnEditToggle.BackColor = SystemColors.ControlDark;
btnEditToggle.ForeColor = SystemColors.GrayText;
btnSaveJson.Enabled = false;
btnSaveJson.BackColor = SystemColors.ControlDark;
btnSaveJson.ForeColor = SystemColors.GrayText;
btnSaveAndClose.Enabled = false;
btnSaveAndClose.BackColor = SystemColors.ControlDark;
btnSaveAndClose.ForeColor = SystemColors.GrayText;
btnRestoreSnapshot.Enabled = false;
btnRestoreSnapshot.BackColor = SystemColors.ControlDark;
btnRestoreSnapshot.ForeColor = SystemColors.GrayText;
btnCancelEdit.Enabled = false;
btnCancelEdit.BackColor = SystemColors.ControlDark;
btnCancelEdit.ForeColor = SystemColors.GrayText;
panelEditButtons.Visible = true; // Always visible
// Setup context menu for richTextBox
SetupRichTextBoxContextMenu();
gameDataManager = new GameDataManager();
LoadGameData();
}
private void SetupRichTextBoxContextMenu()
{
ContextMenuStrip contextMenu = new ContextMenuStrip();
ToolStripMenuItem copyItem = new ToolStripMenuItem("Copy", null, (s, e) => richTextBoxJson.Copy());
copyItem.ShortcutKeys = Keys.Control | Keys.C;
ToolStripMenuItem cutItem = new ToolStripMenuItem("Cut", null, (s, e) => richTextBoxJson.Cut());
cutItem.ShortcutKeys = Keys.Control | Keys.X;
ToolStripMenuItem pasteItem = new ToolStripMenuItem("Paste", null, (s, e) => richTextBoxJson.Paste());
pasteItem.ShortcutKeys = Keys.Control | Keys.V;
ToolStripMenuItem selectAllItem = new ToolStripMenuItem("Select All", null, (s, e) => richTextBoxJson.SelectAll());
selectAllItem.ShortcutKeys = Keys.Control | Keys.A;
contextMenu.Items.AddRange(new ToolStripItem[] { copyItem, cutItem, pasteItem, new ToolStripSeparator(), selectAllItem });
// Enable/disable items based on edit mode
contextMenu.Opening += (s, e) =>
{
copyItem.Enabled = richTextBoxJson.SelectionLength > 0;
cutItem.Enabled = !richTextBoxJson.ReadOnly && richTextBoxJson.SelectionLength > 0;
pasteItem.Enabled = !richTextBoxJson.ReadOnly && Clipboard.ContainsText();
};
richTextBoxJson.ContextMenuStrip = contextMenu;
richTextBoxJson.ShortcutsEnabled = true;
}
private void LoadGameData()
{
try
{
toolStripStatusLabel1.Text = "Loading game data...";
Application.DoEvents();
gameDataManager.LoadAllJsonFiles(streamingAssetsPath);
RefreshMapEntities();
UpdateUI();
toolStripStatusLabel1.Text = $"Loaded {gameDataManager.GetEntityCount()} entities successfully";
}
catch (Exception ex)
{
MessageBox.Show($"Error loading game data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
toolStripStatusLabel1.Text = "Error loading data";
}
}
private void RefreshMapEntities()
{
mapEntities.Clear();
var allEntities = gameDataManager.GetEntitiesByType();
foreach (var kvp in allEntities)
{
foreach (var entity in kvp.Value)
{
if (entity.FilePath.Contains("map_templates") &&
Path.GetFileName(entity.FilePath).EndsWith(".rmg.json", StringComparison.OrdinalIgnoreCase))
{
mapEntities.Add(entity);
}
}
}
}
private void UpdateUI()
{
int entityCount = gameDataManager.GetEntityCount();
lblEntityCount.Text = $"Entities: {entityCount} total | Maps: {mapEntities.Count}";
Text = $"Heroes OE Mod Tool - Loaded {entityCount} entities";
txtPath.Text = streamingAssetsPath;
PopulateEntityTree();
if (entityCount > 0)
{
toolStripStatusLabel1.Text = $"Loaded {entityCount} entities successfully";
}
}
private void btnBrowsePath_Click(object sender, EventArgs e)
{
// Build full path from current drive and path
string currentFullPath = GetFullPath();
folderBrowserDialog1.SelectedPath = currentFullPath;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string selectedPath = folderBrowserDialog1.SelectedPath;
// Extract drive letter and path
if (selectedPath.Length >= 2 && selectedPath[1] == ':')
{
string driveLetter = selectedPath.Substring(0, 2);
string pathWithoutDrive = selectedPath.Substring(2).TrimStart('\\');
// Update drive combo box
for (int i = 0; i < cmbDrive.Items.Count; i++)
{
if (cmbDrive.Items[i].ToString() == driveLetter)
{
cmbDrive.SelectedIndex = i;
break;
}
}
// Update path textbox (without drive)
txtPath.Text = pathWithoutDrive;
}
else
{
txtPath.Text = selectedPath;
}
streamingAssetsPath = GetFullPath();
}
}
private void btnRefresh_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtPath.Text))
{
streamingAssetsPath = GetFullPath();
gameDataManager = new GameDataManager();
mapEntities.Clear();
treeViewEntities.Nodes.Clear();
listViewReferences.BeginUpdate();
try
{
listViewReferences.Items.Clear();
}
finally
{
listViewReferences.EndUpdate();
}
richTextBoxJson.Clear();
lblSelectedEntity.Text = "Select an entity to view details";
isMapView = false;
mapToggle.Text = "Show Maps Only";
// Clear navigation history
navigationHistory.Clear();
navigationIndex = -1;
UpdateNavigationButtons();
LoadGameData();
}
else
{
MessageBox.Show("Please select a valid StreamingAssets folder path.", "Invalid Path", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void mapToggle_Click(object sender, EventArgs e)
{
isMapView = !isMapView;
mapToggle.Text = isMapView ? "Show All Entities" : "Show Maps Only";
PopulateEntityTree();
toolStripStatusLabel1.Text = isMapView ? $"Map view: Showing {mapEntities.Count} maps only" : "All entities view";
}
private void treeViewEntities_AfterSelect(object sender, TreeViewEventArgs e)
{
// Check if we're in edit mode and have unsaved changes
if (isEditMode && !string.IsNullOrEmpty(editModeSnapshot))
{
// Check if content has changed
if (richTextBoxJson.Text != editModeSnapshot)
{
// Ask user what to do
DialogResult result = MessageBox.Show(
"You have unsaved changes. Do you want to save them before switching nodes?",
"Unsaved Changes",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
// Save changes
SaveJsonChanges();
ExitEditMode(false);
}
else if (result == DialogResult.No)
{
// Discard changes
ExitEditMode(false);
}
else // Cancel
{
// Stay in edit mode, prevent node selection change
return;
}
}
else
{
// No changes, just exit edit mode silently
ExitEditMode(false);
}
}
// If we're in map view and clicked on a top-level map entity, DON'T switch to full view
// User wants to stay in map view and explore the map details
if (isMapView && e.Node?.Tag is GameEntity entity)
{
// Check if this is a top-level map node (the map itself, not a zone/connection subitem)
bool isTopLevelMap = false;
if (e.Node.Parent != null && e.Node.Parent.Name.StartsWith("Mode_"))
{
// Direct child of a mode grouping node = top-level map
isTopLevelMap = true;
}
// DON'T switch to full view when clicking map name - stay in map view
// But for zone/connection subitems, switch to full view to see all relationships
if (!isTopLevelMap && !IsMapEntity(entity))
{
// For subitems (zones, connections), switch to full view to see all relationships
isMapView = false;
mapToggle.Text = "Show Maps Only";
// Set navigating flag to prevent adding the intermediate node to history
isNavigating = true;
PopulateEntityTree();
FindAndSelectTreeNode(entity.Id);
isNavigating = false;
toolStripStatusLabel1.Text = "Switched to full view - showing all entities and relationships";
// Now add to history after we've switched views and selected the node
if (e.Node != null)
{
AddToNavigationHistory(e.Node);
}
return;
}
}
// Add to navigation history (unless we're navigating via back/forward buttons)
if (!isNavigating && e.Node != null)
{
AddToNavigationHistory(e.Node);
}
// Display entity details if the node has a GameEntity tag
if (e.Node?.Tag is GameEntity selectedEntity)
{
DisplayEntityDetails(selectedEntity);
}
else if (e.Node?.Tag is JObject jobj)
{
// For JSON objects, find the parent zone/connection entity to show references
GameEntity parentEntity = FindParentEntity(e.Node);
if (parentEntity != null)
{
// Display the JSON object but use parent entity for references
lblSelectedEntity.Text = $"{parentEntity.Type}: {parentEntity.Id} - {e.Node.Text}";
richTextBoxJson.Text = jobj.ToString(Formatting.Indented);
DisplayReferencesForEntity(parentEntity);
}
else
{
// No parent entity, just show JSON
DisplayJsonObject(jobj, e.Node.Text);
}
}
else if (e.Node?.Tag is JArray jarr)
{
// For JSON arrays, find the parent zone/connection entity to show references
GameEntity parentEntity = FindParentEntity(e.Node);
if (parentEntity != null)
{
// Display the JSON array but use parent entity for references
lblSelectedEntity.Text = $"{parentEntity.Type}: {parentEntity.Id} - {e.Node.Text}";
richTextBoxJson.Text = jarr.ToString(Formatting.Indented);
DisplayReferencesForEntity(parentEntity);
}
else
{
// No parent entity, just show JSON
DisplayJsonArray(jarr, e.Node.Text);
}
}
else if (e.Node?.Tag is JToken jtoken)
{
// Display any other JSON token
DisplayJsonToken(jtoken, e.Node.Text);
}
else
{
// For nodes without tags (grouping nodes), disable edit button
btnEditToggle.Enabled = false;
btnEditToggle.BackColor = SystemColors.ControlDark;
btnEditToggle.ForeColor = SystemColors.GrayText;
btnSaveJson.Enabled = false;
btnSaveJson.BackColor = SystemColors.ControlDark;
btnSaveJson.ForeColor = SystemColors.GrayText;
btnSaveAndClose.Enabled = false;
btnSaveAndClose.BackColor = SystemColors.ControlDark;
btnSaveAndClose.ForeColor = SystemColors.GrayText;
btnCancelEdit.Enabled = false;
btnCancelEdit.BackColor = SystemColors.ControlDark;
btnCancelEdit.ForeColor = SystemColors.GrayText;
// Find parent entity to show references
GameEntity parentEntity = FindParentEntity(e.Node);
if (parentEntity != null)
{
lblSelectedEntity.Text = $"{parentEntity.Type}: {parentEntity.Id} - {e.Node.Text}";
richTextBoxJson.Text = $"// {e.Node.Text}\n// This is a grouping node within {parentEntity.Id}. Expand to see subitems.";
DisplayReferencesForEntity(parentEntity);
toolStripStatusLabel1.Text = $"{parentEntity.Type}: {parentEntity.Id} - {e.Node.Text}";
}
else
{
lblSelectedEntity.Text = $"Group: {e.Node.Text}";
richTextBoxJson.Text = $"// {e.Node.Text}\n// This is a grouping node. Expand to see subitems.";
listViewReferences.BeginUpdate();
try
{
listViewReferences.Items.Clear();
}
finally
{
listViewReferences.EndUpdate();
}
toolStripStatusLabel1.Text = $"Group: {e.Node.Text}";
}
RestoreRichTextBoxSize(); // Restore full size for non-editable content
// btnEditToggle.Enabled = false; // Disable edit button for grouping nodes
}
}
private bool IsMapEntity(GameEntity entity)
{
return entity.FilePath.Contains("map_templates") &&
Path.GetFileName(entity.FilePath).EndsWith(".rmg.json", StringComparison.OrdinalIgnoreCase);
}
private void treeViewEntities_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (ModifierKeys == Keys.Alt || ModifierKeys == Keys.Control)
{
treeViewEntities.BeginUpdate();
try
{
treeViewEntities.ExpandAll();
toolStripStatusLabel1.Text = "Expanded all nodes";
}
finally
{
treeViewEntities.EndUpdate();
}
}
}
private void treeViewEntities_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
{
if (ModifierKeys == Keys.Alt || ModifierKeys == Keys.Control)
{
treeViewEntities.BeginUpdate();
try
{
treeViewEntities.CollapseAll();
toolStripStatusLabel1.Text = "Collapsed all nodes";
}
finally
{
treeViewEntities.EndUpdate();
}
}
}
private void treeViewEntities_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (ModifierKeys == Keys.Alt || ModifierKeys == Keys.Control)
{
if (e.X <= 20)
{
treeViewEntities.BeginUpdate();
try
{
if (e.Node.IsExpanded || HasExpandedChildren(e.Node))
{
treeViewEntities.CollapseAll();
toolStripStatusLabel1.Text = "Collapsed all nodes (Ctrl/Alt + Click)";
}
else
{
treeViewEntities.ExpandAll();
toolStripStatusLabel1.Text = "Expanded all nodes (Ctrl/Alt + Click)";
}
}
finally
{
treeViewEntities.EndUpdate();
}
}
}
}
private void btnToggleExpand_Click(object sender, EventArgs e)
{
treeViewEntities.BeginUpdate();
try
{
if (btnToggleExpand.Text == "Collapse All")
{
treeViewEntities.CollapseAll();
btnToggleExpand.Text = "Expand All";
toolStripStatusLabel1.Text = "Collapsed all nodes";
}
else
{
treeViewEntities.ExpandAll();
btnToggleExpand.Text = "Collapse All";
toolStripStatusLabel1.Text = "Expanded all nodes";
}
}
finally
{
treeViewEntities.EndUpdate();
}
}
private bool HasExpandedChildren(TreeNode node)
{
foreach (TreeNode child in node.Nodes)
{
if (child.IsExpanded)
return true;
if (HasExpandedChildren(child))
return true;
}
return false;
}
private void ResizeRichTextBoxForEditing()
{
// Do nothing - buttons are always visible at bottom
}
private void RestoreRichTextBoxSize()
{
// Do nothing - buttons are always visible at bottom
}
private void listViewReferences_SelectedIndexChanged(object sender, EventArgs e)
{
// Defer the actual handling to avoid conflicts with ListView internal processing
BeginInvoke(new Action(() => HandleListViewSelection()));
}
private void HandleListViewSelection()
{
try
{
// Guard against invalid selections
if (listViewReferences.SelectedItems.Count == 0 ||
listViewReferences.SelectedIndices.Count == 0)
{
return;
}
// Validate the selected index is within bounds
int selectedIndex = listViewReferences.SelectedIndices[0];
if (selectedIndex < 0 || selectedIndex >= listViewReferences.Items.Count)
{
return;
}
string entityId = listViewReferences.SelectedItems[0].Text;
// Add current node to history BEFORE navigating away
if (treeViewEntities.SelectedNode != null)
{
AddToNavigationHistory(treeViewEntities.SelectedNode);
}
// Now navigate to the referenced entity
GameEntity referencedEntity = gameDataManager.GetEntity(entityId);
if (referencedEntity != null)
{
// Set navigating flag to prevent adding duplicate history entry
isNavigating = true;
// Find and select the tree node for this entity
bool found = FindAndSelectTreeNode(entityId);
// If not found in current view, might need to switch views
if (!found)
{
// Check if it's a map entity and we're not in map view
if (IsMapEntity(referencedEntity) && !isMapView)
{
isMapView = true;
mapToggle.Text = "Show All Entities";
PopulateEntityTree();
FindAndSelectTreeNode(entityId);
}
else if (!IsMapEntity(referencedEntity) && isMapView)
{
isMapView = false;
mapToggle.Text = "Show Maps Only";
PopulateEntityTree();
FindAndSelectTreeNode(entityId);
}
}
isNavigating = false;
}
}
catch (ArgumentOutOfRangeException)
{
// Silently handle index out of range - likely a timing issue with selection
return;
}
catch (Exception ex)
{
toolStripStatusLabel1.Text = $"Navigation error: {ex.Message}";
}
}
private void PopulateEntityTree()
{
treeViewEntities.Nodes.Clear();
if (isMapView)
{
var maps = gameDataManager.GetMapEntitiesWithDetails();
var mapsByMode = maps.GroupBy(m =>
{
try
{
return m.RawData["gameMode"]?.ToString() ?? "Unknown";
}
catch
{
return "Unknown";
}
}).OrderBy(g => g.Key);
foreach (var modeGroup in mapsByMode)
{
TreeNode modeNode = new TreeNode($"{modeGroup.Key} Maps ({modeGroup.Count()})")
{
Name = $"Mode_{modeGroup.Key}",
ImageIndex = 0,
SelectedImageIndex = 0
};
foreach (var map in modeGroup.OrderBy(x => x.Name))
{
TreeNode mapNode = new TreeNode(map.Name)
{
Tag = map,
Name = map.Id,
ImageIndex = 1,
SelectedImageIndex = 1,
ToolTipText = map.ToolTipText
};
try
{
var zones = map.RawData["variants"]?[0]?["zones"] as JArray;
var connections = map.RawData["variants"]?[0]?["connections"] as JArray;
var contentLists = map.RawData["contentLists"] as JArray;
// Build dictionary of content pools from this map's contentLists
var mapContentPools = new Dictionary<string, GameEntity>();
if (contentLists != null)
{
foreach (var item in contentLists)
{
string itemName = item["name"]?.ToString();
if (!string.IsNullOrEmpty(itemName))
{
var contentEntity = new GameEntity
{
Id = itemName,
Type = "content_pools",
Name = itemName,
FilePath = map.FilePath,
RawData = item as JObject
};
mapContentPools[itemName] = contentEntity;
}
}
}
// Create virtual GameEntity objects for each zone so they can be navigated
var zoneEntities = new Dictionary<string, GameEntity>();
var connectionEntities = new Dictionary<string, GameEntity>();
if (zones != null)
{
foreach (var zone in zones)
{
string zoneName = zone["name"]?.ToString();
if (!string.IsNullOrEmpty(zoneName))
{
var zoneEntity = new GameEntity
{
Id = zoneName, // Use just the zone name as ID so it can be found
Type = "Zone",
Name = zoneName,
FilePath = map.FilePath,
RawData = zone as JObject
};
zoneEntities[zoneName] = zoneEntity;
}
}
}
// Create virtual GameEntity objects for connections
if (connections != null)
{
foreach (var conn in connections)
{
string connName = conn["name"]?.ToString();
if (!string.IsNullOrEmpty(connName))
{
var connEntity = new GameEntity
{
Id = connName, // Connection name as ID
Type = "Connection",
Name = connName,
FilePath = map.FilePath,
RawData = conn as JObject
};
connectionEntities[connName] = connEntity;
}
}
}
// Build references for all virtual entities
var allVirtualEntities = zoneEntities.Values.Concat(connectionEntities.Values).ToList();
foreach (var entity in allVirtualEntities)
{
BuildReferencesForEntity(entity, zoneEntities, connectionEntities);
}
// Add comprehensive zone breakdown
if (zones != null && zones.Count > 0)
{
// Group zones by type for better organization
var spawnZones = zones.Where(z => z["name"]?.ToString()?.StartsWith("Spawn-") == true).ToList();
var treasureZones = zones.Where(z => z["name"]?.ToString()?.StartsWith("Treasure-") == true).ToList();
var otherZones = zones.Where(z => !z["name"]?.ToString()?.StartsWith("Spawn-") == true &&
!z["name"]?.ToString()?.StartsWith("Treasure-") == true).ToList();
// Spawn zones
if (spawnZones.Any())
{
TreeNode spawnNode = new TreeNode($"Spawn Zones ({spawnZones.Count})")
{
ForeColor = Color.DarkGreen
};
foreach (var zone in spawnZones)
{
string zoneName = zone["name"]?.ToString() ?? "Unknown";
var mainObjects = zone["mainObjects"] as JArray;
string objInfo = mainObjects?.Count > 0 ? $" - {mainObjects.Count} objects" : "";
TreeNode zoneNode = new TreeNode($"{zoneName}{objInfo}")
{
ForeColor = Color.DarkGreen
};
// Tag with the actual zone entity
if (zoneEntities.ContainsKey(zoneName))
{
zoneNode.Tag = zoneEntities[zoneName];
zoneNode.ToolTipText = $"Zone: {zoneName}\nLayout: {zone["layout"]}\nSize: {zone["size"]}";
}
// Add zone details as subitems
AddZoneDetails(zoneNode, zone, zoneEntities, mapContentPools);
spawnNode.Nodes.Add(zoneNode);
}
mapNode.Nodes.Add(spawnNode);
}
// Treasure zones
if (treasureZones.Any())
{
TreeNode treasureNode = new TreeNode($"Treasure Zones ({treasureZones.Count})")
{
ForeColor = Color.DarkOrange
};
foreach (var zone in treasureZones)
{
string zoneName = zone["name"]?.ToString() ?? "Unknown";
var mainObjects = zone["mainObjects"] as JArray;
string objInfo = mainObjects?.Count > 0 ? $" - {mainObjects.Count} objects" : "";
TreeNode zoneNode = new TreeNode($"{zoneName}{objInfo}")
{
ForeColor = Color.DarkOrange
};
// Tag with the actual zone entity
if (zoneEntities.ContainsKey(zoneName))
{
zoneNode.Tag = zoneEntities[zoneName];
zoneNode.ToolTipText = $"Zone: {zoneName}\nLayout: {zone["layout"]}\nSize: {zone["size"]}";
}
// Add zone details as subitems
AddZoneDetails(zoneNode, zone, zoneEntities, mapContentPools);
treasureNode.Nodes.Add(zoneNode);
}
mapNode.Nodes.Add(treasureNode);
}
// Other zones
if (otherZones.Any())
{
TreeNode otherNode = new TreeNode($"Other Zones ({otherZones.Count})")
{
ForeColor = Color.Gray
};
foreach (var zone in otherZones)
{
string zoneName = zone["name"]?.ToString() ?? "Unknown";
TreeNode zoneNode = new TreeNode(zoneName)
{
ForeColor = Color.Gray
};
// Tag with the actual zone entity
if (zoneEntities.ContainsKey(zoneName))
{
zoneNode.Tag = zoneEntities[zoneName];
zoneNode.ToolTipText = $"Zone: {zoneName}\nLayout: {zone["layout"]}\nSize: {zone["size"]}";
}
// Add zone details as subitems
AddZoneDetails(zoneNode, zone, zoneEntities, mapContentPools);
otherNode.Nodes.Add(zoneNode);
}
mapNode.Nodes.Add(otherNode);
}
}
// Add detailed road/connection analysis
if (connections != null && connections.Count > 0)
{
// Group connections by type
var roadConnections = connections.Where(c => c["road"]?.ToString() == "True").ToList();
var portalConnections = connections.Where(c => c["connectionType"]?.ToString() == "Portal").ToList();
var directConnections = connections.Where(c => c["connectionType"]?.ToString() == "Direct").ToList();
TreeNode connectionNode = new TreeNode($"Connections ({connections.Count})")
{
ForeColor = Color.Purple
};
// Road network analysis
if (roadConnections.Any())
{
TreeNode roadNode = new TreeNode($"Roads ({roadConnections.Count})")
{
ForeColor = Color.Brown
};
foreach (var road in roadConnections)
{
string roadName = road["name"]?.ToString() ?? "Unnamed";
string roadType = road["connectionType"]?.ToString() ?? "Unknown";
string guardValue = road["guardValue"]?.ToString();
string guardIncrement = road["guardWeeklyIncrement"]?.ToString();
string fromZone = road["from"]?.ToString() ?? "?";
string toZone = road["to"]?.ToString() ?? "?";
TreeNode roadItemNode = new TreeNode($"{roadName} ({fromZone} → {toZone})")
{
ForeColor = Color.Brown,
ToolTipText = $"Type: {roadType}\n{fromZone} → {toZone}\nGuard: {guardValue}\nWeekly Increment: {guardIncrement}"
};
// Add subitems showing the zone endpoints
if (!string.IsNullOrEmpty(fromZone) && fromZone != "?")
{
TreeNode fromNode = new TreeNode($"From: {fromZone}")
{
ForeColor = Color.DarkGreen
};
// Tag with the actual zone entity
if (zoneEntities.ContainsKey(fromZone))
{
fromNode.Tag = zoneEntities[fromZone];
var fromZoneData = zones?.FirstOrDefault(z => z["name"]?.ToString() == fromZone);
if (fromZoneData != null)
{
fromNode.ToolTipText = $"Zone: {fromZone}\nLayout: {fromZoneData["layout"]}\nSize: {fromZoneData["size"]}";
}
}
roadItemNode.Nodes.Add(fromNode);
}
if (!string.IsNullOrEmpty(toZone) && toZone != "?")
{
TreeNode toNode = new TreeNode($"To: {toZone}")
{
ForeColor = Color.DarkOrange
};
// Tag with the actual zone entity
if (zoneEntities.ContainsKey(toZone))
{
toNode.Tag = zoneEntities[toZone];
var toZoneData = zones?.FirstOrDefault(z => z["name"]?.ToString() == toZone);
if (toZoneData != null)
{
toNode.ToolTipText = $"Zone: {toZone}\nLayout: {toZoneData["layout"]}\nSize: {toZoneData["size"]}";
}
}
roadItemNode.Nodes.Add(toNode);
}
roadNode.Nodes.Add(roadItemNode);
}
connectionNode.Nodes.Add(roadNode);
}
// Portal connections
if (portalConnections.Any())
{
TreeNode portalNode = new TreeNode($"Portals ({portalConnections.Count})")
{
ForeColor = Color.Magenta
};
foreach (var portal in portalConnections)
{
string portalName = portal["name"]?.ToString() ?? "Unnamed";
string fromZone = portal["from"]?.ToString() ?? "?";
string toZone = portal["to"]?.ToString() ?? "?";
string guardValue = portal["guardValue"]?.ToString();
string guardIncrement = portal["guardWeeklyIncrement"]?.ToString();
TreeNode portalItemNode = new TreeNode($"{portalName} ({fromZone} ⟷ {toZone})")
{
ForeColor = Color.Magenta,
ToolTipText = $"Portal\n{fromZone} ⟷ {toZone}\nGuard: {guardValue}\nWeekly Increment: {guardIncrement}"
};
// Add subitems showing the zone endpoints
if (!string.IsNullOrEmpty(fromZone) && fromZone != "?")
{
TreeNode fromNode = new TreeNode($"From: {fromZone}")
{
ForeColor = Color.DarkGreen
};
// Tag with the actual zone entity
if (zoneEntities.ContainsKey(fromZone))
{
fromNode.Tag = zoneEntities[fromZone];
var fromZoneData = zones?.FirstOrDefault(z => z["name"]?.ToString() == fromZone);
if (fromZoneData != null)
{
fromNode.ToolTipText = $"Zone: {fromZone}\nLayout: {fromZoneData["layout"]}\nSize: {fromZoneData["size"]}";
}
}
portalItemNode.Nodes.Add(fromNode);
}
if (!string.IsNullOrEmpty(toZone) && toZone != "?")
{
TreeNode toNode = new TreeNode($"To: {toZone}")
{
ForeColor = Color.DarkOrange
};
// Tag with the actual zone entity
if (zoneEntities.ContainsKey(toZone))
{
toNode.Tag = zoneEntities[toZone];
var toZoneData = zones?.FirstOrDefault(z => z["name"]?.ToString() == toZone);
if (toZoneData != null)
{
toNode.ToolTipText = $"Zone: {toZone}\nLayout: {toZoneData["layout"]}\nSize: {toZoneData["size"]}";
}
}
portalItemNode.Nodes.Add(toNode);
}
portalNode.Nodes.Add(portalItemNode);