Pyrogenesis  13997
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
ScriptFunctions.cpp
Go to the documentation of this file.
1 /* Copyright (C) 2013 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 
21 
22 #include "graphics/Camera.h"
23 #include "graphics/GameView.h"
24 #include "graphics/MapReader.h"
25 #include "gui/GUIManager.h"
27 #include "lib/timer.h"
28 #include "lib/utf8.h"
29 #include "lib/sysdep/sysdep.h"
30 #include "maths/FixedVector3D.h"
31 #include "network/NetClient.h"
32 #include "network/NetServer.h"
33 #include "network/NetTurnManager.h"
34 #include "ps/CLogger.h"
35 #include "ps/CConsole.h"
36 #include "ps/Errors.h"
37 #include "ps/Game.h"
38 #include "ps/World.h"
39 #include "ps/Hotkey.h"
40 #include "ps/Overlay.h"
41 #include "ps/ProfileViewer.h"
42 #include "ps/Pyrogenesis.h"
43 #include "ps/SavedGame.h"
46 #include "ps/UserReport.h"
47 #include "ps/GameSetup/Atlas.h"
48 #include "ps/GameSetup/Config.h"
49 #include "ps/ConfigDB.h"
51 #include "tools/atlas/GameInterface/GameLoop.h"
52 
61 
62 #include "js/jsapi.h"
63 
64 /*
65  * This file defines a set of functions that are available to GUI scripts, to allow
66  * interaction with the rest of the engine.
67  * Functions are exposed to scripts within the global object 'Engine', so
68  * scripts should call "Engine.FunctionName(...)" etc.
69  */
70 
71 extern void restart_mainloop_in_atlas(); // from main.cpp
72 
73 namespace {
74 
76 {
77  return OBJECT_TO_JSVAL(g_GUI->GetScriptObject());
78 }
79 
80 void PushGuiPage(void* UNUSED(cbdata), std::wstring name, CScriptVal initData)
81 {
82  g_GUI->PushPage(name, initData);
83 }
84 
85 void SwitchGuiPage(void* UNUSED(cbdata), std::wstring name, CScriptVal initData)
86 {
87  g_GUI->SwitchPage(name, initData);
88 }
89 
90 void PopGuiPage(void* UNUSED(cbdata))
91 {
92  g_GUI->PopPage();
93 }
94 
95 CScriptVal GuiInterfaceCall(void* cbdata, std::wstring name, CScriptVal data)
96 {
97  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
98 
99  if (!g_Game)
100  return JSVAL_VOID;
102  ENSURE(sim);
103 
104  CmpPtr<ICmpGuiInterface> cmpGuiInterface(*sim, SYSTEM_ENTITY);
105  if (!cmpGuiInterface)
106  return JSVAL_VOID;
107 
108  int player = -1;
109  if (g_Game)
110  player = g_Game->GetPlayerID();
111 
113  CScriptVal ret (cmpGuiInterface->ScriptCall(player, name, arg.get()));
114  return guiManager->GetScriptInterface().CloneValueFromOtherContext(sim->GetScriptInterface(), ret.get());
115 }
116 
117 void PostNetworkCommand(void* cbdata, CScriptVal cmd)
118 {
119  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
120 
121  if (!g_Game)
122  return;
124  ENSURE(sim);
125 
126  CmpPtr<ICmpCommandQueue> cmpCommandQueue(*sim, SYSTEM_ENTITY);
127  if (!cmpCommandQueue)
128  return;
129 
130  jsval cmd2 = sim->GetScriptInterface().CloneValueFromOtherContext(guiManager->GetScriptInterface(), cmd.get());
131 
132  cmpCommandQueue->PostNetworkCommand(cmd2);
133 }
134 
135 std::vector<entity_id_t> PickEntitiesAtPoint(void* UNUSED(cbdata), int x, int y)
136 {
138 }
139 
140 std::vector<entity_id_t> PickFriendlyEntitiesInRect(void* UNUSED(cbdata), int x0, int y0, int x1, int y1, int player)
141 {
142  return EntitySelection::PickEntitiesInRect(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), x0, y0, x1, y1, player, false);
143 }
144 
145 std::vector<entity_id_t> PickFriendlyEntitiesOnScreen(void* cbdata, int player)
146 {
147  return PickFriendlyEntitiesInRect(cbdata, 0, 0, g_xres, g_yres, player);
148 }
149 
150 std::vector<entity_id_t> PickSimilarFriendlyEntities(void* UNUSED(cbdata), std::string templateName, bool includeOffScreen, bool matchRank, bool allowFoundations)
151 {
152  return EntitySelection::PickSimilarEntities(*g_Game->GetSimulation2(), *g_Game->GetView()->GetCamera(), templateName, g_Game->GetPlayerID(), includeOffScreen, matchRank, false, allowFoundations);
153 }
154 
155 CFixedVector3D GetTerrainAtScreenPoint(void* UNUSED(cbdata), int x, int y)
156 {
157  CVector3D pos = g_Game->GetView()->GetCamera()->GetWorldCoordinates(x, y, true);
159 }
160 
161 std::wstring SetCursor(void* UNUSED(cbdata), std::wstring name)
162 {
163  std::wstring old = g_CursorName;
164  g_CursorName = name;
165  return old;
166 }
167 
168 int GetPlayerID(void* UNUSED(cbdata))
169 {
170  if (g_Game)
171  return g_Game->GetPlayerID();
172  return -1;
173 }
174 
175 void SetPlayerID(void* UNUSED(cbdata), int id)
176 {
177  if (g_Game)
178  g_Game->SetPlayerID(id);
179 }
180 
181 std::wstring GetDefaultPlayerName(void* UNUSED(cbdata))
182 {
183  CStr playername;
184  CFG_GET_VAL("playername", String, playername);
185  std::wstring name = playername.FromUTF8();
186  if (!name.empty())
187  return name;
188 
189  name = sys_get_user_name();
190  if (!name.empty())
191  return name;
192 
193  return L"anonymous";
194 }
195 
196 std::wstring GetDefaultMPServer(void* UNUSED(cbdata))
197 {
198  CStr server;
199  CFG_GET_VAL("multiplayerserver", String, server);
200  return server.FromUTF8();
201 }
202 
203 void SaveMPConfig(void* UNUSED(cbdata), std::wstring playerName, std::wstring server)
204 {
205  g_ConfigDB.CreateValue(CFG_USER, "playername")->m_String = CStrW(playerName).ToUTF8();
206  g_ConfigDB.CreateValue(CFG_USER, "multiplayerserver")->m_String = CStrW(server).ToUTF8();
207  g_ConfigDB.WriteFile(CFG_USER);
208 }
209 
210 void StartNetworkGame(void* UNUSED(cbdata))
211 {
214 }
215 
216 void StartGame(void* cbdata, CScriptVal attribs, int playerID)
217 {
218  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
219 
222 
223  ENSURE(!g_Game);
224  g_Game = new CGame();
225 
226  // Convert from GUI script context to sim script context
228  CScriptValRooted gameAttribs (sim->GetScriptInterface().GetContext(),
229  sim->GetScriptInterface().CloneValueFromOtherContext(guiManager->GetScriptInterface(), attribs.get()));
230 
231  g_Game->SetPlayerID(playerID);
232  g_Game->StartGame(gameAttribs, "");
233 }
234 
235 CScriptVal StartSavedGame(void* cbdata, std::wstring name)
236 {
237  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
238 
241 
242  ENSURE(!g_Game);
243 
244  // Load the saved game data from disk
245  CScriptValRooted metadata;
246  std::string savedState;
247  Status err = SavedGames::Load(name, guiManager->GetScriptInterface(), metadata, savedState);
248  if (err < 0)
249  return CScriptVal();
250 
251  g_Game = new CGame();
252 
253  // Convert from GUI script context to sim script context
255  CScriptValRooted gameMetadata (sim->GetScriptInterface().GetContext(),
256  sim->GetScriptInterface().CloneValueFromOtherContext(guiManager->GetScriptInterface(), metadata.get()));
257 
258  CScriptValRooted gameInitAttributes;
259  sim->GetScriptInterface().GetProperty(gameMetadata.get(), "initAttributes", gameInitAttributes);
260 
261  int playerID;
262  sim->GetScriptInterface().GetProperty(gameMetadata.get(), "player", playerID);
263 
264  // Start the game
265  g_Game->SetPlayerID(playerID);
266  g_Game->StartGame(gameInitAttributes, savedState);
267 
268  return metadata.get();
269 }
270 
271 void SaveGame(void* cbdata, std::wstring filename, std::wstring description)
272 {
273  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
274 
275  if (SavedGames::Save(filename, description, *g_Game->GetSimulation2(), guiManager, g_Game->GetPlayerID()) < 0)
276  LOGERROR(L"Failed to save game");
277 }
278 
279 void SaveGamePrefix(void* cbdata, std::wstring prefix, std::wstring description)
280 {
281  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
282 
283  if (SavedGames::SavePrefix(prefix, description, *g_Game->GetSimulation2(), guiManager, g_Game->GetPlayerID()) < 0)
284  LOGERROR(L"Failed to save game");
285 }
286 
287 void SetNetworkGameAttributes(void* cbdata, CScriptVal attribs)
288 {
289  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
290 
292 
293  g_NetServer->UpdateGameAttributes(attribs, guiManager->GetScriptInterface());
294 }
295 
296 void StartNetworkHost(void* cbdata, std::wstring playerName)
297 {
298  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
299 
302  ENSURE(!g_Game);
303 
304  g_NetServer = new CNetServer();
306  {
307  guiManager->GetScriptInterface().ReportError("Failed to start server");
309  return;
310  }
311 
312  g_Game = new CGame();
314  g_NetClient->SetUserName(playerName);
315 
316  if (!g_NetClient->SetupConnection("127.0.0.1"))
317  {
318  guiManager->GetScriptInterface().ReportError("Failed to connect to server");
321  }
322 }
323 
324 void StartNetworkJoin(void* cbdata, std::wstring playerName, std::string serverAddress)
325 {
326  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
327 
330  ENSURE(!g_Game);
331 
332  g_Game = new CGame();
334  g_NetClient->SetUserName(playerName);
335  if (!g_NetClient->SetupConnection(serverAddress))
336  {
337  guiManager->GetScriptInterface().ReportError("Failed to connect to server");
340  }
341 }
342 
343 void DisconnectNetworkGame(void* UNUSED(cbdata))
344 {
345  // TODO: we ought to do async reliable disconnections
346 
350 }
351 
353 {
354  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
355 
356  if (!g_NetClient)
357  return CScriptVal();
358 
360 
361  // Convert from net client context to GUI script context
363 }
364 
365 void AssignNetworkPlayer(void* UNUSED(cbdata), int playerID, std::string guid)
366 {
368 
369  g_NetServer->AssignPlayer(playerID, guid);
370 }
371 
372 void SendNetworkChat(void* UNUSED(cbdata), std::wstring message)
373 {
375 
376  g_NetClient->SendChatMessage(message);
377 }
378 
379 std::vector<CScriptValRooted> GetAIs(void* cbdata)
380 {
381  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
382 
383  return ICmpAIManager::GetAIs(guiManager->GetScriptInterface());
384 }
385 
386 std::vector<CScriptValRooted> GetSavedGames(void* cbdata)
387 {
388  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
389 
390  return SavedGames::GetSavedGames(guiManager->GetScriptInterface());
391 }
392 
393 bool DeleteSavedGame(void* UNUSED(cbdata), std::wstring name)
394 {
395  return SavedGames::DeleteSavedGame(name);
396 }
397 
398 void OpenURL(void* UNUSED(cbdata), std::string url)
399 {
400  sys_open_url(url);
401 }
402 
403 void RestartInAtlas(void* UNUSED(cbdata))
404 {
406 }
407 
408 bool AtlasIsAvailable(void* UNUSED(cbdata))
409 {
410  return ATLAS_IsAvailable();
411 }
412 
413 bool IsAtlasRunning(void* UNUSED(cbdata))
414 {
415  return (g_AtlasGameLoop && g_AtlasGameLoop->running);
416 }
417 
418 CScriptVal LoadMapSettings(void* cbdata, VfsPath pathname)
419 {
420  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
421 
422  CMapSummaryReader reader;
423 
424  if (reader.LoadMap(pathname) != PSRETURN_OK)
425  return CScriptVal();
426 
427  return reader.GetMapSettings(guiManager->GetScriptInterface()).get();
428 }
429 
431 {
432  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
433 
434  if (!g_Game)
435  return CScriptVal();
436 
437  return guiManager->GetScriptInterface().CloneValueFromOtherContext(
440 }
441 
442 /**
443  * Get the current X coordinate of the camera.
444  */
445 float CameraGetX(void* UNUSED(cbdata))
446 {
447  if (g_Game && g_Game->GetView())
448  return g_Game->GetView()->GetCameraX();
449  return -1;
450 }
451 
452 /**
453  * Get the current Z coordinate of the camera.
454  */
455 float CameraGetZ(void* UNUSED(cbdata))
456 {
457  if (g_Game && g_Game->GetView())
458  return g_Game->GetView()->GetCameraZ();
459  return -1;
460 }
461 
462 /**
463  * Start / stop camera following mode
464  * @param entityid unit id to follow. If zero, stop following mode
465  */
466 void CameraFollow(void* UNUSED(cbdata), entity_id_t entityid)
467 {
468  if (g_Game && g_Game->GetView())
469  g_Game->GetView()->CameraFollow(entityid, false);
470 }
471 
472 /**
473  * Start / stop first-person camera following mode
474  * @param entityid unit id to follow. If zero, stop following mode
475  */
476 void CameraFollowFPS(void* UNUSED(cbdata), entity_id_t entityid)
477 {
478  if (g_Game && g_Game->GetView())
479  g_Game->GetView()->CameraFollow(entityid, true);
480 }
481 
482 /// Move camera to a 2D location
483 void CameraMoveTo(void* UNUSED(cbdata), entity_pos_t x, entity_pos_t z)
484 {
485  // called from JS; must not fail
486  if(!(g_Game && g_Game->GetWorld() && g_Game->GetView() && g_Game->GetWorld()->GetTerrain()))
487  return;
488 
489  CTerrain* terrain = g_Game->GetWorld()->GetTerrain();
490 
491  CVector3D target;
492  target.X = x.ToFloat();
493  target.Z = z.ToFloat();
494  target.Y = terrain->GetExactGroundLevel(target.X, target.Z);
495 
496  g_Game->GetView()->MoveCameraTarget(target);
497 }
498 
500 {
501  if (g_Game && g_Game->GetView())
502  return g_Game->GetView()->GetFollowedEntity();
503 
504  return INVALID_ENTITY;
505 }
506 
507 bool HotkeyIsPressed_(void* UNUSED(cbdata), std::string hotkeyName)
508 {
509  return HotkeyIsPressed(hotkeyName);
510 }
511 
512 void DisplayErrorDialog(void* UNUSED(cbdata), std::wstring msg)
513 {
514  debug_DisplayError(msg.c_str(), DE_NO_DEBUG_INFO, NULL, NULL, NULL, 0, NULL, NULL);
515 }
516 
518 {
519  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
520 
521  return g_ProfileViewer.SaveToJS(guiManager->GetScriptInterface());
522 }
523 
524 
525 bool IsUserReportEnabled(void* UNUSED(cbdata))
526 {
528 }
529 
530 bool IsSplashScreenEnabled(void* UNUSED(cbdata))
531 {
532  bool splashScreenEnable = true;
533  CFG_GET_VAL("splashscreenenable", Bool, splashScreenEnable);
534  return splashScreenEnable;
535 }
536 
537 void SetSplashScreenEnabled(void* UNUSED(cbdata), bool enabled)
538 {
539  CStr val = (enabled ? "true" : "false");
540  g_ConfigDB.CreateValue(CFG_USER, "splashscreenenable")->m_String = val;
541  g_ConfigDB.WriteFile(CFG_USER);
542 }
543 
544 
545 void SetUserReportEnabled(void* UNUSED(cbdata), bool enabled)
546 {
548 }
549 
550 std::string GetUserReportStatus(void* UNUSED(cbdata))
551 {
552  return g_UserReporter.GetStatus();
553 }
554 
555 void SubmitUserReport(void* UNUSED(cbdata), std::string type, int version, std::wstring data)
556 {
557  g_UserReporter.SubmitReport(type.c_str(), version, utf8_from_wstring(data));
558 }
559 
560 
561 
562 void SetSimRate(void* UNUSED(cbdata), float rate)
563 {
564  g_Game->SetSimRate(rate);
565 }
566 
567 float GetSimRate(void* UNUSED(cbdata))
568 {
569  return g_Game->GetSimRate();
570 }
571 
572 void SetTurnLength(void* UNUSED(cbdata), int length)
573 {
574  if (g_NetServer)
575  g_NetServer->SetTurnLength(length);
576  else
577  LOGERROR(L"Only network host can change turn length");
578 }
579 
580 // Focus the game camera on a given position.
581 void SetCameraTarget(void* UNUSED(cbdata), float x, float y, float z)
582 {
584 }
585 
586 // Deliberately cause the game to crash.
587 // Currently implemented via access violation (read of address 0).
588 // Useful for testing the crashlog/stack trace code.
589 int Crash(void* UNUSED(cbdata))
590 {
591  debug_printf(L"Crashing at user's request.\n");
592  return *(volatile int*)0;
593 }
594 
595 void DebugWarn(void* UNUSED(cbdata))
596 {
597  debug_warn(L"Warning at user's request.");
598 }
599 
600 // Force a JS garbage collection cycle to take place immediately.
601 // Writes an indication of how long this took to the console.
602 void ForceGC(void* cbdata)
603 {
604  CGUIManager* guiManager = static_cast<CGUIManager*> (cbdata);
605 
606  double time = timer_Time();
607  JS_GC(guiManager->GetScriptInterface().GetContext());
608  time = timer_Time() - time;
609  g_Console->InsertMessage(L"Garbage collection completed in: %f", time);
610 }
611 
612 void DumpSimState(void* UNUSED(cbdata))
613 {
614  OsPath path = psLogDir()/"sim_dump.txt";
615  std::ofstream file (OsString(path).c_str(), std::ofstream::out | std::ofstream::trunc);
617 }
618 
619 void DumpTerrainMipmap(void* UNUSED(cbdata))
620 {
621  VfsPath filename(L"screenshots/terrainmipmap.png");
623  OsPath realPath;
624  g_VFS->GetRealPath(filename, realPath);
625  LOGMESSAGERENDER(L"Terrain mipmap written to '%ls'", realPath.string().c_str());
626 }
627 
628 void EnableTimeWarpRecording(void* UNUSED(cbdata), unsigned int numTurns)
629 {
631 }
632 
633 void RewindTimeWarp(void* UNUSED(cbdata))
634 {
636 }
637 
638 void QuickSave(void* UNUSED(cbdata))
639 {
641 }
642 
643 void QuickLoad(void* UNUSED(cbdata))
644 {
646 }
647 
648 void SetBoundingBoxDebugOverlay(void* UNUSED(cbdata), bool enabled)
649 {
651 }
652 
653 } // namespace
654 
655 void GuiScriptingInit(ScriptInterface& scriptInterface)
656 {
657  JSI_GameView::RegisterScriptFunctions(scriptInterface);
658  JSI_Renderer::RegisterScriptFunctions(scriptInterface);
659  JSI_Console::RegisterScriptFunctions(scriptInterface);
660  JSI_ConfigDB::RegisterScriptFunctions(scriptInterface);
661 
662  // GUI manager functions:
663  scriptInterface.RegisterFunction<CScriptVal, &GetActiveGui>("GetActiveGui");
664  scriptInterface.RegisterFunction<void, std::wstring, CScriptVal, &PushGuiPage>("PushGuiPage");
665  scriptInterface.RegisterFunction<void, std::wstring, CScriptVal, &SwitchGuiPage>("SwitchGuiPage");
666  scriptInterface.RegisterFunction<void, &PopGuiPage>("PopGuiPage");
667 
668  // Simulation<->GUI interface functions:
669  scriptInterface.RegisterFunction<CScriptVal, std::wstring, CScriptVal, &GuiInterfaceCall>("GuiInterfaceCall");
670  scriptInterface.RegisterFunction<void, CScriptVal, &PostNetworkCommand>("PostNetworkCommand");
671 
672  // Entity picking
673  scriptInterface.RegisterFunction<std::vector<entity_id_t>, int, int, &PickEntitiesAtPoint>("PickEntitiesAtPoint");
674  scriptInterface.RegisterFunction<std::vector<entity_id_t>, int, int, int, int, int, &PickFriendlyEntitiesInRect>("PickFriendlyEntitiesInRect");
675  scriptInterface.RegisterFunction<std::vector<entity_id_t>, int, &PickFriendlyEntitiesOnScreen>("PickFriendlyEntitiesOnScreen");
676  scriptInterface.RegisterFunction<std::vector<entity_id_t>, std::string, bool, bool, bool, &PickSimilarFriendlyEntities>("PickSimilarFriendlyEntities");
677  scriptInterface.RegisterFunction<CFixedVector3D, int, int, &GetTerrainAtScreenPoint>("GetTerrainAtScreenPoint");
678 
679  // Network / game setup functions
680  scriptInterface.RegisterFunction<void, &StartNetworkGame>("StartNetworkGame");
681  scriptInterface.RegisterFunction<void, CScriptVal, int, &StartGame>("StartGame");
682  scriptInterface.RegisterFunction<void, std::wstring, &StartNetworkHost>("StartNetworkHost");
683  scriptInterface.RegisterFunction<void, std::wstring, std::string, &StartNetworkJoin>("StartNetworkJoin");
684  scriptInterface.RegisterFunction<void, &DisconnectNetworkGame>("DisconnectNetworkGame");
685  scriptInterface.RegisterFunction<CScriptVal, &PollNetworkClient>("PollNetworkClient");
686  scriptInterface.RegisterFunction<void, CScriptVal, &SetNetworkGameAttributes>("SetNetworkGameAttributes");
687  scriptInterface.RegisterFunction<void, int, std::string, &AssignNetworkPlayer>("AssignNetworkPlayer");
688  scriptInterface.RegisterFunction<void, std::wstring, &SendNetworkChat>("SendNetworkChat");
689  scriptInterface.RegisterFunction<std::vector<CScriptValRooted>, &GetAIs>("GetAIs");
690 
691  // Saved games
692  scriptInterface.RegisterFunction<CScriptVal, std::wstring, &StartSavedGame>("StartSavedGame");
693  scriptInterface.RegisterFunction<std::vector<CScriptValRooted>, &GetSavedGames>("GetSavedGames");
694  scriptInterface.RegisterFunction<bool, std::wstring, &DeleteSavedGame>("DeleteSavedGame");
695  scriptInterface.RegisterFunction<void, std::wstring, std::wstring, &SaveGame>("SaveGame");
696  scriptInterface.RegisterFunction<void, std::wstring, std::wstring, &SaveGamePrefix>("SaveGamePrefix");
697  scriptInterface.RegisterFunction<void, &QuickSave>("QuickSave");
698  scriptInterface.RegisterFunction<void, &QuickLoad>("QuickLoad");
699 
700  // Misc functions
701  scriptInterface.RegisterFunction<std::wstring, std::wstring, &SetCursor>("SetCursor");
702  scriptInterface.RegisterFunction<int, &GetPlayerID>("GetPlayerID");
703  scriptInterface.RegisterFunction<void, int, &SetPlayerID>("SetPlayerID");
704  scriptInterface.RegisterFunction<std::wstring, &GetDefaultPlayerName>("GetDefaultPlayerName");
705  scriptInterface.RegisterFunction<std::wstring, &GetDefaultMPServer>("GetDefaultMPServer");
706  scriptInterface.RegisterFunction<void, std::wstring, std::wstring, &SaveMPConfig>("SaveMPConfig");
707  scriptInterface.RegisterFunction<void, std::string, &OpenURL>("OpenURL");
708  scriptInterface.RegisterFunction<void, &RestartInAtlas>("RestartInAtlas");
709  scriptInterface.RegisterFunction<bool, &AtlasIsAvailable>("AtlasIsAvailable");
710  scriptInterface.RegisterFunction<bool, &IsAtlasRunning>("IsAtlasRunning");
711  scriptInterface.RegisterFunction<CScriptVal, VfsPath, &LoadMapSettings>("LoadMapSettings");
712  scriptInterface.RegisterFunction<CScriptVal, &GetMapSettings>("GetMapSettings");
713  scriptInterface.RegisterFunction<float, &CameraGetX>("CameraGetX");
714  scriptInterface.RegisterFunction<float, &CameraGetZ>("CameraGetZ");
715  scriptInterface.RegisterFunction<void, entity_id_t, &CameraFollow>("CameraFollow");
716  scriptInterface.RegisterFunction<void, entity_id_t, &CameraFollowFPS>("CameraFollowFPS");
717  scriptInterface.RegisterFunction<void, entity_pos_t, entity_pos_t, &CameraMoveTo>("CameraMoveTo");
718  scriptInterface.RegisterFunction<entity_id_t, &GetFollowedEntity>("GetFollowedEntity");
719  scriptInterface.RegisterFunction<bool, std::string, &HotkeyIsPressed_>("HotkeyIsPressed");
720  scriptInterface.RegisterFunction<void, std::wstring, &DisplayErrorDialog>("DisplayErrorDialog");
721  scriptInterface.RegisterFunction<CScriptVal, &GetProfilerState>("GetProfilerState");
722 
723  // User report functions
724  scriptInterface.RegisterFunction<bool, &IsUserReportEnabled>("IsUserReportEnabled");
725  scriptInterface.RegisterFunction<void, bool, &SetUserReportEnabled>("SetUserReportEnabled");
726  scriptInterface.RegisterFunction<std::string, &GetUserReportStatus>("GetUserReportStatus");
727  scriptInterface.RegisterFunction<void, std::string, int, std::wstring, &SubmitUserReport>("SubmitUserReport");
728 
729  // Splash screen functions
730  scriptInterface.RegisterFunction<bool, &IsSplashScreenEnabled>("IsSplashScreenEnabled");
731  scriptInterface.RegisterFunction<void, bool, &SetSplashScreenEnabled>("SetSplashScreenEnabled");
732 
733  // Development/debugging functions
734  scriptInterface.RegisterFunction<void, float, &SetSimRate>("SetSimRate");
735  scriptInterface.RegisterFunction<float, &GetSimRate>("GetSimRate");
736  scriptInterface.RegisterFunction<void, int, &SetTurnLength>("SetTurnLength");
737  scriptInterface.RegisterFunction<void, float, float, float, &SetCameraTarget>("SetCameraTarget");
738  scriptInterface.RegisterFunction<int, &Crash>("Crash");
739  scriptInterface.RegisterFunction<void, &DebugWarn>("DebugWarn");
740  scriptInterface.RegisterFunction<void, &ForceGC>("ForceGC");
741  scriptInterface.RegisterFunction<void, &DumpSimState>("DumpSimState");
742  scriptInterface.RegisterFunction<void, &DumpTerrainMipmap>("DumpTerrainMipmap");
743  scriptInterface.RegisterFunction<void, unsigned int, &EnableTimeWarpRecording>("EnableTimeWarpRecording");
744  scriptInterface.RegisterFunction<void, &RewindTimeWarp>("RewindTimeWarp");
745  scriptInterface.RegisterFunction<void, bool, &SetBoundingBoxDebugOverlay>("SetBoundingBoxDebugOverlay");
746 }
The container that holds the rules, resources and attributes of the game.
Definition: Game.h:39
ScriptInterface & GetScriptInterface()
Get the script interface associated with this network client, which is equivalent to the one used by ...
Definition: NetClient.cpp:191
A simple fixed-point number class.
Definition: Fixed.h:115
std::vector< CScriptValRooted > GetSavedGames(ScriptInterface &scriptInterface)
Get list of saved games for GUI script usage.
Definition: SavedGame.cpp:175
std::wstring sys_get_user_name()
Get the current user&#39;s login name.
Definition: unix.cpp:295
void SetTurnLength(void *cbdata, int length)
float GetSimRate()
Definition: Game.h:150
void StartGame()
Call from the GUI to asynchronously notify all clients that they should start loading the game...
Definition: NetServer.cpp:939
CScriptValRooted GetMapSettings(ScriptInterface &scriptInterface)
Returns a value of the form:
Definition: MapReader.cpp:373
JSBool SetCursor(JSContext *cx, uintN argc, jsval *vp)
Definition: ScriptGlue.cpp:203
void SendNetworkChat(void *cbdata, std::wstring message)
CUserReporter g_UserReporter
Definition: UserReport.cpp:73
#define UNUSED(param)
mark a function parameter as unused and avoid the corresponding compiler warning. ...
void DumpToDisk(const VfsPath &path) const
void PopPage()
Unload the currently active GUI page, and make the previous page active.
Definition: GUIManager.cpp:83
Path VfsPath
VFS path of the form &quot;(dir/)*file?&quot;.
Definition: vfs_path.h:40
CNetClient * g_NetClient
Global network client for the standard game.
Definition: NetClient.cpp:37
bool DeleteSavedGame(const std::wstring &name)
Permanently deletes the saved game archive with the given name.
Definition: SavedGame.cpp:224
void PushGuiPage(void *cbdata, std::wstring name, CScriptVal initData)
static std::vector< CScriptValRooted > GetAIs(ScriptInterface &scriptInterface)
Returns a vector of {&quot;id&quot;:&quot;value-for-AddPlayer&quot;, &quot;name&quot;:&quot;Human readable name&quot;} objects, based on all the available AI scripts.
bool HotkeyIsPressed_(void *cbdata, std::string hotkeyName)
void RegisterScriptFunctions(ScriptInterface &scriptInterface)
const OsPath & psLogDir()
Definition: Pyrogenesis.cpp:96
static bool ms_EnableDebugOverlays
std::wstring GetDefaultMPServer(void *cbdata)
#define LOGERROR
Definition: CLogger.h:35
Status Save(const std::wstring &name, const std::wstring &description, CSimulation2 &simulation, CGUIManager *gui, int playerID)
Create new saved game archive with given name and simulation data.
Definition: SavedGame.cpp:50
CStrW g_CursorName
Definition: Config.cpp:31
void SaveGame(void *cbdata, std::wstring filename, std::wstring description)
ErrorReaction debug_DisplayError(const wchar_t *description, size_t flags, void *context, const wchar_t *lastFuncToSkip, const wchar_t *pathname, int line, const char *func, atomic_bool *suppress)
display an error dialog with a message and stack trace.
Definition: debug.cpp:426
const PSRETURN PSRETURN_OK
Definition: Errors.h:103
bool ATLAS_IsAvailable()
Definition: Atlas.cpp:61
bool SetupConnection()
Begin listening for network connections.
Definition: NetServer.cpp:928
std::string GetStatus()
Definition: UserReport.cpp:564
std::string utf8_from_wstring(const std::wstring &src, Status *err)
opposite of wstring_from_utf8
Definition: utf8.cpp:208
void RegisterScriptFunctions(ScriptInterface &scriptInterface)
int g_xres
Definition: Config.cpp:58
std::string GetUserReportStatus(void *cbdata)
#define CFG_GET_VAL(name, type, destination)
Definition: ConfigDB.h:147
static CStr prefix
Definition: DllLoader.cpp:47
void CameraFollow(entity_id_t entity, bool firstPerson)
Definition: GameView.cpp:1030
static void out(const wchar_t *fmt,...)
Definition: wdbg_sym.cpp:419
void SubmitUserReport(void *cbdata, std::string type, int version, std::wstring data)
void StartNetworkJoin(void *cbdata, std::wstring playerName, std::string serverAddress)
std::vector< entity_id_t > PickSimilarEntities(CSimulation2 &simulation, const CCamera &camera, const std::string &templateName, player_id_t owner, bool includeOffScreen, bool matchRank, bool allowEditorSelectables, bool allowFoundations)
Finds all entities with the given entity template name, belonging to the given player.
Definition: Selection.cpp:167
void EnableTimeWarpRecording(size_t numTurns)
Enables the recording of state snapshots every numTurns, which can be jumped back to via RewindTimeWa...
CFixedVector3D GetTerrainAtScreenPoint(void *cbdata, int x, int y)
CScriptVal GuiInterfaceCall(void *cbdata, std::wstring name, CScriptVal data)
void PushPage(const CStrW &name, CScriptVal initData)
Load a new GUI page and make it active.
Definition: GUIManager.cpp:75
const jsval & get() const
Returns the current value.
Definition: ScriptVal.h:38
void GuiScriptingInit(ScriptInterface &scriptInterface)
std::vector< entity_id_t > PickEntitiesAtPoint(CSimulation2 &simulation, const CCamera &camera, int screenX, int screenY, player_id_t player, bool allowEditorSelectables)
Finds all selectable entities under the given screen coordinates.
Definition: Selection.cpp:32
CNetServer * g_NetServer
Global network server for the standard game.
Definition: NetServer.cpp:46
A trivial wrapper around a jsval.
Definition: ScriptVal.h:29
GameLoopState * g_AtlasGameLoop
void StartGame()
CScriptValRooted GuiPoll()
Retrieves the next queued GUI message, and removes it from the queue.
Definition: NetClient.cpp:161
float GetExactGroundLevel(float x, float z) const
Definition: Terrain.cpp:353
CVector3D GetWorldCoordinates(int px, int py, bool aboveWater=false) const
Definition: Camera.cpp:204
CGUIManager * g_GUI
Definition: GUIManager.cpp:32
float GetCameraX()
Definition: GameView.cpp:952
std::vector< entity_id_t > PickFriendlyEntitiesInRect(void *cbdata, int x0, int y0, int x1, int y1, int player)
void SetBoundingBoxDebugOverlay(void *cbdata, bool enabled)
const entity_id_t SYSTEM_ENTITY
Entity ID for singleton &#39;system&#39; components.
Definition: Entity.h:44
Public API for simulation system.
Definition: Simulation2.h:46
Status SavePrefix(const std::wstring &prefix, const std::wstring &description, CSimulation2 &simulation, CGUIManager *gui, int playerID)
Create new saved game archive with given prefix and simulation data.
Definition: SavedGame.cpp:35
Hotkey system.
int GetPlayerID()
Definition: Game.cpp:249
CTerrain * GetTerrain()
Get the pointer to the terrain object.
Definition: World.h:88
CFixed_15_16 entity_pos_t
Positions and distances (measured in metres)
Definition: Position.h:36
void CameraFollow(void *cbdata, entity_id_t entityid)
Start / stop camera following mode.
std::vector< CScriptValRooted > GetSavedGames(void *cbdata)
void SetSplashScreenEnabled(void *cbdata, bool enabled)
#define ENSURE(expr)
ensure the expression &lt;expr&gt; evaluates to non-zero.
Definition: debug.h:282
void SetTurnLength(u32 msecs)
Set the turn length to a fixed value.
Definition: NetServer.cpp:955
void SetPlayerID(int playerID)
Definition: Game.cpp:254
void SubmitReport(const char *type, int version, const std::string &data)
Submit a report to be transmitted to the online server.
Definition: UserReport.cpp:616
void AssignPlayer(int playerID, const CStr &guid)
Call from the GUI to update the player assignments.
Definition: NetServer.cpp:933
std::vector< CScriptValRooted > GetAIs(void *cbdata)
CConsole * g_Console
Definition: CConsole.cpp:46
float X
Definition: Vector3D.h:31
void OpenURL(void *cbdata, std::string url)
display just the given message; do not add any information about the call stack, do not write crashlo...
Definition: debug.h:109
Status sys_open_url(const std::string &url)
Open the user&#39;s default web browser to the given URL.
Definition: unix.cpp:343
virtual void PostNetworkCommand(CScriptVal cmd)=0
Send a command associated with the current player to the networking system.
Definition: path.h:75
float Y
Definition: Vector3D.h:31
const String & string() const
Definition: path.h:123
Contains functions for managing saved game archives.
float ToFloat() const
Convert to float. May be lossy - float can&#39;t represent all values.
Definition: Fixed.h:161
CScriptVal StartSavedGame(void *cbdata, std::wstring name)
void UpdateGameAttributes(const CScriptVal &attrs, ScriptInterface &scriptInterface)
Call from the GUI to update the game setup attributes.
Definition: NetServer.cpp:945
int g_yres
Definition: Config.cpp:58
void StartGame(const CScriptValRooted &attribs, const std::string &savedState)
Definition: Game.cpp:261
void SetUserName(const CStrW &username)
Set the user&#39;s name that will be displayed to all players.
Definition: NetClient.cpp:123
CNetTurnManager * GetTurnManager() const
Definition: Game.h:159
JSObject * GetScriptObject()
See CGUI::GetScriptObject; applies to the currently active page.
Definition: GUIManager.cpp:290
ScriptInterface & GetScriptInterface() const
#define SAFE_DELETE(p)
delete memory ensuing from new and set the pointer to zero (thus making double-frees safe / a no-op) ...
void SaveMPConfig(void *cbdata, std::wstring playerName, std::wstring server)
CCamera * GetCamera()
Definition: GameView.cpp:390
CGame * g_Game
Globally accessible pointer to the CGame object.
Definition: Game.cpp:56
void AssignNetworkPlayer(void *cbdata, int playerID, std::string guid)
Network server interface.
Definition: NetServer.h:97
void SetSimRate(float simRate)
Set the simulation scale multiplier.
Definition: Game.h:147
i64 Status
Error handling system.
Definition: status.h:171
#define g_ConfigDB
Definition: ConfigDB.h:52
double timer_Time()
Definition: timer.cpp:98
A simplified syntax for accessing entity components.
Definition: CmpPtr.h:55
jsval CloneValueFromOtherContext(ScriptInterface &otherContext, jsval val)
Construct a new value (usable in this ScriptInterface&#39;s context) by cloning a value from a different ...
float GetCameraZ()
Definition: GameView.cpp:959
std::vector< entity_id_t > PickEntitiesAtPoint(void *cbdata, int x, int y)
CSimulation2 * GetSimulation2()
Get the pointer to the simulation2 object.
Definition: Game.h:136
ScriptInterface & GetScriptInterface()
Definition: GUIManager.h:52
bool GetProperty(jsval obj, const char *name, T &out)
Get the named property on the given object.
entity_id_t GetFollowedEntity()
Definition: GameView.cpp:1036
CGameView * GetView()
Get the pointer to the game view object.
Definition: Game.h:128
float CameraGetX(void *cbdata)
Get the current X coordinate of the camera.
bool SetupConnection(const CStr &server)
Set up a connection to the remote networked server.
Definition: NetClient.cpp:130
void CameraMoveTo(void *cbdata, entity_pos_t x, entity_pos_t z)
Move camera to a 2D location.
PSRETURN LoadMap(const VfsPath &pathname)
Try to load a map file.
Definition: MapReader.cpp:342
virtual CScriptVal ScriptCall(int player, const std::wstring &cmd, CScriptVal data)=0
Generic call function, for use by GUI scripts to talk to the GuiInterface script. ...
void SwitchPage(const CStrW &name, CScriptVal initData)
Load a new GUI page and make it active.
Definition: GUIManager.cpp:69
void SetReportingEnabled(bool enabled)
Definition: UserReport.cpp:554
Network client.
Definition: NetClient.h:57
std::vector< entity_id_t > PickFriendlyEntitiesOnScreen(void *cbdata, int player)
void SetUserReportEnabled(void *cbdata, bool enabled)
void PostNetworkCommand(void *cbdata, CScriptVal cmd)
entity_id_t GetFollowedEntity(void *cbdata)
void SendChatMessage(const std::wstring &text)
Definition: NetClient.cpp:243
void CameraFollowFPS(void *cbdata, entity_id_t entityid)
Start / stop first-person camera following mode.
std::wstring GetDefaultPlayerName(void *cbdata)
CScriptVal GetMapSettings()
Get the current map settings.
#define g_ProfileViewer
Status Load(const std::wstring &name, ScriptInterface &scriptInterface, CScriptValRooted &metadata, std::string &savedState)
Load saved game archive with the given name.
Definition: SavedGame.cpp:152
void SwitchGuiPage(void *cbdata, std::wstring name, CScriptVal initData)
#define LOGMESSAGERENDER
Definition: CLogger.h:33
void RegisterScriptFunctions(ScriptInterface &ScriptInterface)
void StartNetworkHost(void *cbdata, std::wstring playerName)
std::vector< entity_id_t > PickSimilarFriendlyEntities(void *cbdata, std::string templateName, bool includeOffScreen, bool matchRank, bool allowFoundations)
static CFixed FromFloat(float n)
Definition: Fixed.h:141
jsval get() const
Returns the current value (or JSVAL_VOID if uninitialised).
Definition: ScriptVal.cpp:45
CWorld * GetWorld()
Get the pointer to the game world object.
Definition: Game.h:120
float Z
Definition: Vector3D.h:31
void restart_mainloop_in_atlas()
Definition: main.cpp:436
Abstraction around a SpiderMonkey JSContext.
bool HotkeyIsPressed(const CStr &keyname)
Definition: Hotkey.cpp:400
#define debug_warn(expr)
display the error dialog with the given text.
Definition: debug.h:324
void RegisterScriptFunctions(ScriptInterface &scriptInterface)
External interface to the GUI system.
Definition: GUIManager.h:45
void EnableTimeWarpRecording(void *cbdata, unsigned int numTurns)
bool DeleteSavedGame(void *cbdata, std::wstring name)
CScriptVal LoadMapSettings(void *cbdata, VfsPath pathname)
float CameraGetZ(void *cbdata)
Get the current Z coordinate of the camera.
const entity_id_t INVALID_ENTITY
Invalid entity ID.
Definition: Entity.h:36
PIVFS g_VFS
Definition: Filesystem.cpp:30
void SetNetworkGameAttributes(void *cbdata, CScriptVal attribs)
u32 entity_id_t
Entity ID type.
Definition: Entity.h:24
void RewindTimeWarp()
Jumps back to the latest recorded state snapshot (if any).
A restricted map reader that returns various summary information for use by scripts (particularly the...
Definition: MapReader.h:159
void MoveCameraTarget(const CVector3D &target)
Definition: GameView.cpp:966
bool DumpDebugState(std::ostream &stream)
void InsertMessage(const wchar_t *szMessage,...) WPRINTF_ARGS(2)
Definition: CConsole.cpp:508
void SetCameraTarget(void *cbdata, float x, float y, float z)
Helper functions related to entity selection.
JSContext * GetContext() const
void SaveGamePrefix(void *cbdata, std::wstring prefix, std::wstring description)
void ResetCameraTarget(const CVector3D &target)
Definition: GameView.cpp:988
const CHeightMipmap & GetHeightMipmap() const
Definition: Terrain.h:156
void ReportError(const char *msg)
Report the given error message through the JS error reporting mechanism, and throw a JS exception...
void DisplayErrorDialog(void *cbdata, std::wstring msg)
void debug_printf(const wchar_t *fmt,...)
write a formatted string to the debug channel, subject to filtering (see below).
Definition: debug.cpp:142
void SetSimRate(void *cbdata, float rate)
bool IsReportingEnabled()
Definition: UserReport.cpp:547
static std::string OsString(const OsPath &path)
Definition: os_path.h:42
std::vector< entity_id_t > PickEntitiesInRect(CSimulation2 &simulation, const CCamera &camera, int sx0, int sy0, int sx1, int sy1, player_id_t owner, bool allowEditorSelectables)
Finds all selectable entities within the given screen coordinate rectangle, belonging to the given pl...
Definition: Selection.cpp:108