Debian Codegraph @

source/tools/atlas/AtlasUI/ScenarioEditor/Sections/Map/Map.cpp

raw
1 /* Copyright (C) 2025 Wildfire Games.
2 * This file is part of 0 A.D.
3 *
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include "precompiled.h"
19
20 #include "Map.h"
21
22 #include "tools/atlas/AtlasObject/AtlasObject.h"
23 #include "tools/atlas/AtlasUI/CustomControls/MapResizeDialog/MapResizeDialog.h"
24 #include "tools/atlas/AtlasUI/General/AtlasWindowCommandProc.h"
25 #include "tools/atlas/AtlasUI/General/Observable.h"
26 #include "tools/atlas/AtlasUI/ScenarioEditor/ScenarioEditor.h"
27 #include "tools/atlas/AtlasUI/ScenarioEditor/Sections/Common/Sidebar.h"
28 #include "tools/atlas/AtlasUI/ScenarioEditor/Tools/Common/Tools.h"
29 #include "tools/atlas/GameInterface/MessagePasser.h"
30 #include "tools/atlas/GameInterface/Messages.h"
31 #include "tools/atlas/GameInterface/Shareable.h"
32
33 #include <algorithm>
34 #include <cstdint>
35 #include <ctime>
36 #include <list>
37 #include <map>
38 #include <random>
39 #include <set>
40 #include <string>
41 #include <utility>
42 #include <vector>
43 #include <wx/busyinfo.h>
44 #include <wx/button.h>
45 #include <wx/chartype.h>
46 #include <wx/checkbox.h>
47 #include <wx/choice.h>
48 #include <wx/clntdata.h>
49 #include <wx/collpane.h>
50 #include <wx/debug.h>
51 #include <wx/gdicmn.h>
52 #include <wx/log.h>
53 #include <wx/object.h>
54 #include <wx/panel.h>
55 #include <wx/scrolwin.h>
56 #include <wx/sizer.h>
57 #include <wx/statbox.h>
58 #include <wx/stattext.h>
59 #include <wx/string.h>
60 #include <wx/textctrl.h>
61 #include <wx/toolbar.h>
62 #include <wx/translation.h>
63 #include <wx/utils.h>
64 #include <wx/valtext.h>
65 #include <wx/window.h>
66 #include <wx/wxcrt.h>
67
68 #define CREATE_CHECKBOX(window, parentSizer, name, description, ID) \
69 parentSizer->Add(new wxStaticText(window, wxID_ANY, _(name)), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT)); \
70 parentSizer->Add(Tooltipped(new wxCheckBox(window, ID, wxEmptyString), _(description)));
71
72 enum
73 {
74 ID_MapName,
75 ID_MapDescription,
76 ID_MapReveal,
77 ID_MapAlly,
78 ID_MapType,
79 ID_MapPreview,
80 ID_MapTeams,
81 ID_MapKW_Demo,
82 ID_MapKW_Naval,
83 ID_MapKW_New,
84 ID_MapKW_Trigger,
85 ID_RandomScript,
86 ID_RandomSize,
87 ID_RandomBiome,
88 ID_RandomNomad,
89 ID_RandomSeed,
90 ID_RandomReseed,
91 ID_RandomGenerate,
92 ID_ResizeMap,
93 ID_SimPlay,
94 ID_SimFast,
95 ID_SimSlow,
96 ID_SimPause,
97 ID_SimReset,
98 ID_PlayerPlacement,
99 ID_OpenPlayerPanel
100 };
101
102 enum
103 {
104 SimInactive,
105 SimPlaying,
106 SimPlayingFast,
107 SimPlayingSlow,
108 SimPaused
109 };
110
111 bool IsPlaying(int s) { return (s == SimPlaying || s == SimPlayingFast || s == SimPlayingSlow); }
112
113 // TODO: Some of these helper things should be moved out of this file
114 // and into shared locations
115
116 // Helper function for adding tooltips
117 static wxWindow* Tooltipped(wxWindow* window, const wxString& tip)
118 {
119 window->SetToolTip(tip);
120 return window;
121 }
122
123 // Helper class for storing AtObjs
124 class AtObjClientData : public wxClientData
125 {
126 public:
127 AtObjClientData(const AtObj& obj) : obj(obj) {}
128 virtual ~AtObjClientData() {}
129 AtObj GetValue() { return obj; }
130 private:
131 AtObj obj;
132 };
133
134 class MapSettingsControl : public wxPanel
135 {
136 public:
137 MapSettingsControl(wxWindow* parent, ScenarioEditor& scenarioEditor);
138 void CreateWidgets();
139 void ReadFromEngine();
140 void SetMapSettings(const AtObj& obj);
141 AtObj UpdateSettingsObject();
142 private:
143 void SendToEngine();
144 void OnVictoryConditionChanged(long controlId);
145
146 void OnEdit(wxCommandEvent& evt)
147 {
148 long id = static_cast<long>(evt.GetId());
149 if (std::any_of(m_VictoryConditions.begin(), m_VictoryConditions.end(), [id](const std::pair<long, AtObj>& vc) {
150 return vc.first == id;
151 }))
152 OnVictoryConditionChanged(id);
153
154 SendToEngine();
155 }
156
157 std::map<long, AtObj> m_VictoryConditions;
158 std::set<std::string> m_MapSettingsKeywords;
159 std::set<std::string> m_MapSettingsVictoryConditions;
160 std::vector<wxChoice*> m_PlayerCivChoices;
161 Observable<AtObj>& m_MapSettings;
162
163 DECLARE_EVENT_TABLE();
164 };
165
166 BEGIN_EVENT_TABLE(MapSettingsControl, wxPanel)
167 EVT_TEXT(ID_MapName, MapSettingsControl::OnEdit)
168 EVT_TEXT(ID_MapDescription, MapSettingsControl::OnEdit)
169 EVT_TEXT(ID_MapPreview, MapSettingsControl::OnEdit)
170 EVT_CHECKBOX(wxID_ANY, MapSettingsControl::OnEdit)
171 EVT_CHOICE(wxID_ANY, MapSettingsControl::OnEdit)
172 END_EVENT_TABLE();
173
174 MapSettingsControl::MapSettingsControl(wxWindow* parent, ScenarioEditor& scenarioEditor)
175 : wxPanel(parent, wxID_ANY), m_MapSettings(scenarioEditor.GetMapSettings())
176 {
177 wxStaticBoxSizer* sizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Map settings"));
178 SetSizer(sizer);
179 }
180
181 void MapSettingsControl::CreateWidgets()
182 {
183 wxStaticBoxSizer* sizer = static_cast<wxStaticBoxSizer*>(GetSizer());
184
185 /////////////////////////////////////////////////////////////////////////
186 // Map settings
187 wxBoxSizer* nameSizer = new wxBoxSizer(wxHORIZONTAL);
188 nameSizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("Name")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL));
189 nameSizer->Add(8, 0);
190 nameSizer->Add(Tooltipped(new wxTextCtrl(sizer->GetStaticBox(), ID_MapName),
191 _("Displayed name of the map")), wxSizerFlags().Proportion(1));
192 sizer->Add(nameSizer, wxSizerFlags().Expand());
193
194 sizer->Add(0, 2);
195
196 sizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("Description")));
197 sizer->Add(Tooltipped(new wxTextCtrl(sizer->GetStaticBox(), ID_MapDescription, wxEmptyString, wxDefaultPosition, wxSize(-1, 100), wxTE_MULTILINE),
198 _("Short description used on the map selection screen")), wxSizerFlags().Expand());
199
200 sizer->AddSpacer(5);
201
202 wxFlexGridSizer* gridSizer = new wxFlexGridSizer(2, 5, 5);
203 gridSizer->AddGrowableCol(1);
204
205 // TODO: have preview selector tool?
206 gridSizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("Preview")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT));
207 gridSizer->Add(Tooltipped(new wxTextCtrl(sizer->GetStaticBox(), ID_MapPreview, wxEmptyString),
208 _("Texture used for map preview")), wxSizerFlags().Expand());
209 CREATE_CHECKBOX(sizer->GetStaticBox(), gridSizer, "Reveal map", "If checked, players won't need to explore", ID_MapReveal);
210 CREATE_CHECKBOX(sizer->GetStaticBox(), gridSizer, "Ally view", "If checked, players will be able to see what their teammates see and won't need to research cartography", ID_MapAlly);
211 CREATE_CHECKBOX(sizer->GetStaticBox(), gridSizer, "Lock teams", "If checked, teams will be locked", ID_MapTeams);
212 sizer->Add(gridSizer, wxSizerFlags().Expand());
213
214 sizer->AddSpacer(5);
215
216 wxStaticBoxSizer* victoryConditionSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Victory Conditions"));
217 wxFlexGridSizer* vcGridSizer = new wxFlexGridSizer(2, 0, 5);
218 vcGridSizer->AddGrowableCol(1);
219
220 AtlasMessage::qGetVictoryConditionData qryVictoryCondition;
221 qryVictoryCondition.Post();
222 std::vector<std::string> victoryConditionData = *qryVictoryCondition.data;
223
224 for (const std::string& victoryConditionJson : victoryConditionData)
225 {
226 AtObj victoryCondition = AtlasObject::LoadFromJSON(victoryConditionJson);
227 long index = wxWindow::NewControlId();
228 wxString title = wxString::FromUTF8(victoryCondition["Data"]["Title"]);
229 std::string escapedTitle = title.Lower().ToStdString();
230 std::replace(escapedTitle.begin(), escapedTitle.end(), ' ', '_');
231 AtObj updateCondition = *(victoryCondition["Data"]["Title"]);
232 updateCondition.setString(escapedTitle.c_str());
233 m_VictoryConditions.insert(std::pair<long, AtObj>(index, victoryCondition));
234 CREATE_CHECKBOX(victoryConditionSizer->GetStaticBox(), vcGridSizer, title, "Select " + title + " victory condition.", index);
235 }
236
237 victoryConditionSizer->Add(vcGridSizer);
238 sizer->Add(victoryConditionSizer, wxSizerFlags().Expand());
239
240 sizer->AddSpacer(5);
241
242 wxStaticBoxSizer* keywordsSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Keywords"));
243 wxFlexGridSizer* kwGridSizer = new wxFlexGridSizer(4, 5, 15);
244 CREATE_CHECKBOX(keywordsSizer->GetStaticBox(), kwGridSizer, "Demo", "If checked, map will only be visible using filters in game setup", ID_MapKW_Demo);
245 CREATE_CHECKBOX(keywordsSizer->GetStaticBox(), kwGridSizer, "Naval", "If checked, map will only be visible using filters in game setup", ID_MapKW_Naval);
246 CREATE_CHECKBOX(keywordsSizer->GetStaticBox(), kwGridSizer, "New", "If checked, the map will appear in the list of new maps", ID_MapKW_New);
247 CREATE_CHECKBOX(keywordsSizer->GetStaticBox(), kwGridSizer, "Trigger", "If checked, the map will appear in the list of maps with trigger scripts", ID_MapKW_Trigger);
248
249 keywordsSizer->Add(kwGridSizer);
250 sizer->Add(keywordsSizer, wxSizerFlags().Expand());
251 }
252
253 void MapSettingsControl::ReadFromEngine()
254 {
255 AtlasMessage::qGetMapSettings qry;
256 qry.Post();
257 if (!(*qry.settings).empty())
258 {
259 // Prevent error if there's no map settings to parse
260 m_MapSettings = AtlasObject::LoadFromJSON(*qry.settings);
261 }
262
263 // map name
264 wxDynamicCast(FindWindow(ID_MapName), wxTextCtrl)->ChangeValue(wxString::FromUTF8(m_MapSettings["Name"]));
265
266 // map description
267 wxDynamicCast(FindWindow(ID_MapDescription), wxTextCtrl)->ChangeValue(wxString::FromUTF8(m_MapSettings["Description"]));
268
269 // map preview
270 wxDynamicCast(FindWindow(ID_MapPreview), wxTextCtrl)->ChangeValue(wxString::FromUTF8(m_MapSettings["Preview"]));
271
272 // reveal map
273 wxDynamicCast(FindWindow(ID_MapReveal), wxCheckBox)->SetValue(wxString::FromUTF8(m_MapSettings["RevealMap"]) == "true");
274
275 // ally view
276 wxDynamicCast(FindWindow(ID_MapAlly), wxCheckBox)->SetValue(wxString::FromUTF8(m_MapSettings["AllyView"]) == "true");
277
278 // victory conditions
279 m_MapSettingsVictoryConditions.clear();
280 for (AtIter victoryCondition = m_MapSettings["VictoryConditions"]["item"]; victoryCondition.defined(); ++victoryCondition)
281 m_MapSettingsVictoryConditions.insert(std::string(victoryCondition));
282
283 // Clear Checkboxes before loading data. We don't update victory condition just yet because it might reenable some of the checkboxes.
284 for (const std::pair<const long, AtObj>& vc : m_VictoryConditions)
285 {
286 wxCheckBox* checkBox = wxDynamicCast(FindWindow(vc.first), wxCheckBox);
287 if (!checkBox)
288 continue;
289
290 checkBox->SetValue(false);
291 checkBox->Enable(true);
292 }
293
294 for (const std::pair<const long, AtObj>& vc : m_VictoryConditions)
295 {
296 std::string escapedTitle = wxString::FromUTF8(vc.second["Data"]["Title"]).Lower().ToStdString();
297 std::replace(escapedTitle.begin(), escapedTitle.end(), ' ', '_');
298 if (m_MapSettingsVictoryConditions.find(escapedTitle) == m_MapSettingsVictoryConditions.end())
299 continue;
300
301 wxCheckBox* checkBox = wxDynamicCast(FindWindow(vc.first), wxCheckBox);
302 if (!checkBox)
303 continue;
304
305 checkBox->SetValue(true);
306 OnVictoryConditionChanged(vc.first);
307 }
308
309 // lock teams
310 wxDynamicCast(FindWindow(ID_MapTeams), wxCheckBox)->SetValue(wxString::FromUTF8(m_MapSettings["LockTeams"]) == "true");
311
312 // keywords
313 {
314 m_MapSettingsKeywords.clear();
315 for (AtIter keyword = m_MapSettings["Keywords"]["item"]; keyword.defined(); ++keyword)
316 m_MapSettingsKeywords.insert(std::string(keyword));
317 wxWindow* window;
318 #define INIT_CHECKBOX(ID, mapSettings, value) \
319 window = FindWindow(ID); \
320 if (window != nullptr) \
321 wxDynamicCast(window, wxCheckBox)->SetValue(mapSettings.count(value) != 0);
322 INIT_CHECKBOX(ID_MapKW_Demo, m_MapSettingsKeywords, "demo");
323 INIT_CHECKBOX(ID_MapKW_Naval, m_MapSettingsKeywords, "naval");
324 INIT_CHECKBOX(ID_MapKW_New, m_MapSettingsKeywords, "new");
325 INIT_CHECKBOX(ID_MapKW_Trigger, m_MapSettingsKeywords, "trigger");
326 #undef INIT_CHECKBOX
327 }
328 }
329
330 void MapSettingsControl::SetMapSettings(const AtObj& obj)
331 {
332 m_MapSettings = obj;
333 m_MapSettings.NotifyObservers();
334
335 SendToEngine();
336 }
337
338 void MapSettingsControl::OnVictoryConditionChanged(long controlId)
339 {
340 AtObj victoryCondition;
341 wxCheckBox* modifiedCheckbox = wxDynamicCast(FindWindow(controlId), wxCheckBox);
342
343 for (const std::pair<const long, AtObj>& vc : m_VictoryConditions)
344 {
345 if (vc.first != controlId)
346 continue;
347
348 victoryCondition = vc.second;
349 break;
350 }
351
352 if (modifiedCheckbox->GetValue())
353 {
354 for (AtIter victoryConditionPair = victoryCondition["Data"]["ChangeOnChecked"]; victoryConditionPair.defined(); ++victoryConditionPair)
355 {
356 for (const std::pair<const long, AtObj>& vc : m_VictoryConditions)
357 {
358 std::string escapedTitle = wxString::FromUTF8(vc.second["Data"]["Title"]).Lower().ToStdString();
359 std::replace(escapedTitle.begin(), escapedTitle.end(), ' ', '_');
360
361 if (victoryConditionPair[escapedTitle.c_str()].defined())
362 {
363 wxCheckBox* victoryConditionCheckBox = wxDynamicCast(FindWindow(vc.first), wxCheckBox);
364 victoryConditionCheckBox->SetValue(wxString::FromUTF8(victoryConditionPair[escapedTitle.c_str()]).Lower().ToStdString() == "true");
365 }
366 }
367 }
368 }
369
370 for (const std::pair<const long, AtObj>& vc : m_VictoryConditions)
371 {
372 if (vc.first == controlId)
373 continue;
374
375 wxCheckBox* otherCheckbox = wxDynamicCast(FindWindow(vc.first), wxCheckBox);
376 otherCheckbox->Enable(true);
377
378 for (const std::pair<const long, AtObj>& vc2 : m_VictoryConditions)
379 {
380 for (AtIter victoryConditionTitle = vc2.second["Data"]["DisabledWhenChecked"]; victoryConditionTitle.defined(); ++victoryConditionTitle)
381 {
382 std::string escapedTitle = wxString::FromUTF8(vc.second["Data"]["Title"]).Lower().ToStdString();
383 std::replace(escapedTitle.begin(), escapedTitle.end(), ' ', '_');
384 if (escapedTitle == wxString::FromUTF8(victoryConditionTitle["item"]).ToStdString() && wxDynamicCast(FindWindow(vc2.first), wxCheckBox)->GetValue())
385 {
386 otherCheckbox->Enable(false);
387 otherCheckbox->SetValue(false);
388 break;
389 }
390 }
391 }
392 }
393 }
394
395 AtObj MapSettingsControl::UpdateSettingsObject()
396 {
397 // map name
398 m_MapSettings.set("Name", wxDynamicCast(FindWindow(ID_MapName), wxTextCtrl)->GetValue().utf8_str());
399
400 // map description
401 m_MapSettings.set("Description", wxDynamicCast(FindWindow(ID_MapDescription), wxTextCtrl)->GetValue().utf8_str());
402
403 // map preview
404 m_MapSettings.set("Preview", wxDynamicCast(FindWindow(ID_MapPreview), wxTextCtrl)->GetValue().utf8_str());
405
406 // reveal map
407 m_MapSettings.setBool("RevealMap", wxDynamicCast(FindWindow(ID_MapReveal), wxCheckBox)->GetValue());
408
409 // ally view
410 m_MapSettings.setBool("AllyView", wxDynamicCast(FindWindow(ID_MapAlly), wxCheckBox)->GetValue());
411
412 // victory conditions
413 #define INSERT_VICTORY_CONDITION_CHECKBOX(name, ID) \
414 if (wxDynamicCast(FindWindow(ID), wxCheckBox)->GetValue()) \
415 m_MapSettingsVictoryConditions.insert(name); \
416 else \
417 m_MapSettingsVictoryConditions.erase(name);
418
419 for (const std::pair<const long, AtObj>& vc : m_VictoryConditions)
420 {
421 std::string escapedTitle = wxString::FromUTF8(vc.second["Data"]["Title"]).Lower().ToStdString();
422 std::replace(escapedTitle.begin(), escapedTitle.end(), ' ', '_');
423 INSERT_VICTORY_CONDITION_CHECKBOX(escapedTitle, vc.first)
424 }
425
426 #undef INSERT_VICTORY_CONDITION_CHECKBOX
427
428 AtObj victoryConditions;
429 victoryConditions.set("@array", "");
430 for (const std::string& victoryCondition : m_MapSettingsVictoryConditions)
431 victoryConditions.add("item", victoryCondition.c_str());
432 m_MapSettings.set("VictoryConditions", victoryConditions);
433
434 // keywords
435 {
436 #define INSERT_KEYWORDS_CHECKBOX(name, ID) \
437 if (wxDynamicCast(FindWindow(ID), wxCheckBox)->GetValue()) \
438 m_MapSettingsKeywords.insert(name); \
439 else \
440 m_MapSettingsKeywords.erase(name);
441
442 INSERT_KEYWORDS_CHECKBOX("demo", ID_MapKW_Demo);
443 INSERT_KEYWORDS_CHECKBOX("naval", ID_MapKW_Naval);
444 INSERT_KEYWORDS_CHECKBOX("new", ID_MapKW_New);
445 INSERT_KEYWORDS_CHECKBOX("trigger", ID_MapKW_Trigger);
446
447 #undef INSERT_KEYWORDS_CHECKBOX
448
449 AtObj keywords;
450 keywords.set("@array", "");
451 for (const std::string& keyword : m_MapSettingsKeywords)
452 keywords.add("item", keyword.c_str());
453 m_MapSettings.set("Keywords", keywords);
454 }
455
456 // teams locked
457 m_MapSettings.setBool("LockTeams", wxDynamicCast(FindWindow(ID_MapTeams), wxCheckBox)->GetValue());
458
459 // default AI RNG seed
460 m_MapSettings.setInt("AISeed", 0);
461
462 return m_MapSettings;
463 }
464
465 void MapSettingsControl::SendToEngine()
466 {
467 UpdateSettingsObject();
468
469 std::string json = AtlasObject::SaveToJSON(m_MapSettings);
470
471 // TODO: would be nice if we supported undo for settings changes
472
473 POST_COMMAND(SetMapSettings, (json));
474 }
475
476
477 MapSidebar::MapSidebar(ScenarioEditor& scenarioEditor, wxWindow* sidebarContainer, wxWindow* bottomBarContainer)
478 : Sidebar(scenarioEditor, sidebarContainer, bottomBarContainer), m_SimState(SimInactive)
479 {
480 wxSizer* scrollSizer = new wxBoxSizer(wxVERTICAL);
481 wxScrolledWindow* scrolledWindow = new wxScrolledWindow(this);
482 scrolledWindow->SetScrollRate(10, 10);
483 scrolledWindow->SetSizer(scrollSizer);
484 m_MainSizer->Add(scrolledWindow, wxSizerFlags().Expand().Proportion(1));
485
486 m_MapSettingsCtrl = new MapSettingsControl(scrolledWindow, m_ScenarioEditor);
487 scrollSizer->Add(m_MapSettingsCtrl, wxSizerFlags().Expand());
488
489 {
490 /////////////////////////////////////////////////////////////////////////
491 // Random map settings
492 wxStaticBoxSizer* sizer = new wxStaticBoxSizer(wxVERTICAL, scrolledWindow, _("Random map"));
493 scrollSizer->Add(sizer, wxSizerFlags().Expand());
494
495 sizer->Add(new wxChoice(sizer->GetStaticBox(), ID_RandomScript), wxSizerFlags().Expand());
496
497 sizer->AddSpacer(5);
498
499 sizer->Add(new wxButton(sizer->GetStaticBox(), ID_OpenPlayerPanel, _T("Change players")), wxSizerFlags().Expand());
500
501 sizer->AddSpacer(5);
502
503 wxFlexGridSizer* gridSizer = new wxFlexGridSizer(2, 5, 5);
504 gridSizer->AddGrowableCol(1);
505
506 gridSizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("Biome")),
507 wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT));
508 gridSizer->Add(new wxChoice(sizer->GetStaticBox(), ID_RandomBiome), wxSizerFlags().Expand());
509
510 gridSizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("Player Placement")),
511 wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT));
512 gridSizer->Add(new wxChoice(sizer->GetStaticBox(), ID_PlayerPlacement), wxSizerFlags().Expand());
513
514 wxChoice* sizeChoice = new wxChoice(sizer->GetStaticBox(), ID_RandomSize);
515 gridSizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("Map size")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT));
516 gridSizer->Add(sizeChoice, wxSizerFlags().Expand());
517
518 CREATE_CHECKBOX(sizer->GetStaticBox(), gridSizer, "Nomad", "Place only some units instead of starting bases.", ID_RandomNomad);
519
520 gridSizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("Random seed")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL | wxALIGN_RIGHT));
521 wxBoxSizer* seedSizer = new wxBoxSizer(wxHORIZONTAL);
522 seedSizer->Add(Tooltipped(new wxTextCtrl(sizer->GetStaticBox(), ID_RandomSeed, _T("0"), wxDefaultPosition, wxDefaultSize, 0, wxTextValidator(wxFILTER_NUMERIC)),
523 _("Seed value for random map")), wxSizerFlags(1).Expand());
524 seedSizer->Add(Tooltipped(new wxButton(sizer->GetStaticBox(), ID_RandomReseed, _("R"), wxDefaultPosition, wxSize(40, -1)),
525 _("New random seed")));
526 gridSizer->Add(seedSizer, wxSizerFlags().Expand());
527
528 sizer->Add(gridSizer, wxSizerFlags().Expand());
529
530 sizer->AddSpacer(5);
531
532 sizer->Add(Tooltipped(new wxButton(sizer->GetStaticBox(), ID_RandomGenerate, _("Generate map")),
533 _("Run selected random map script")), wxSizerFlags().Expand());
534 }
535
536 {
537 /////////////////////////////////////////////////////////////////////////
538 // Misc tools
539 wxStaticBoxSizer* sizer = new wxStaticBoxSizer(wxVERTICAL, scrolledWindow, _("Misc tools"));
540 sizer->Add(new wxButton(sizer->GetStaticBox(), ID_ResizeMap, _("Resize/Recenter map")), wxSizerFlags().Expand());
541 scrollSizer->Add(sizer, wxSizerFlags().Expand().Border(wxTOP, 10));
542 }
543
544 {
545 /////////////////////////////////////////////////////////////////////////
546 // Simulation buttons
547 wxStaticBoxSizer* sizer = new wxStaticBoxSizer(wxVERTICAL, scrolledWindow, _("Simulation test"));
548 scrollSizer->Add(sizer, wxSizerFlags().Expand().Border(wxTOP, 8));
549
550 wxGridSizer* gridSizer = new wxGridSizer(5);
551 gridSizer->Add(Tooltipped(new wxButton(sizer->GetStaticBox(), ID_SimPlay, _("Play"), wxDefaultPosition, wxSize(48, -1)),
552 _("Run the simulation at normal speed")), wxSizerFlags().Expand());
553 gridSizer->Add(Tooltipped(new wxButton(sizer->GetStaticBox(), ID_SimFast, _("Fast"), wxDefaultPosition, wxSize(48, -1)),
554 _("Run the simulation at 8x speed")), wxSizerFlags().Expand());
555 gridSizer->Add(Tooltipped(new wxButton(sizer->GetStaticBox(), ID_SimSlow, _("Slow"), wxDefaultPosition, wxSize(48, -1)),
556 _("Run the simulation at 1/8x speed")), wxSizerFlags().Expand());
557 gridSizer->Add(Tooltipped(new wxButton(sizer->GetStaticBox(), ID_SimPause, _("Pause"), wxDefaultPosition, wxSize(48, -1)),
558 _("Pause the simulation")), wxSizerFlags().Expand());
559 gridSizer->Add(Tooltipped(new wxButton(sizer->GetStaticBox(), ID_SimReset, _("Reset"), wxDefaultPosition, wxSize(48, -1)),
560 _("Reset the editor to initial state")), wxSizerFlags().Expand());
561 sizer->Add(gridSizer, wxSizerFlags().Expand());
562 UpdateSimButtons();
563 }
564 }
565
566 void MapSidebar::OnCollapse(wxCollapsiblePaneEvent& WXUNUSED(evt))
567 {
568 Freeze();
569
570 // Toggling the collapsing doesn't seem to update the sidebar layout
571 // automatically, so do it explicitly here
572 Layout();
573
574 Refresh(); // fixes repaint glitch on Windows
575
576 Thaw();
577 }
578
579 void MapSidebar::OnFirstDisplay()
580 {
581 // We do this here becase messages are used which requires simulation to be init'd
582 m_MapSettingsCtrl->CreateWidgets();
583 m_MapSettingsCtrl->ReadFromEngine();
584
585 // Load the map sizes list
586 AtlasMessage::qGetMapSizes qrySizes;
587 qrySizes.Post();
588 AtObj sizes = AtlasObject::LoadFromJSON(*qrySizes.sizes);
589 wxChoice* sizeChoice = wxDynamicCast(FindWindow(ID_RandomSize), wxChoice);
590 for (AtIter s = sizes["Data"]["item"]; s.defined(); ++s)
591 sizeChoice->Append(wxString::FromUTF8(s["Name"]), reinterpret_cast<void*>(static_cast<intptr_t>((*s["Tiles"]).getLong())));
592 sizeChoice->SetSelection(0);
593
594 // Load the RMS script list
595 AtlasMessage::qGetRMSData qry;
596 qry.Post();
597 std::vector<std::string> scripts = *qry.data;
598 wxChoice* scriptChoice = wxDynamicCast(FindWindow(ID_RandomScript), wxChoice);
599 scriptChoice->Clear();
600 for (size_t i = 0; i < scripts.size(); ++i)
601 {
602 AtObj data = AtlasObject::LoadFromJSON(scripts[i]);
603 wxString name = wxString::FromUTF8(data["settings"]["Name"]);
604 if (!name.IsEmpty())
605 scriptChoice->Append(name, new AtObjClientData(*data["settings"]));
606 }
607 scriptChoice->SetSelection(0);
608
609 Layout();
610 }
611
612 void MapSidebar::OnMapReload()
613 {
614 m_MapSettingsCtrl->ReadFromEngine();
615
616 // Reset sim test buttons
617 POST_MESSAGE(SimPlay, (0.f, false));
618 POST_MESSAGE(SimStopMusic, ());
619 POST_MESSAGE(GuiSwitchPage, (L"page_atlas.xml"));
620 m_SimState = SimInactive;
621 UpdateSimButtons();
622 }
623
624 void MapSidebar::UpdateSimButtons()
625 {
626 wxButton* button;
627
628 button = wxDynamicCast(FindWindow(ID_SimPlay), wxButton);
629 wxCHECK(button, );
630 button->Enable(m_SimState != SimPlaying);
631
632 button = wxDynamicCast(FindWindow(ID_SimFast), wxButton);
633 wxCHECK(button, );
634 button->Enable(m_SimState != SimPlayingFast);
635
636 button = wxDynamicCast(FindWindow(ID_SimSlow), wxButton);
637 wxCHECK(button, );
638 button->Enable(m_SimState != SimPlayingSlow);
639
640 button = wxDynamicCast(FindWindow(ID_SimPause), wxButton);
641 wxCHECK(button, );
642 button->Enable(IsPlaying(m_SimState));
643
644 button = wxDynamicCast(FindWindow(ID_SimReset), wxButton);
645 wxCHECK(button, );
646 button->Enable(m_SimState != SimInactive);
647 }
648
649 void MapSidebar::OnSimPlay(wxCommandEvent& event)
650 {
651 float speed = 1.f;
652 int newState = SimPlaying;
653 if (event.GetId() == ID_SimFast)
654 {
655 speed = 8.f;
656 newState = SimPlayingFast;
657 }
658 else if (event.GetId() == ID_SimSlow)
659 {
660 speed = 0.125f;
661 newState = SimPlayingSlow;
662 }
663
664 if (m_SimState == SimInactive)
665 {
666 // Force update of player settings
667 POST_MESSAGE(LoadPlayerSettings, (false));
668
669 POST_MESSAGE(SimStateSave, (L"default"));
670 POST_MESSAGE(GuiSwitchPage, (L"page_session.xml"));
671 POST_MESSAGE(SimPlay, (speed, true));
672 m_SimState = newState;
673 }
674 else // paused or already playing at a different speed
675 {
676 POST_MESSAGE(SimPlay, (speed, true));
677 m_SimState = newState;
678 }
679 UpdateSimButtons();
680 }
681
682 void MapSidebar::OnSimPause(wxCommandEvent& WXUNUSED(event))
683 {
684 if (IsPlaying(m_SimState))
685 {
686 POST_MESSAGE(SimPlay, (0.f, true));
687 m_SimState = SimPaused;
688 }
689 UpdateSimButtons();
690 }
691
692 void MapSidebar::OnSimReset(wxCommandEvent& WXUNUSED(event))
693 {
694 if (IsPlaying(m_SimState))
695 {
696 POST_MESSAGE(SimPlay, (0.f, true));
697 POST_MESSAGE(SimStateRestore, (L"default"));
698 POST_MESSAGE(SimStopMusic, ());
699 POST_MESSAGE(SimPlay, (0.f, false));
700 POST_MESSAGE(GuiSwitchPage, (L"page_atlas.xml"));
701 m_SimState = SimInactive;
702 }
703 else if (m_SimState == SimPaused)
704 {
705 POST_MESSAGE(SimPlay, (0.f, true));
706 POST_MESSAGE(SimStateRestore, (L"default"));
707 POST_MESSAGE(SimStopMusic, ());
708 POST_MESSAGE(SimPlay, (0.f, false));
709 POST_MESSAGE(GuiSwitchPage, (L"page_atlas.xml"));
710 m_SimState = SimInactive;
711 }
712 UpdateSimButtons();
713 }
714
715 void MapSidebar::OnRandomScript(wxCommandEvent& WXUNUSED(evt))
716 {
717 wxChoice* biomeChoice = wxDynamicCast(FindWindow(ID_RandomBiome), wxChoice);
718 wxChoice* scriptChoice = wxDynamicCast(FindWindow(ID_RandomScript), wxChoice);
719
720 if (scriptChoice->GetSelection() < 0)
721 return;
722
723 biomeChoice->Clear();
724
725 AtObj mapSettings = dynamic_cast<AtObjClientData*>(scriptChoice->GetClientObject(
726 scriptChoice->GetSelection()))->GetValue();
727 std::vector<std::string> biomes;
728 if (mapSettings["SupportedBiomes"]["@array"].defined())
729 {
730 for (AtIter it = mapSettings["SupportedBiomes"]["item"]; it.defined(); ++it)
731 biomes.push_back(static_cast<const char*>(*it));
732 }
733 else
734 {
735 std::string singleBiome{static_cast<const char*>(*mapSettings["SupportedBiomes"])};
736 if (!singleBiome.empty())
737 biomes.push_back(singleBiome);
738 }
739
740 if (std::any_of(biomes.begin(), biomes.end(), [](const std::string& biome)
741 {
742 return !biome.empty() && biome.back() == '/';
743 }))
744 {
745 AtlasMessage::qExpandBiomes qry;
746 qry.biomes = std::move(biomes);
747 qry.Post();
748 biomes = *qry.biomes;
749 }
750
751 for (const std::string& biome : biomes)
752 biomeChoice->Append(wxString::FromUTF8(biome.c_str()));
753
754 biomeChoice->SetSelection(0);
755
756 wxChoice* playerPlacementChoice = wxDynamicCast(FindWindow(ID_PlayerPlacement), wxChoice);
757 playerPlacementChoice->Clear();
758 for (AtIter it = mapSettings["PlayerPlacements"]["item"]; it.defined(); ++it)
759 playerPlacementChoice->Append(wxString::FromUTF8(static_cast<const char*>(*it)));
760 playerPlacementChoice->SetSelection(0);
761 }
762
763 void MapSidebar::OnRandomReseed(wxCommandEvent& WXUNUSED(evt))
764 {
765 std::mt19937 engine(std::time(nullptr));
766 std::uniform_int_distribution<int> distribution(0, 10000);
767
768 // Pick a shortish randomish value
769 wxString seed;
770 seed << distribution(engine);
771 wxDynamicCast(FindWindow(ID_RandomSeed), wxTextCtrl)->SetValue(seed);
772 }
773
774 void MapSidebar::OnRandomGenerate(wxCommandEvent& WXUNUSED(evt))
775 {
776 if (m_ScenarioEditor.DiscardChangesDialog())
777 return;
778
779 wxChoice* scriptChoice = wxDynamicCast(FindWindow(ID_RandomScript), wxChoice);
780
781 if (scriptChoice->GetSelection() < 0)
782 return;
783
784 // TODO: this settings thing seems a bit of a mess,
785 // since it's mixing data from three different sources
786
787 AtObj settings = m_MapSettingsCtrl->UpdateSettingsObject();
788
789 AtObj scriptSettings = dynamic_cast<AtObjClientData*>(scriptChoice->GetClientObject(scriptChoice->GetSelection()))->GetValue();
790
791 settings.addOverlay(scriptSettings);
792
793 wxChoice* sizeChoice = wxDynamicCast(FindWindow(ID_RandomSize), wxChoice);
794 wxString size;
795 size << (intptr_t)sizeChoice->GetClientData(sizeChoice->GetSelection());
796 settings.setInt("Size", wxAtoi(size));
797
798 settings.setBool("Nomad", wxDynamicCast(FindWindow(ID_RandomNomad), wxCheckBox)->GetValue());
799
800 settings.setInt("Seed", wxAtoi(wxDynamicCast(FindWindow(ID_RandomSeed), wxTextCtrl)->GetValue()));
801
802 const wxString biome{wxDynamicCast(FindWindow(ID_RandomBiome), wxChoice)->GetStringSelection()};
803 if (!biome.IsEmpty())
804 settings.set("Biome", biome.utf8_str());
805
806 const wxString playerPlacement{
807 wxDynamicCast(FindWindow(ID_PlayerPlacement), wxChoice)->GetStringSelection()};
808 if (!playerPlacement.empty())
809 settings.set("PlayerPlacement", playerPlacement.utf8_str());
810
811 std::string json = AtlasObject::SaveToJSON(settings);
812
813 wxBusyInfo busy(_("Generating map"));
814 wxBusyCursor busyc;
815
816 wxString scriptName = wxString::FromUTF8(settings["Script"]);
817
818 // Copy the old map settings, so we don't lose them if the map generation fails
819 AtObj oldSettings = settings;
820
821 // Deactivate tools, so they don't carry forwards into the new CWorld
822 // and crash.
823 m_ScenarioEditor.GetToolManager().SetCurrentTool(_T(""));
824 // TODO: clear the undo buffer, etc
825
826 AtlasMessage::qGenerateMap qry((std::wstring)scriptName.wc_str(), json);
827 qry.Post();
828
829 if (qry.status < 0)
830 {
831 // Display error message and revert to old map settings
832 wxLogError(_("Random map script '%s' failed"), scriptName.c_str());
833 m_MapSettingsCtrl->SetMapSettings(oldSettings);
834 }
835
836 m_ScenarioEditor.NotifyOnMapReload();
837
838 m_ScenarioEditor.GetCommandProc().ClearCommands();
839 }
840
841 void MapSidebar::OnOpenPlayerPanel(wxCommandEvent& WXUNUSED(evt))
842 {
843 m_ScenarioEditor.SelectPage(_T("PlayerSidebar"));
844 }
845
846 void MapSidebar::OnResizeMap(wxCommandEvent& WXUNUSED(evt))
847 {
848 MapResizeDialog dlg(this);
849
850 if (dlg.ShowModal() != wxID_OK)
851 return;
852 wxPoint offset = dlg.GetOffset();
853 POST_COMMAND(ResizeMap, (dlg.GetNewSize(), offset.x, offset.y));
854 }
855
856 BEGIN_EVENT_TABLE(MapSidebar, Sidebar)
857 EVT_COLLAPSIBLEPANE_CHANGED(wxID_ANY, MapSidebar::OnCollapse)
858 EVT_BUTTON(ID_SimPlay, MapSidebar::OnSimPlay)
859 EVT_BUTTON(ID_SimFast, MapSidebar::OnSimPlay)
860 EVT_BUTTON(ID_SimSlow, MapSidebar::OnSimPlay)
861 EVT_BUTTON(ID_SimPause, MapSidebar::OnSimPause)
862 EVT_BUTTON(ID_SimReset, MapSidebar::OnSimReset)
863 EVT_BUTTON(ID_RandomReseed, MapSidebar::OnRandomReseed)
864 EVT_BUTTON(ID_RandomGenerate, MapSidebar::OnRandomGenerate)
865 EVT_BUTTON(ID_ResizeMap, MapSidebar::OnResizeMap)
866 EVT_BUTTON(ID_OpenPlayerPanel, MapSidebar::OnOpenPlayerPanel)
867 EVT_CHOICE(ID_RandomScript, MapSidebar::OnRandomScript)
868 END_EVENT_TABLE();