Debian Codegraph @

source/tools/atlas/AtlasUI/ScenarioEditor/ScenarioEditor.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 "ScenarioEditor.h"
21
22 #include "tools/atlas/AtlasObject/AtlasObject.h"
23 #include "tools/atlas/AtlasUI/CustomControls/Buttons/ToolButton.h"
24 #include "tools/atlas/AtlasUI/CustomControls/Canvas/Canvas.h"
25 #include "tools/atlas/AtlasUI/CustomControls/FileHistory/FileHistory.h"
26 #include "tools/atlas/AtlasUI/CustomControls/HighResTimer/HighResTimer.h"
27 #include "tools/atlas/AtlasUI/CustomControls/MapDialog/MapDialog.h"
28 #include "tools/atlas/AtlasUI/General/AtlasWindowCommandProc.h"
29 #include "tools/atlas/AtlasUI/General/Datafile.h"
30 #include "tools/atlas/AtlasUI/General/Observable.h"
31 #include "tools/atlas/AtlasUI/Misc/DLLInterface.h"
32 #include "tools/atlas/AtlasUI/Misc/KeyMap.h"
33 #include "tools/atlas/AtlasUI/ScenarioEditor/SectionLayout.h"
34 #include "tools/atlas/AtlasUI/ScenarioEditor/Tools/Common/MiscState.h"
35 #include "tools/atlas/AtlasUI/ScenarioEditor/Tools/Common/ObjectSettings.h"
36 #include "tools/atlas/AtlasUI/ScenarioEditor/Tools/Common/Tools.h"
37 #include "tools/atlas/GameInterface/MessagePasser.h"
38 #include "tools/atlas/GameInterface/Messages.h"
39 #include "tools/atlas/GameInterface/Shareable.h"
40 #include "tools/atlas/GameInterface/SharedTypes.h"
41
42 #include <cstddef>
43 #include <list>
44 #include <string>
45 #include <utility>
46 #include <wx/busyinfo.h>
47 #include <wx/chartype.h>
48 #include <wx/clipbrd.h>
49 #include <wx/config.h>
50 #include <wx/dataobj.h>
51 #include <wx/datetime.h>
52 #include <wx/debug.h>
53 #include <wx/ffile.h>
54 #include <wx/filedlg.h>
55 #include <wx/filefn.h>
56 #include <wx/filename.h>
57 #include <wx/gdicmn.h>
58 #include <wx/glcanvas.h>
59 #include <wx/imagbmp.h>
60 #include <wx/image.h>
61 #include <wx/imagpng.h>
62 #include <wx/log.h>
63 #include <wx/menu.h>
64 #include <wx/msgdlg.h>
65 #include <wx/sstream.h>
66 #include <wx/sysopt.h>
67 #include <wx/textdlg.h>
68 #include <wx/toolbar.h>
69 #include <wx/tooltip.h>
70 #include <wx/toplevel.h>
71 #include <wx/translation.h>
72 #include <wx/utils.h>
73 #include <wx/xml/xml.h>
74
75 class wxInputStream;
76 class wxWindow;
77
78 #include <array>
79
80 static HighResTimer g_Timer;
81
82 /**
83 * wxWidgets only registers the double click on mousedown.
84 */
85 static int g_Clicks = 1;
86
87 using namespace AtlasMessage;
88
89 enum TIMER_TYPE
90 {
91 TIMER_TOOL,
92 TIMER_RENDER
93 };
94
95 const int TIMER_TOOL_INTERVAL = 16;
96 const int TIMER_RENDER_INTERVAL = 16;
97 const int TIMER_RENDER_SLOW_INTERVAL = 200;
98
99 // This records the last activity on the WX side.
100 double last_wx_user_activity = 0.0;
101
102 //////////////////////////////////////////////////////////////////////////
103
104 // GL functions exported from DLL, and called by game (in a separate
105 // thread to the standard wx one)
106 ATLASDLLIMPEXP void Atlas_GLSetCurrent(void* canvas)
107 {
108 static_cast<Canvas*>(canvas)->SetCurrent();
109 }
110
111 ATLASDLLIMPEXP void Atlas_GLSwapBuffers(void* canvas)
112 {
113 static_cast<Canvas*>(canvas)->SwapBuffers();
114 }
115
116
117 //////////////////////////////////////////////////////////////////////////
118
119 class GameCanvas : public Canvas
120 {
121 public:
122 GameCanvas(ScenarioEditor& scenarioEditor, wxWindow* parent, int* attribList)
123 : Canvas(parent, attribList, wxWANTS_CHARS),
124 m_ScenarioEditor(scenarioEditor), m_MouseState(NONE), m_LastMouseState(NONE)
125 {
126 }
127
128 private:
129
130 void SetScrolling(int dir, float speed, bool enable)
131 {
132 POST_MESSAGE(ScrollConstant, (eRenderView::GAME, dir, enable ? speed : 0.0f));
133 }
134
135 bool KeyScroll(wxKeyEvent& evt, bool enable)
136 {
137 static std::array<bool, 6> scrolling{};
138
139 switch (evt.GetKeyCode())
140 {
141 case 'A': case WXK_LEFT: std::get<0>(scrolling) = enable; break;
142 case 'D': case WXK_RIGHT: std::get<1>(scrolling) = enable; break;
143 case 'W': case WXK_UP: std::get<2>(scrolling) = enable; break;
144 case 'S': case WXK_DOWN: std::get<3>(scrolling) = enable; break;
145 case 'Q': case '[': std::get<4>(scrolling) = enable; break;
146 case 'E': case ']': std::get<5>(scrolling) = enable; break;
147 // Modifier keys changing speed and therefore requiring update.
148 case WXK_SHIFT: case WXK_CONTROL: break;
149 default: return false;
150 }
151
152 float speed = 120.f * ScenarioEditor::GetSpeedModifier();
153
154 SetScrolling(eScrollConstantDir::LEFT, speed, std::get<0>(scrolling));
155 SetScrolling(eScrollConstantDir::RIGHT, speed, std::get<1>(scrolling));
156 SetScrolling(eScrollConstantDir::FORWARDS, speed, std::get<2>(scrolling));
157 SetScrolling(eScrollConstantDir::BACKWARDS, speed, std::get<3>(scrolling));
158 SetScrolling(eScrollConstantDir::CLOCKWISE, speed, std::get<4>(scrolling));
159 SetScrolling(eScrollConstantDir::ANTICLOCKWISE, speed, std::get<5>(scrolling));
160
161 return true;
162 }
163
164 void OnKeyDown(wxKeyEvent& evt)
165 {
166 if (m_ScenarioEditor.GetToolManager().GetCurrentTool()->OnKey(evt, ITool::KEY_DOWN))
167 {
168 // Key event has been handled by the tool, so don't try
169 // to use it for camera motion too
170 last_wx_user_activity = g_Timer.GetTime();
171 return;
172 }
173
174 if (KeyScroll(evt, true))
175 return;
176
177 POST_MESSAGE(GuiKeyEvent, (GetSDLKeyFromWxKeyCode(evt.GetKeyCode()), evt.GetUnicodeKey(), true));
178
179 evt.Skip();
180 }
181
182 void OnKeyUp(wxKeyEvent& evt)
183 {
184 if (m_ScenarioEditor.GetToolManager().GetCurrentTool()->OnKey(evt, ITool::KEY_UP))
185 {
186 last_wx_user_activity = g_Timer.GetTime();
187 return;
188 }
189
190 if (KeyScroll(evt, false))
191 return;
192
193 POST_MESSAGE(GuiKeyEvent, (GetSDLKeyFromWxKeyCode(evt.GetKeyCode()), evt.GetUnicodeKey(), false));
194
195 evt.Skip();
196 }
197
198 void OnChar(wxKeyEvent& evt)
199 {
200 if (m_ScenarioEditor.GetToolManager().GetCurrentTool()->OnKey(evt, ITool::KEY_CHAR))
201 {
202 last_wx_user_activity = g_Timer.GetTime();
203 return;
204 }
205
206 // Alt+enter toggles fullscreen
207 if (evt.GetKeyCode() == WXK_RETURN && wxGetKeyState(WXK_ALT))
208 {
209 if (m_ScenarioEditor.IsFullScreen())
210 m_ScenarioEditor.ShowFullScreen(false);
211 else
212 m_ScenarioEditor.ShowFullScreen(true, wxFULLSCREEN_NOBORDER | wxFULLSCREEN_NOCAPTION);
213 return;
214 }
215
216 if (evt.GetKeyCode() == 'c')
217 {
218 POST_MESSAGE(CameraReset, ());
219 last_wx_user_activity = g_Timer.GetTime();
220 return;
221 }
222
223 int dir = 0;
224 if (evt.GetKeyCode() == '-' || evt.GetKeyCode() == '_')
225 dir = -1;
226 else if (evt.GetKeyCode() == '+' || evt.GetKeyCode() == '=')
227 dir = +1;
228 // TODO: internationalisation (-/_ and +/= don't always share a key)
229
230 if (dir)
231 {
232 float speed = 16.f * ScenarioEditor::GetSpeedModifier();
233 POST_MESSAGE(SmoothZoom, (eRenderView::GAME, speed*dir));
234 }
235 else
236 {
237 // Slight hack: Only pass 'alphanumeric' keys; special keys will generate a KeyDown/KeyUp event instead
238 if (evt.GetKeyCode() >= 33 && evt.GetKeyCode() <= 126)
239 POST_MESSAGE(GuiCharEvent, (GetSDLKeyFromWxKeyCode(evt.GetKeyCode()), evt.GetUnicodeKey()));
240
241 evt.Skip();
242 }
243 }
244
245 void OnKillFocus(wxFocusEvent& evt)
246 {
247 // Stop any scrolling, since otherwise we'll carry on forever if
248 // we lose focus and the KeyUp events go to a different window
249 POST_MESSAGE(ScrollConstant, (eRenderView::GAME, eScrollConstantDir::LEFT, 0.0f));
250 POST_MESSAGE(ScrollConstant, (eRenderView::GAME, eScrollConstantDir::RIGHT, 0.0f));
251 POST_MESSAGE(ScrollConstant, (eRenderView::GAME, eScrollConstantDir::FORWARDS, 0.0f));
252 POST_MESSAGE(ScrollConstant, (eRenderView::GAME, eScrollConstantDir::BACKWARDS, 0.0f));
253 POST_MESSAGE(ScrollConstant, (eRenderView::GAME, eScrollConstantDir::CLOCKWISE, 0.0f));
254 POST_MESSAGE(ScrollConstant, (eRenderView::GAME, eScrollConstantDir::ANTICLOCKWISE, 0.0f));
255
256 evt.Skip();
257 }
258
259 virtual void HandleMouseEvent(wxMouseEvent& evt)
260 {
261
262 // TODO or at least to think about: When using other controls in the
263 // editor, it's annoying that keyboard/scrollwheel no longer navigate
264 // around the world until you click on it.
265 // Setting focus back whenever the mouse moves over the GL window
266 // feels like a fairly natural solution to me, since I can use
267 // e.g. brush-editing controls normally, and then move the mouse to
268 // see the brush outline and magically get given back full control
269 // of the camera.
270 if (evt.Moving())
271 SetFocus();
272
273 // Refresh on any mouse event, including just moving the mouse around.
274 last_wx_user_activity = g_Timer.GetTime();
275
276 if (m_ScenarioEditor.GetToolManager().GetCurrentTool()->OnMouse(evt))
277 {
278 // Mouse event has been handled by the tool, so don't try
279 // to use it for camera motion too
280 return;
281 }
282
283 // Global mouse event handlers (for camera motion)
284
285 if (evt.GetWheelRotation())
286 {
287 float speed = 16.f * ScenarioEditor::GetSpeedModifier();
288 POST_MESSAGE(SmoothZoom, (eRenderView::GAME, evt.GetWheelRotation() * speed / evt.GetWheelDelta()));
289 }
290 else
291 {
292 if (evt.MiddleIsDown())
293 {
294 if (wxGetKeyState(WXK_CONTROL) || evt.RightIsDown())
295 m_MouseState = ROTATEAROUND;
296 else
297 m_MouseState = SCROLL;
298 }
299 else
300 m_MouseState = NONE;
301
302 if (m_MouseState != m_LastMouseState)
303 {
304 switch (m_MouseState)
305 {
306 case NONE: break;
307 case SCROLL: POST_MESSAGE(Scroll, (eRenderView::GAME, eScrollType::FROM, evt.GetPosition())); break;
308 case ROTATEAROUND: POST_MESSAGE(RotateAround, (eRenderView::GAME, eRotateAroundType::FROM, evt.GetPosition())); break;
309 default: wxFAIL;
310 }
311 m_LastMouseState = m_MouseState;
312 }
313 else if (evt.Dragging())
314 {
315 switch (m_MouseState)
316 {
317 case NONE: break;
318 case SCROLL: POST_MESSAGE(Scroll, (eRenderView::GAME, eScrollType::TO, evt.GetPosition())); break;
319 case ROTATEAROUND: POST_MESSAGE(RotateAround, (eRenderView::GAME, eRotateAroundType::TO, evt.GetPosition())); break;
320 default: wxFAIL;
321 }
322 }
323 }
324
325 // Button down and double click appear to be mutually exclusive events,
326 // meaning a second button down event is not sent before a double click
327 if (evt.ButtonDown() || evt.ButtonDClick())
328 {
329 g_Clicks = evt.ButtonDClick() ? 2 : 1;
330 POST_MESSAGE(GuiMouseButtonEvent, (evt.GetButton(), true, evt.GetPosition(), g_Clicks));
331 }
332 else if (evt.ButtonUp())
333 POST_MESSAGE(GuiMouseButtonEvent, (evt.GetButton(), false, evt.GetPosition(), g_Clicks));
334 else if (evt.GetEventType() == wxEVT_MOTION)
335 POST_MESSAGE(GuiMouseMotionEvent, (evt.GetPosition()));
336 }
337
338 enum { NONE, SCROLL, ROTATEAROUND };
339 int m_MouseState, m_LastMouseState;
340
341 ScenarioEditor& m_ScenarioEditor;
342
343 DECLARE_EVENT_TABLE();
344 };
345
346 BEGIN_EVENT_TABLE(GameCanvas, Canvas)
347 EVT_KEY_DOWN(GameCanvas::OnKeyDown)
348 EVT_KEY_UP(GameCanvas::OnKeyUp)
349 EVT_CHAR(GameCanvas::OnChar)
350 EVT_KILL_FOCUS(GameCanvas::OnKillFocus)
351 END_EVENT_TABLE()
352
353 //////////////////////////////////////////////////////////////////////////
354
355 enum
356 {
357 ID_Quit = 1,
358
359 ID_New,
360 ID_Open,
361 ID_Save,
362 ID_SaveAs,
363 ID_ImportHeightmap,
364
365 ID_Copy,
366 ID_Paste,
367
368 ID_Wireframe,
369 ID_MessageTrace,
370 ID_Screenshot,
371 ID_BigScreenshot,
372 ID_JavaScript,
373 ID_CameraReset,
374 ID_DumpState,
375 ID_DumpBinaryState,
376
377 ID_Manual,
378 ID_ReportBug,
379
380 ID_Toolbar // must be last in the list
381 };
382
383 BEGIN_EVENT_TABLE(ScenarioEditor, wxFrame)
384 EVT_CLOSE(ScenarioEditor::OnClose)
385 EVT_TIMER(wxID_ANY, ScenarioEditor::OnTimer)
386
387 EVT_MENU(ID_New, ScenarioEditor::OnNew)
388 EVT_MENU(ID_Open, ScenarioEditor::OnOpen)
389 EVT_MENU(ID_Save, ScenarioEditor::OnSave)
390 EVT_MENU(ID_SaveAs, ScenarioEditor::OnSaveAs)
391 EVT_MENU(ID_ImportHeightmap, ScenarioEditor::OnImportHeightmap)
392 EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, ScenarioEditor::OnMRUFile)
393
394 EVT_MENU(ID_Quit, ScenarioEditor::OnQuit)
395 EVT_MENU(wxID_UNDO, ScenarioEditor::OnUndo)
396 EVT_MENU(wxID_REDO, ScenarioEditor::OnRedo)
397 EVT_MENU(ID_Copy, ScenarioEditor::OnCopy)
398 EVT_MENU(ID_Paste, ScenarioEditor::OnPaste)
399
400 EVT_MENU(ID_Wireframe, ScenarioEditor::OnWireframe)
401 EVT_MENU(ID_MessageTrace, ScenarioEditor::OnMessageTrace)
402 EVT_MENU(ID_Screenshot, ScenarioEditor::OnScreenshot)
403 EVT_MENU(ID_BigScreenshot, ScenarioEditor::OnScreenshot)
404 EVT_MENU(ID_JavaScript, ScenarioEditor::OnJavaScript)
405 EVT_MENU(ID_CameraReset, ScenarioEditor::OnCameraReset)
406 EVT_MENU(ID_DumpState, ScenarioEditor::OnDumpState)
407 EVT_MENU(ID_DumpBinaryState, ScenarioEditor::OnDumpState)
408
409 EVT_MENU(ID_Manual, ScenarioEditor::OnHelp)
410 EVT_MENU(ID_ReportBug, ScenarioEditor::OnHelp)
411
412 EVT_MENU_OPEN(ScenarioEditor::OnMenuOpen)
413
414 EVT_IDLE(ScenarioEditor::OnIdle)
415 END_EVENT_TABLE()
416
417 static AtlasWindowCommandProc g_CommandProc;
418 AtlasWindowCommandProc& ScenarioEditor::GetCommandProc() { return g_CommandProc; }
419
420 ScenarioEditor::ScenarioEditor(wxWindow* parent)
421 : wxFrame(parent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(1024, 768))
422 , m_FileHistory(_T("Scenario Editor"))
423 , m_ObjectSettings(g_SelectedObjects, AtlasMessage::eRenderView::GAME)
424 , m_ToolManager(this)
425 {
426 // Global application initialisation:
427
428 wxImage::AddHandler(new wxICOHandler);
429
430 /* "osx.openfiledialog.always-show-types: Per default a wxFileDialog with wxFD_OPEN
431 does not show a types-popup on OSX but allows the selection of files from any of
432 the supported types. Setting this to 1 shows a wxChoice for selection (if there
433 is more than one supported filetype)." */
434 wxSystemOptions::SetOption(_T("osx.openfiledialog.always-show-types"), 1); // has global effect
435
436 // wxLog::SetTraceMask(wxTraceMessages);
437
438 g_SelectedTexture = _T("grass1_spring");
439 g_SelectedTexture.NotifyObservers();
440
441 SetOpenFilename(_T(""));
442
443 #if defined(__WXMSW__)
444 m_Icon = wxIcon(_T("ICON_ScenarioEditor")); // load from atlas.rc
445 #else
446 {
447 const wxString relativePath (_T("tools/atlas/icons/ScenarioEditor.ico"));
448 wxFileName filename (relativePath, wxPATH_UNIX);
449 filename.MakeAbsolute(Datafile::GetDataDirectory());
450 m_Icon = wxIcon(filename.GetFullPath(), wxBITMAP_TYPE_ICO);
451 }
452 #endif
453 SetIcon(m_Icon);
454
455 wxToolTip::Enable(true);
456
457 wxImage::AddHandler(new wxPNGHandler);
458
459 //////////////////////////////////////////////////////////////////////////
460
461 // Do some early game initialisation:
462 // (This must happen before constructing the GL canvas.)
463
464 POST_MESSAGE(Init, ());
465
466 // Wait for it to finish running Init
467 qPing qry;
468 qry.Post();
469
470 //////////////////////////////////////////////////////////////////////////
471 // Menu
472
473 wxMenuBar* menuBar = new wxMenuBar;
474 SetMenuBar(menuBar);
475
476 wxMenu *menuFile = new wxMenu;
477 menuBar->Append(menuFile, _("&File"));
478 {
479 menuFile->Append(ID_New, _("&New..."));
480 menuFile->Append(ID_Open, _("&Open..."));
481 menuFile->Append(ID_Save, _("&Save"));
482 menuFile->Append(ID_SaveAs, _("Save &As..."));
483 menuFile->AppendSeparator();//-----------
484 menuFile->Append(ID_ImportHeightmap, _("&Import Heightmap..."));
485 menuFile->AppendSeparator();//-----------
486 menuFile->Append(ID_Quit, _("E&xit"));
487 m_FileHistory.UseMenu(menuFile);//-------
488 m_FileHistory.AddFilesToMenu();
489 }
490
491 // m_menuItem_Save = menuFile->FindItem(ID_Save); // remember this item, to let it be greyed out
492 // wxASSERT(m_menuItem_Save);
493
494 wxMenu *menuEdit = new wxMenu;
495 menuBar->Append(menuEdit, _("&Edit"));
496 {
497 menuEdit->Append(wxID_UNDO, _("&Undo"));
498 menuEdit->Append(wxID_REDO, _("&Redo"));
499 menuEdit->AppendSeparator();
500 menuEdit->Append(ID_Copy, _("&Copy"));
501 menuEdit->Enable(ID_Copy, false);
502 menuEdit->Append(ID_Paste, _("&Paste"));
503 menuEdit->Enable(ID_Paste, false);
504 }
505
506 g_SelectedObjects.RegisterObserver(0, &ScenarioEditor::OnSelectedObjectsChange, this);
507
508 GetCommandProc().SetEditMenu(menuEdit);
509 GetCommandProc().Initialize();
510
511
512 wxMenu *menuMisc = new wxMenu;
513 menuBar->Append(menuMisc, _("&Misc hacks"));
514 {
515 menuMisc->AppendCheckItem(ID_Wireframe, _("&Wireframe"));
516 menuMisc->AppendCheckItem(ID_MessageTrace, _("Message debug trace"));
517 menuMisc->Append(ID_Screenshot, _("&Screenshot"));
518 menuMisc->Append(ID_BigScreenshot, _("Big screenshot"));
519 menuMisc->Append(ID_JavaScript, _("&JS console"));
520 menuMisc->Append(ID_CameraReset, _("&Reset camera"));
521
522 wxMenu *menuSS = new wxMenu;
523 menuMisc->AppendSubMenu(menuSS, _("Si&mulation state"));
524 menuSS->Append(ID_DumpState, _("&Dump to disk"));
525 menuSS->Append(ID_DumpBinaryState, _("Dump &binary to disk"));
526 }
527
528 wxMenu *menuHelp = new wxMenu;
529 menuBar->Append(menuHelp, _("&Help"));
530 {
531 wxFileName helpPath (_T("tools/atlas/"));
532 helpPath.MakeAbsolute(Datafile::GetDataDirectory());
533 helpPath.SetFullName("help.json");
534 if (wxFileExists(helpPath.GetFullPath()))
535 {
536 wxFFile helpFile(helpPath.GetFullPath());
537 wxString helpData;
538 helpFile.ReadAll(&helpData);
539 AtObj data = AtlasObject::LoadFromJSON(std::string{helpData.ToUTF8().data()});
540 #define ADD_HELP_ITEM(id) \
541 do { \
542 if (!data[#id].hasContent()) \
543 break; \
544 if (!data[#id]["title"].hasContent() || !data[#id]["url"].hasContent()) \
545 break; \
546 menuHelp->Append(ID_##id, _(wxString(data[#id]["title"])), _(wxString(data[#id]["tooltip"]))); \
547 m_HelpData.insert(std::make_pair( \
548 ID_##id, \
549 HelpItem(wxString::FromUTF8(data[#id]["title"]), wxString::FromUTF8(data[#id]["tooltip"]), wxString::FromUTF8(data[#id]["url"])) \
550 )); \
551 } while (0)
552 ADD_HELP_ITEM(Manual);
553 ADD_HELP_ITEM(ReportBug);
554 #undef ADD_HELP_ITEM
555 }
556 else
557 wxLogError(_("'%ls' does not exist"), helpPath.GetFullPath().c_str());
558 }
559
560 m_FileHistory.LoadFromSubDir(*wxConfigBase::Get());
561
562
563 m_SectionLayout.SetWindow(this);
564
565 // Toolbar:
566 // wxOSX/Cocoa 2.9 doesn't seem to like SetToolBar, so we use CreateToolBar which implicitly associates
567 // the toolbar with the frame, and use OnCreateToolBar to construct our custom toolbar
568 // (this should be equivalent behavior on all platforms)
569 CreateToolBar(wxNO_BORDER|wxTB_FLAT|wxTB_HORIZONTAL, ID_Toolbar)->Realize();
570
571 // Set the default tool to be selected
572 m_ToolManager.SetCurrentTool(_T(""));
573
574
575 // Set up GL canvas:
576
577 int glAttribList[] = {
578 WX_GL_RGBA,
579 WX_GL_DOUBLEBUFFER,
580 WX_GL_DEPTH_SIZE, 24, // TODO: wx documentation doesn't say 24 is valid
581 WX_GL_STENCIL_SIZE, 8,
582 WX_GL_BUFFER_SIZE, 24, // color bits
583 WX_GL_MIN_ALPHA, 8, // alpha bits
584 0
585 };
586 Canvas* canvas = new GameCanvas(*this, m_SectionLayout.GetCanvasParent(), glAttribList);
587 m_SectionLayout.SetCanvas(canvas);
588
589 // Set up sidebars:
590
591 m_SectionLayout.Build(*this);
592
593 #if defined(__WXMSW__)
594 // The canvas' context gets made current on creation; but it can only be
595 // current for one thread at a time, and it needs to be current for the
596 // thread that is doing the draw calls, so disable it for this one.
597 wglMakeCurrent(NULL, NULL);
598 #elif defined(__WXGTK__) || defined(__WXOSX__) || defined(__WXMAC__)
599 // Need to make sure the canvas is realised, so that its context is valid
600 // this solves the "invalid drawable" error
601 Show(true);
602 Raise();
603 #endif
604 #ifdef __WXGTK__
605 // TODO: wxSafeYield causes issues on wxOSX 2.9, is it necessary?
606 wxSafeYield();
607 #endif
608
609 // Send setup messages to game engine:
610
611 // We need to set the window HWND for the error dialog instead of iteraing
612 // through all open windows on Windows.
613 POST_MESSAGE(InitAppWindow, (GetHandle()));
614
615 POST_MESSAGE(InitSDL, ());
616
617 POST_MESSAGE(SetCanvas, (static_cast<wxGLCanvas*>(canvas),
618 canvas->GetClientSize().GetWidth() * canvas->GetContentScaleFactor(),
619 canvas->GetClientSize().GetHeight() * canvas->GetContentScaleFactor()));
620
621 POST_MESSAGE(InitGraphics, ());
622
623 canvas->InitSize();
624
625 // Start with a blank map (so that the editor can assume there's always
626 // a valid map loaded)
627 POST_MESSAGE(LoadMap, (_T("maps/scenarios/_default.xml")));
628 POST_MESSAGE(SimPlay, (0.f, false));
629
630 // Select the initial sidebar (after the map has loaded)
631 m_SectionLayout.SelectPage(_T("MapSidebar"));
632
633 // Wait for blank map
634 qry.Post();
635
636 POST_MESSAGE(RenderEnable, (eRenderView::GAME));
637
638 // Set up a timer to make sure tool-updates happen frequently (in addition
639 // to the idle handler (which makes them happen more frequently if there's nothing
640 // else to do))
641 m_Timer.SetOwner(this, TIMER_TOOL);
642 m_Timer.Start(TIMER_TOOL_INTERVAL); // in ms
643
644 // Set up a timer to trigger engine rendering.
645 // This is split from the tool timer to enable different framerates.
646 m_RenderTimer.SetOwner(this, TIMER_RENDER);
647 m_RenderTimer.Start(TIMER_RENDER_INTERVAL); // in ms
648 }
649
650 wxToolBar* ScenarioEditor::OnCreateToolBar(long style, wxWindowID id, const wxString& WXUNUSED(name))
651 {
652 ToolButtonBar* toolbar = new ToolButtonBar(m_ToolManager, this, &m_SectionLayout, id, style);
653 // TODO: configurable small vs large icon images
654
655 // (button label; tooltip text; image; internal tool name; section to switch to)
656 toolbar->AddToolButton(_("Default"), _("Default"), _T("default.png"), _T(""), _T(""));
657 toolbar->AddToolButton(_("Move"), _("Move/rotate object"), _T("moveobject.png"), _T("TransformObject"), _T("")/*_T("ObjectSidebar")*/);
658 toolbar->AddToolButton(_("Elevation"), _("Alter terrain elevation"), _T("alterelevation.png"), _T("AlterElevation"), _T("")/*_T("TerrainSidebar")*/);
659 toolbar->AddToolButton(_("Smooth"), _("Smooth terrain elevation"), _T("smoothelevation.png"), _T("SmoothElevation"), _T("")/*_T("TerrainSidebar")*/);
660 toolbar->AddToolButton(_("Flatten"), _("Flatten terrain elevation"), _T("flattenelevation.png"), _T("FlattenElevation"), _T("")/*_T("TerrainSidebar")*/);
661 toolbar->AddToolButton(_("Paint Terrain"), _("Paint terrain texture"), _T("paintterrain.png"), _T("PaintTerrain"), _T("")/*_T("TerrainSidebar")*/);
662 toolbar->AddToolButton(_("Move"), _("Move cinema path nodes"), _T("movepath.png"), _T("TransformPath"), _T("")/*_T("CinemaSidebar")*/);
663
664 return toolbar;
665 }
666
667 float ScenarioEditor::GetSpeedModifier()
668 {
669 if (wxGetKeyState(WXK_SHIFT) && wxGetKeyState(WXK_CONTROL))
670 return 1.f/64.f;
671 else if (wxGetKeyState(WXK_CONTROL))
672 return 1.f/4.f;
673 else if (wxGetKeyState(WXK_SHIFT))
674 return 4.f;
675 else
676 return 1.f;
677 }
678
679 void ScenarioEditor::OnClose(wxCloseEvent& event)
680 {
681 if (event.CanVeto() && GetCommandProc().IsDirty())
682 {
683 if (wxMessageBox(_T("You have unsaved changes. Are you sure you want to quit?"), _T("Discard unsaved changes?"), wxICON_QUESTION | wxYES_NO) != wxYES)
684 {
685 event.Veto();
686 return;
687 }
688 }
689
690 m_ToolManager.SetCurrentTool(_T(""));
691
692 m_FileHistory.SaveToSubDir(*wxConfigBase::Get());
693
694 // We notify all clients that might interact with the game after its
695 // shutdown to prevent accessing invalid state.
696 m_SectionLayout.OnShutdown();
697
698 POST_MESSAGE(Shutdown, ());
699
700 qExit().Post();
701 // blocks until engine has noticed the message, so we won't be
702 // destroying the GLCanvas while it's still rendering
703
704 Destroy();
705 }
706
707
708 static void UpdateTool(ToolManager& toolManager)
709 {
710 // TODO: Smoother timing stuff?
711 static double last = g_Timer.GetTime();
712 double time = g_Timer.GetTime();
713 toolManager.GetCurrentTool()->OnTick(time-last);
714 last = time;
715 }
716
717 void ScenarioEditor::OnTimer(wxTimerEvent& evt)
718 {
719 if (evt.GetId() == TIMER_TOOL)
720 UpdateTool(m_ToolManager);
721 else
722 {
723 AtlasMessage::qRenderLoop qryRenderLoop;
724 qryRenderLoop.Post();
725 if (!qryRenderLoop.wantHighFPS &&
726 qryRenderLoop.timeSinceActivity > 1.0 && g_Timer.GetTime() - last_wx_user_activity > 1.0)
727 m_RenderTimer.Start(TIMER_RENDER_SLOW_INTERVAL); // save CPU/GPU when activity is lower.
728 else
729 m_RenderTimer.Start(TIMER_RENDER_INTERVAL);
730 }
731 }
732 void ScenarioEditor::OnIdle(wxIdleEvent&)
733 {
734 UpdateTool(m_ToolManager);
735 }
736
737 void ScenarioEditor::OnQuit(wxCommandEvent&)
738 {
739 Close();
740 }
741
742 void ScenarioEditor::OnUndo(wxCommandEvent&)
743 {
744 GetCommandProc().Undo();
745 }
746
747 void ScenarioEditor::OnRedo(wxCommandEvent&)
748 {
749 GetCommandProc().Redo();
750 }
751
752 void ScenarioEditor::OnCopy(wxCommandEvent& WXUNUSED(event))
753 {
754 if (GetToolManager().GetCurrentToolName() == _T("TransformObject"))
755 GetToolManager().GetCurrentTool()->OnCommand(_T("copy"), NULL);
756 }
757
758 void ScenarioEditor::OnPaste(wxCommandEvent& WXUNUSED(event))
759 {
760 if (GetToolManager().GetCurrentToolName() != _T("TransformObject"))
761 GetToolManager().SetCurrentTool(_T("TransformObject"), NULL);
762
763 GetToolManager().GetCurrentTool()->OnCommand(_T("paste"), NULL);
764 }
765
766 //////////////////////////////////////////////////////////////////////////
767
768 void ScenarioEditor::OnNew(wxCommandEvent& WXUNUSED(event))
769 {
770 if (wxMessageBox(_("Discard current map and start blank new map?"), _("New map"), wxOK|wxCANCEL|wxICON_QUESTION, this) == wxOK)
771 OpenFile(_T(""), _T("maps/scenarios/_default.xml"));
772 }
773
774 bool ScenarioEditor::OpenFile(const wxString& name, const wxString& filename)
775 {
776 wxBusyInfo busy(_("Loading ") + name);
777 wxBusyCursor busyc;
778
779 AtlasMessage::qVFSFileExists qry(filename.ToStdWstring());
780 qry.Post();
781 if (!qry.exists)
782 return false;
783
784 // Deactivate tools, so they don't carry forwards into the new CWorld
785 // and crash.
786 m_ToolManager.SetCurrentTool(_T(""));
787 // TODO: clear the undo buffer, etc
788
789 std::wstring map(filename.ToStdWstring());
790 POST_MESSAGE(LoadMap, (map));
791
792 SetOpenFilename(name);
793
794 { // Wait for it to load, while the wxBusyInfo is telling the user that we're doing that
795 qPing pingQuery;
796 pingQuery.Post();
797 }
798
799 NotifyOnMapReload();
800
801 GetCommandProc().ClearCommands();
802
803 return true;
804 // TODO: Make this a non-undoable command
805 }
806
807 // TODO (eventually): replace all this file-handling stuff with the Workspace Editor
808
809 void ScenarioEditor::OnOpen(wxCommandEvent& WXUNUSED(event))
810 {
811 if (DiscardChangesDialog())
812 return;
813
814 MapDialog dlg (NULL, MAPDIALOG_OPEN, m_Icon);
815 if (dlg.ShowModal() == wxID_OK)
816 {
817 wxString filePath = dlg.GetSelectedFilePath();
818 if (!OpenFile(filePath, filePath))
819 wxLogError(_("Map '%ls' does not exist"), filePath.c_str());
820 }
821
822 // TODO: Make this a non-undoable command
823 }
824
825 void ScenarioEditor::OnImportHeightmap(wxCommandEvent& WXUNUSED(event))
826 {
827 if (DiscardChangesDialog())
828 return;
829
830 wxFileDialog dlg (NULL, wxFileSelectorPromptStr,
831 _T(""), _T(""),
832 _T("Valid image files (*.png, *.bmp)|*.png;*.bmp|All files (*.*)|*.*"),
833 wxFD_OPEN);
834 // Set default filter
835 dlg.SetFilterIndex(0);
836
837 if (dlg.ShowModal() != wxID_OK)
838 return;
839
840 OpenFile(_T(""), _T("maps/scenarios/_default.xml"));
841
842 std::wstring image(dlg.GetPath().ToStdWstring());
843 POST_MESSAGE(ImportHeightmap, (image));
844
845 // TODO: Make this a non-undoable command
846 }
847
848 void ScenarioEditor::OnMRUFile(wxCommandEvent& event)
849 {
850 wxString filename(m_FileHistory.GetHistoryFile(event.GetId() - wxID_FILE1));
851
852 // Handle old MRU filenames
853 if (filename.Mid(0, 5) != _T("maps/"))
854 {
855 filename = L"maps/scenarios/" + filename;
856 m_FileHistory.RemoveFileFromHistory(event.GetId() - wxID_FILE1);
857 }
858
859 if (DiscardChangesDialog())
860 return;
861
862 if (!OpenFile(filename, filename))
863 {
864 // Missing or invalid - warn and remove from MRU
865 wxLogError(_("Map '%ls' does not exist"), filename.c_str());
866 m_FileHistory.RemoveFileFromHistory(event.GetId() - wxID_FILE1);
867 }
868 }
869
870 void ScenarioEditor::OnSave(wxCommandEvent& event)
871 {
872 if (m_OpenFilename.IsEmpty())
873 {
874 OnSaveAs(event);
875 }
876 else
877 {
878 wxBusyInfo busy(_("Saving ") + m_OpenFilename);
879 wxBusyCursor busyc;
880
881 // Deactivate tools, so things like unit previews don't get saved.
882 // (TODO: Would be nicer to leave the tools active, and just not save
883 // the preview units.)
884 m_ToolManager.SetCurrentTool(_T(""));
885
886 std::wstring map(m_OpenFilename.ToStdWstring());
887 POST_MESSAGE(SaveMap, (map));
888
889 // Wait for it to finish saving
890 qPing qry;
891 qry.Post();
892
893 GetCommandProc().MarkAsSaved();
894 }
895 }
896
897 void ScenarioEditor::OnSaveAs(wxCommandEvent& WXUNUSED(event))
898 {
899 MapDialog dlg(NULL, MAPDIALOG_SAVE, m_Icon);
900 if (dlg.ShowModal() == wxID_OK)
901 {
902 wxString filePath(dlg.GetSelectedFilePath());
903 wxBusyInfo busy(_("Saving ") + filePath);
904 wxBusyCursor busyc;
905
906 m_ToolManager.SetCurrentTool(_T(""));
907
908 std::wstring map(filePath.ToStdWstring());
909 POST_MESSAGE(SaveMap, (map));
910
911 SetOpenFilename(filePath);
912
913 // Wait for it to finish saving
914 qPing qry;
915 qry.Post();
916
917 GetCommandProc().MarkAsSaved();
918 }
919 }
920
921 void ScenarioEditor::SetOpenFilename(const wxString& filename)
922 {
923 SetTitle(wxString::Format(_("Atlas - Scenario Editor - %s"),
924 (filename.IsEmpty() ? wxString(_("(untitled)")) : filename).c_str()));
925
926 m_OpenFilename = filename;
927
928 if (! filename.IsEmpty())
929 m_FileHistory.AddFileToHistory(filename);
930 }
931
932 void ScenarioEditor::NotifyOnMapReload()
933 {
934 m_SectionLayout.OnMapReload();
935
936 // Notify observers, here so it's independent of individual panels
937 m_MapSettings.NotifyObservers();
938 }
939
940 bool ScenarioEditor::DiscardChangesDialog()
941 {
942 return GetCommandProc().IsDirty() &&
943 wxMessageBox(_T("You have unsaved changes. Are you sure you want to open another map?"), _T("Discard unsaved changes?"), wxICON_QUESTION | wxYES_NO) != wxYES;
944 }
945
946 //////////////////////////////////////////////////////////////////////////
947
948 void ScenarioEditor::OnWireframe(wxCommandEvent& event)
949 {
950 POST_MESSAGE(RenderStyle, (event.IsChecked()));
951 }
952
953 void ScenarioEditor::OnMessageTrace(wxCommandEvent& event)
954 {
955 POST_MESSAGE(MessageTrace, (event.IsChecked()));
956 }
957
958 void ScenarioEditor::OnScreenshot(wxCommandEvent& event)
959 {
960 switch (event.GetId())
961 {
962 case ID_BigScreenshot:
963 POST_MESSAGE(Screenshot, (true));
964 break;
965 case ID_Screenshot:
966 POST_MESSAGE(Screenshot, (false));
967 break;
968 }
969 }
970
971 void ScenarioEditor::OnJavaScript(wxCommandEvent& WXUNUSED(event))
972 {
973 wxString cmd = ::wxGetTextFromUser(_T(""), _("JS command"), _T(""), this);
974 if (cmd.IsEmpty())
975 return;
976 POST_MESSAGE(JavaScript, (std::string(cmd.ToUTF8())));
977 }
978
979 void ScenarioEditor::OnCameraReset(wxCommandEvent& WXUNUSED(event))
980 {
981 POST_MESSAGE(CameraReset, ());
982 }
983
984 void ScenarioEditor::OnDumpState(wxCommandEvent& event)
985 {
986 wxDateTime time = wxDateTime::Now();
987 wxString filename;
988 bool doBinary = false;
989
990 switch (event.GetId())
991 {
992 case ID_DumpState:
993 filename = wxString::Format(_T("sim-dump-%d.txt"), time.GetTicks());
994 break;
995 case ID_DumpBinaryState:
996 doBinary = true;
997 filename = wxString::Format(_T("sim-dump-%d.dat"), time.GetTicks());
998 break;
999 }
1000
1001 qSimStateDebugDump q(doBinary);
1002 q.Post();
1003
1004 std::wstring dump = *q.dump;
1005 wxString state(dump.c_str());
1006
1007 wxFFile file(filename.c_str(), _T("w"));
1008 if (file.IsOpened() && !file.Error())
1009 {
1010 file.Write(state);
1011 file.Close();
1012 }
1013 else
1014 {
1015 wxLogError(_("Error writing to file '%ls'"), filename.c_str());
1016 }
1017 }
1018
1019 void ScenarioEditor::OnSelectedObjectsChange(const std::vector<ObjectID>& selectedObjects)
1020 {
1021 GetMenuBar()->Enable(ID_Copy, !selectedObjects.empty());
1022 }
1023
1024 void ScenarioEditor::OnHelp(wxCommandEvent& event)
1025 {
1026 std::map<int, HelpItem>::const_iterator it = m_HelpData.find(event.GetId());
1027 if (it == m_HelpData.end())
1028 return;
1029 wxMessageDialog* dialog = new wxMessageDialog(
1030 nullptr, _("Do you want to open '" + it->second.m_URL + "'?"),
1031 _("Atlas"), wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION
1032 );
1033 if (dialog->ShowModal() == wxID_YES)
1034 wxLaunchDefaultBrowser(it->second.m_URL);
1035 }
1036
1037 void ScenarioEditor::OnMenuOpen(wxMenuEvent& event)
1038 {
1039 // Ignore wxMSW system menu events, see https://gitea.wildfiregames.com/0ad/0ad/issues/5501
1040 const wxMenu* menu = event.GetMenu();
1041 if (!menu)
1042 return;
1043
1044 // This could be done far more elegantly if wxMenuItem had changeable id.
1045 wxMenu* pasteMenuItem = NULL;
1046 menu->FindItem(ID_Paste, &pasteMenuItem);
1047
1048 GetMenuBar()->Enable(ID_Paste, false);
1049
1050 if (!pasteMenuItem)
1051 return;
1052
1053 wxString content;
1054 if (wxTheClipboard->Open())
1055 {
1056 if (wxTheClipboard->IsSupported(wxDF_TEXT))
1057 {
1058 wxTextDataObject data;
1059 wxTheClipboard->GetData(data);
1060 content = data.GetText();
1061 }
1062
1063 wxTheClipboard->Close();
1064 }
1065
1066 if (content.empty())
1067 return;
1068
1069 wxInputStream* is = new wxStringInputStream(content);
1070 wxXmlDocument doc;
1071 {
1072 wxLogNull stopComplaining;
1073 static_cast<void>(stopComplaining);
1074 if (!doc.Load(*is))
1075 return;
1076 }
1077
1078 wxXmlNode* root = doc.GetRoot();
1079 if (!root || root->GetName() != wxT("Entities"))
1080 return;
1081
1082 GetMenuBar()->Enable(ID_Paste, true);
1083 }
1084
1085
1086 //////////////////////////////////////////////////////////////////////////
1087
1088 Position::Position(const wxPoint& pt)
1089 : type(1)
1090 {
1091 type1.x = pt.x;
1092 type1.y = pt.y;
1093 }
1094
1095 //////////////////////////////////////////////////////////////////////////
1096
1097 /* Disabled (and should be removed if it turns out to be unnecessary)
1098 - see MessagePasserImpl.cpp for information
1099
1100 static void QueryCallback()
1101 {
1102 // If this thread completely blocked on the semaphore inside Query, it would
1103 // never respond to window messages, and the system deadlocks if the
1104 // game tries to display an assertion failure dialog. (See
1105 // WaitForSingleObject on MSDN.)
1106 // So, this callback is called occasionally, and gives wx a change to
1107 // handle messages.
1108
1109 // This is kind of like wxYield, but without the ProcessPendingEvents -
1110 // it's enough to make Windows happy and stop deadlocking, without actually
1111 // calling the event handlers (which could lead to nasty recursion)
1112
1113 // while (wxEventLoop::GetActive()->Pending())
1114 // wxEventLoop::GetActive()->Dispatch();
1115
1116 // Oh dear, we can't use that either - it (at least in wx 2.6.3) still
1117 // processes messages, which causes reentry into various things that we
1118 // don't want to be reentrant. So do it all manually, accepting Windows
1119 // messages and sticking them on a list for later processing (in a custom
1120 // event loop class):
1121
1122 // (TODO: Rethink this entire process on Linux)
1123 // (Alt TODO: Could we make the game never pop up windows (or use the Win32
1124 // GUI in any other way) when it's running under Atlas, so we wouldn't need
1125 // to do any message processing here at all?)
1126
1127 #ifdef _WIN32
1128 AtlasEventLoop* evtLoop = (AtlasEventLoop*)wxEventLoop::GetActive();
1129
1130 // evtLoop might be NULL, particularly if we're still initialising windows
1131 // and haven't got into the normal event loop yet. But we'd have to process
1132 // messages anyway, to avoid the deadlocks that this is for. So, don't bother
1133 // with that and just crash instead.
1134 // (Maybe it could be solved better by constructing/finding an event loop
1135 // object here and setting it as the global one, assuming it's not overwritten
1136 // later by wx.)
1137
1138 while (evtLoop->Pending())
1139 {
1140 // Based on src/msw/evtloop.cpp's wxEventLoop::Dispatch()
1141
1142 MSG msg;
1143 BOOL rc = ::GetMessage(&msg, (HWND) NULL, 0, 0);
1144
1145 if (rc == 0)
1146 {
1147 // got WM_QUIT
1148 return;
1149 }
1150
1151 if (rc == -1)
1152 {
1153 wxLogLastError(wxT("GetMessage"));
1154 return;
1155 }
1156
1157 // Our special bits:
1158
1159 if (msg.message == WM_PAINT)
1160 {
1161 // "GetMessage does not remove WM_PAINT messages from the queue.
1162 // The messages remain in the queue until processed."
1163 // So let's process them, to avoid infinite loops...
1164 PAINTSTRUCT paint;
1165 ::BeginPaint(msg.hwnd, &paint);
1166 ::EndPaint(msg.hwnd, &paint);
1167 // Remember that some painting was needed - we'll just repaint
1168 // the whole screen when this is finished.
1169 evtLoop->NeedsPaint();
1170 }
1171 else
1172 {
1173 // Add this message to a queue for later processing. (That's
1174 // probably kind of valid, at least in most cases.)
1175 MSG* pMsg = new MSG(msg);
1176 evtLoop->AddMessage(pMsg);
1177 }
1178 }
1179 #endif
1180 }
1181 */
1182 void QueryMessage::Post()
1183 {
1184 // g_MessagePasser->Query(this, &QueryCallback);
1185 g_MessagePasser->Query(this, NULL);
1186 }