OpenTTD Source  13.0-beta1
script_instance.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "../stdafx.h"
11 #include "../debug.h"
12 #include "../saveload/saveload.h"
13 
14 #include "../script/squirrel_class.hpp"
15 
16 #include "script_fatalerror.hpp"
17 #include "script_storage.hpp"
18 #include "script_info.hpp"
19 #include "script_instance.hpp"
20 
21 #include "api/script_controller.hpp"
22 #include "api/script_error.hpp"
23 #include "api/script_event.hpp"
24 #include "api/script_log.hpp"
25 
26 #include "../company_base.h"
27 #include "../company_func.h"
28 #include "../fileio_func.h"
29 #include "../misc/endian_buffer.hpp"
30 
31 #include "../safeguards.h"
32 
33 ScriptStorage::~ScriptStorage()
34 {
35  /* Free our pointers */
36  if (event_data != nullptr) ScriptEventController::FreeEventPointer();
37  if (log_data != nullptr) ScriptLog::FreeLogPointer();
38 }
39 
45 static void PrintFunc(bool error_msg, const SQChar *message)
46 {
47  /* Convert to OpenTTD internal capable string */
48  ScriptController::Print(error_msg, message);
49 }
50 
51 ScriptInstance::ScriptInstance(const char *APIName) :
52  engine(nullptr),
53  versionAPI(nullptr),
54  controller(nullptr),
55  storage(nullptr),
56  instance(nullptr),
57  is_started(false),
58  is_dead(false),
59  is_save_data_on_stack(false),
60  suspend(0),
61  is_paused(false),
62  in_shutdown(false),
63  callback(nullptr)
64 {
65  this->storage = new ScriptStorage();
66  this->engine = new Squirrel(APIName);
68 }
69 
70 void ScriptInstance::Initialize(const char *main_script, const char *instance_name, CompanyID company)
71 {
72  ScriptObject::ActiveInstance active(this);
73 
74  this->controller = new ScriptController(company);
75 
76  /* Register the API functions and classes */
77  this->engine->SetGlobalPointer(this->engine);
78  this->RegisterAPI();
79 
80  try {
81  ScriptObject::SetAllowDoCommand(false);
82  /* Load and execute the script for this script */
83  if (strcmp(main_script, "%_dummy") == 0) {
84  this->LoadDummyScript();
85  } else if (!this->engine->LoadScript(main_script) || this->engine->IsSuspended()) {
86  if (this->engine->IsSuspended()) ScriptLog::Error("This script took too long to load script. AI is not started.");
87  this->Died();
88  return;
89  }
90 
91  /* Create the main-class */
92  this->instance = new SQObject();
93  if (!this->engine->CreateClassInstance(instance_name, this->controller, this->instance)) {
94  /* If CreateClassInstance has returned false instance has not been
95  * registered with squirrel, so avoid trying to Release it by clearing it now */
96  delete this->instance;
97  this->instance = nullptr;
98  this->Died();
99  return;
100  }
101  ScriptObject::SetAllowDoCommand(true);
102  } catch (Script_FatalError &e) {
103  this->is_dead = true;
104  this->engine->ThrowError(e.GetErrorMessage().c_str());
105  this->engine->ResumeError();
106  this->Died();
107  }
108 }
109 
111 {
112  extern void squirrel_register_std(Squirrel *engine);
113  squirrel_register_std(this->engine);
114 }
115 
116 bool ScriptInstance::LoadCompatibilityScripts(const char *api_version, Subdirectory dir)
117 {
118  char script_name[32];
119  seprintf(script_name, lastof(script_name), "compat_%s.nut", api_version);
120  for (Searchpath sp : _valid_searchpaths) {
121  std::string buf = FioGetDirectory(sp, dir);
122  buf += script_name;
123  if (!FileExists(buf)) continue;
124 
125  if (this->engine->LoadScript(buf.c_str())) return true;
126 
127  ScriptLog::Error("Failed to load API compatibility script");
128  Debug(script, 0, "Error compiling / running API compatibility script: {}", buf);
129  return false;
130  }
131 
132  ScriptLog::Warning("API compatibility script not found");
133  return true;
134 }
135 
136 ScriptInstance::~ScriptInstance()
137 {
138  ScriptObject::ActiveInstance active(this);
139  this->in_shutdown = true;
140 
141  if (instance != nullptr) this->engine->ReleaseObject(this->instance);
142  if (engine != nullptr) delete this->engine;
143  delete this->storage;
144  delete this->controller;
145  delete this->instance;
146 }
147 
149 {
150  assert(this->suspend < 0);
151  this->suspend = -this->suspend - 1;
152 }
153 
155 {
156  Debug(script, 0, "The script died unexpectedly.");
157  this->is_dead = true;
158  this->in_shutdown = true;
159 
160  this->last_allocated_memory = this->GetAllocatedMemory(); // Update cache
161 
162  if (this->instance != nullptr) this->engine->ReleaseObject(this->instance);
163  delete this->instance;
164  delete this->engine;
165  this->instance = nullptr;
166  this->engine = nullptr;
167 }
168 
170 {
171  ScriptObject::ActiveInstance active(this);
172 
173  if (this->IsDead()) return;
174  if (this->engine->HasScriptCrashed()) {
175  /* The script crashed during saving, kill it here. */
176  this->Died();
177  return;
178  }
179  if (this->is_paused) return;
180  this->controller->ticks++;
181 
182  if (this->suspend < -1) this->suspend++; // Multiplayer suspend, increase up to -1.
183  if (this->suspend < 0) return; // Multiplayer suspend, wait for Continue().
184  if (--this->suspend > 0) return; // Singleplayer suspend, decrease to 0.
185 
186  _current_company = ScriptObject::GetCompany();
187 
188  /* If there is a callback to call, call that first */
189  if (this->callback != nullptr) {
190  if (this->is_save_data_on_stack) {
191  sq_poptop(this->engine->GetVM());
192  this->is_save_data_on_stack = false;
193  }
194  try {
195  this->callback(this);
196  } catch (Script_Suspend &e) {
197  this->suspend = e.GetSuspendTime();
198  this->callback = e.GetSuspendCallback();
199 
200  return;
201  }
202  }
203 
204  this->suspend = 0;
205  this->callback = nullptr;
206 
207  if (!this->is_started) {
208  try {
209  ScriptObject::SetAllowDoCommand(false);
210  /* Run the constructor if it exists. Don't allow any DoCommands in it. */
211  if (this->engine->MethodExists(*this->instance, "constructor")) {
212  if (!this->engine->CallMethod(*this->instance, "constructor", MAX_CONSTRUCTOR_OPS) || this->engine->IsSuspended()) {
213  if (this->engine->IsSuspended()) ScriptLog::Error("This script took too long to initialize. Script is not started.");
214  this->Died();
215  return;
216  }
217  }
218  if (!this->CallLoad() || this->engine->IsSuspended()) {
219  if (this->engine->IsSuspended()) ScriptLog::Error("This script took too long in the Load function. Script is not started.");
220  this->Died();
221  return;
222  }
223  ScriptObject::SetAllowDoCommand(true);
224  /* Start the script by calling Start() */
225  if (!this->engine->CallMethod(*this->instance, "Start", _settings_game.script.script_max_opcode_till_suspend) || !this->engine->IsSuspended()) this->Died();
226  } catch (Script_Suspend &e) {
227  this->suspend = e.GetSuspendTime();
228  this->callback = e.GetSuspendCallback();
229  } catch (Script_FatalError &e) {
230  this->is_dead = true;
231  this->engine->ThrowError(e.GetErrorMessage().c_str());
232  this->engine->ResumeError();
233  this->Died();
234  }
235 
236  this->is_started = true;
237  return;
238  }
239  if (this->is_save_data_on_stack) {
240  sq_poptop(this->engine->GetVM());
241  this->is_save_data_on_stack = false;
242  }
243 
244  /* Continue the VM */
245  try {
247  } catch (Script_Suspend &e) {
248  this->suspend = e.GetSuspendTime();
249  this->callback = e.GetSuspendCallback();
250  } catch (Script_FatalError &e) {
251  this->is_dead = true;
252  this->engine->ThrowError(e.GetErrorMessage().c_str());
253  this->engine->ResumeError();
254  this->Died();
255  }
256 }
257 
259 {
260  if (this->is_started && !this->IsDead()) {
261  ScriptObject::ActiveInstance active(this);
262  this->engine->CollectGarbage();
263  }
264 }
265 
267 {
268  instance->engine->InsertResult(ScriptObject::GetLastCommandRes());
269 }
270 
272 {
273  instance->engine->InsertResult(EndianBufferReader::ToValue<VehicleID>(ScriptObject::GetLastCommandResData()));
274 }
275 
277 {
278  instance->engine->InsertResult(EndianBufferReader::ToValue<SignID>(ScriptObject::GetLastCommandResData()));
279 }
280 
282 {
283  instance->engine->InsertResult(EndianBufferReader::ToValue<GroupID>(ScriptObject::GetLastCommandResData()));
284 }
285 
287 {
288  instance->engine->InsertResult(EndianBufferReader::ToValue<GoalID>(ScriptObject::GetLastCommandResData()));
289 }
290 
292 {
293  instance->engine->InsertResult(EndianBufferReader::ToValue<StoryPageID>(ScriptObject::GetLastCommandResData()));
294 }
295 
297 {
298  instance->engine->InsertResult(EndianBufferReader::ToValue<StoryPageElementID>(ScriptObject::GetLastCommandResData()));
299 }
300 
302 {
303  return this->storage;
304 }
305 
307 {
308  ScriptObject::ActiveInstance active(this);
309 
310  return ScriptObject::GetLogPointer();
311 }
312 
313 /*
314  * All data is stored in the following format:
315  * First 1 byte indicating if there is a data blob at all.
316  * 1 byte indicating the type of data.
317  * The data itself, this differs per type:
318  * - integer: a binary representation of the integer (int32).
319  * - string: First one byte with the string length, then a 0-terminated char
320  * array. The string can't be longer than 255 bytes (including
321  * terminating '\0').
322  * - array: All data-elements of the array are saved recursive in this
323  * format, and ended with an element of the type
324  * SQSL_ARRAY_TABLE_END.
325  * - table: All key/value pairs are saved in this format (first key 1, then
326  * value 1, then key 2, etc.). All keys and values can have an
327  * arbitrary type (as long as it is supported by the save function
328  * of course). The table is ended with an element of the type
329  * SQSL_ARRAY_TABLE_END.
330  * - bool: A single byte with value 1 representing true and 0 false.
331  * - null: No data.
332  */
333 
336  SQSL_INT = 0x00,
337  SQSL_STRING = 0x01,
338  SQSL_ARRAY = 0x02,
339  SQSL_TABLE = 0x03,
340  SQSL_BOOL = 0x04,
341  SQSL_NULL = 0x05,
343 };
344 
345 static byte _script_sl_byte;
346 
348 static const SaveLoad _script_byte[] = {
349  SLEG_VAR("type", _script_sl_byte, SLE_UINT8),
350 };
351 
352 /* static */ bool ScriptInstance::SaveObject(HSQUIRRELVM vm, SQInteger index, int max_depth, bool test)
353 {
354  if (max_depth == 0) {
355  ScriptLog::Error("Savedata can only be nested to 25 deep. No data saved."); // SQUIRREL_MAX_DEPTH = 25
356  return false;
357  }
358 
359  switch (sq_gettype(vm, index)) {
360  case OT_INTEGER: {
361  if (!test) {
363  SlObject(nullptr, _script_byte);
364  }
365  SQInteger res;
366  sq_getinteger(vm, index, &res);
367  if (!test) {
368  int64 value = (int64)res;
369  SlCopy(&value, 1, SLE_INT64);
370  }
371  return true;
372  }
373 
374  case OT_STRING: {
375  if (!test) {
377  SlObject(nullptr, _script_byte);
378  }
379  const SQChar *buf;
380  sq_getstring(vm, index, &buf);
381  size_t len = strlen(buf) + 1;
382  if (len >= 255) {
383  ScriptLog::Error("Maximum string length is 254 chars. No data saved.");
384  return false;
385  }
386  if (!test) {
387  _script_sl_byte = (byte)len;
388  SlObject(nullptr, _script_byte);
389  SlCopy(const_cast<char *>(buf), len, SLE_CHAR);
390  }
391  return true;
392  }
393 
394  case OT_ARRAY: {
395  if (!test) {
397  SlObject(nullptr, _script_byte);
398  }
399  sq_pushnull(vm);
400  while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
401  /* Store the value */
402  bool res = SaveObject(vm, -1, max_depth - 1, test);
403  sq_pop(vm, 2);
404  if (!res) {
405  sq_pop(vm, 1);
406  return false;
407  }
408  }
409  sq_pop(vm, 1);
410  if (!test) {
412  SlObject(nullptr, _script_byte);
413  }
414  return true;
415  }
416 
417  case OT_TABLE: {
418  if (!test) {
420  SlObject(nullptr, _script_byte);
421  }
422  sq_pushnull(vm);
423  while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
424  /* Store the key + value */
425  bool res = SaveObject(vm, -2, max_depth - 1, test) && SaveObject(vm, -1, max_depth - 1, test);
426  sq_pop(vm, 2);
427  if (!res) {
428  sq_pop(vm, 1);
429  return false;
430  }
431  }
432  sq_pop(vm, 1);
433  if (!test) {
435  SlObject(nullptr, _script_byte);
436  }
437  return true;
438  }
439 
440  case OT_BOOL: {
441  if (!test) {
443  SlObject(nullptr, _script_byte);
444  }
445  SQBool res;
446  sq_getbool(vm, index, &res);
447  if (!test) {
448  _script_sl_byte = res ? 1 : 0;
449  SlObject(nullptr, _script_byte);
450  }
451  return true;
452  }
453 
454  case OT_NULL: {
455  if (!test) {
457  SlObject(nullptr, _script_byte);
458  }
459  return true;
460  }
461 
462  default:
463  ScriptLog::Error("You tried to save an unsupported type. No data saved.");
464  return false;
465  }
466 }
467 
468 /* static */ void ScriptInstance::SaveEmpty()
469 {
470  _script_sl_byte = 0;
471  SlObject(nullptr, _script_byte);
472 }
473 
475 {
476  ScriptObject::ActiveInstance active(this);
477 
478  /* Don't save data if the script didn't start yet or if it crashed. */
479  if (this->engine == nullptr || this->engine->HasScriptCrashed()) {
480  SaveEmpty();
481  return;
482  }
483 
484  HSQUIRRELVM vm = this->engine->GetVM();
485  if (this->is_save_data_on_stack) {
486  _script_sl_byte = 1;
487  SlObject(nullptr, _script_byte);
488  /* Save the data that was just loaded. */
489  SaveObject(vm, -1, SQUIRREL_MAX_DEPTH, false);
490  } else if (!this->is_started) {
491  SaveEmpty();
492  return;
493  } else if (this->engine->MethodExists(*this->instance, "Save")) {
494  HSQOBJECT savedata;
495  /* We don't want to be interrupted during the save function. */
496  bool backup_allow = ScriptObject::GetAllowDoCommand();
497  ScriptObject::SetAllowDoCommand(false);
498  try {
499  if (!this->engine->CallMethod(*this->instance, "Save", &savedata, MAX_SL_OPS)) {
500  /* The script crashed in the Save function. We can't kill
501  * it here, but do so in the next script tick. */
502  SaveEmpty();
503  this->engine->CrashOccurred();
504  return;
505  }
506  } catch (Script_FatalError &e) {
507  /* If we don't mark the script as dead here cleaning up the squirrel
508  * stack could throw Script_FatalError again. */
509  this->is_dead = true;
510  this->engine->ThrowError(e.GetErrorMessage().c_str());
511  this->engine->ResumeError();
512  SaveEmpty();
513  /* We can't kill the script here, so mark it as crashed (not dead) and
514  * kill it in the next script tick. */
515  this->is_dead = false;
516  this->engine->CrashOccurred();
517  return;
518  }
519  ScriptObject::SetAllowDoCommand(backup_allow);
520 
521  if (!sq_istable(savedata)) {
522  ScriptLog::Error(this->engine->IsSuspended() ? "This script took too long to Save." : "Save function should return a table.");
523  SaveEmpty();
524  this->engine->CrashOccurred();
525  return;
526  }
527  sq_pushobject(vm, savedata);
528  if (SaveObject(vm, -1, SQUIRREL_MAX_DEPTH, true)) {
529  _script_sl_byte = 1;
530  SlObject(nullptr, _script_byte);
531  SaveObject(vm, -1, SQUIRREL_MAX_DEPTH, false);
532  this->is_save_data_on_stack = true;
533  } else {
534  SaveEmpty();
535  this->engine->CrashOccurred();
536  }
537  } else {
538  ScriptLog::Warning("Save function is not implemented");
539  _script_sl_byte = 0;
540  SlObject(nullptr, _script_byte);
541  }
542 }
543 
545 {
546  /* Suspend script. */
547  HSQUIRRELVM vm = this->engine->GetVM();
549 
550  this->is_paused = true;
551 }
552 
554 {
555  this->is_paused = false;
556 }
557 
559 {
560  return this->is_paused;
561 }
562 
563 /* static */ bool ScriptInstance::LoadObjects(HSQUIRRELVM vm)
564 {
565  SlObject(nullptr, _script_byte);
566  switch (_script_sl_byte) {
567  case SQSL_INT: {
568  int64 value;
569  SlCopy(&value, 1, IsSavegameVersionBefore(SLV_SCRIPT_INT64) ? SLE_FILE_I32 | SLE_VAR_I64 : SLE_INT64);
570  if (vm != nullptr) sq_pushinteger(vm, (SQInteger)value);
571  return true;
572  }
573 
574  case SQSL_STRING: {
575  SlObject(nullptr, _script_byte);
576  static char buf[std::numeric_limits<decltype(_script_sl_byte)>::max()];
577  SlCopy(buf, _script_sl_byte, SLE_CHAR);
579  if (vm != nullptr) sq_pushstring(vm, buf, -1);
580  return true;
581  }
582 
583  case SQSL_ARRAY: {
584  if (vm != nullptr) sq_newarray(vm, 0);
585  while (LoadObjects(vm)) {
586  if (vm != nullptr) sq_arrayappend(vm, -2);
587  /* The value is popped from the stack by squirrel. */
588  }
589  return true;
590  }
591 
592  case SQSL_TABLE: {
593  if (vm != nullptr) sq_newtable(vm);
594  while (LoadObjects(vm)) {
595  LoadObjects(vm);
596  if (vm != nullptr) sq_rawset(vm, -3);
597  /* The key (-2) and value (-1) are popped from the stack by squirrel. */
598  }
599  return true;
600  }
601 
602  case SQSL_BOOL: {
603  SlObject(nullptr, _script_byte);
604  if (vm != nullptr) sq_pushbool(vm, (SQBool)(_script_sl_byte != 0));
605  return true;
606  }
607 
608  case SQSL_NULL: {
609  if (vm != nullptr) sq_pushnull(vm);
610  return true;
611  }
612 
613  case SQSL_ARRAY_TABLE_END: {
614  return false;
615  }
616 
617  default: NOT_REACHED();
618  }
619 }
620 
621 /* static */ void ScriptInstance::LoadEmpty()
622 {
623  SlObject(nullptr, _script_byte);
624  /* Check if there was anything saved at all. */
625  if (_script_sl_byte == 0) return;
626 
627  LoadObjects(nullptr);
628 }
629 
630 void ScriptInstance::Load(int version)
631 {
632  ScriptObject::ActiveInstance active(this);
633 
634  if (this->engine == nullptr || version == -1) {
635  LoadEmpty();
636  return;
637  }
638  HSQUIRRELVM vm = this->engine->GetVM();
639 
640  SlObject(nullptr, _script_byte);
641  /* Check if there was anything saved at all. */
642  if (_script_sl_byte == 0) return;
643 
644  sq_pushinteger(vm, version);
645  LoadObjects(vm);
646  this->is_save_data_on_stack = true;
647 }
648 
650 {
651  HSQUIRRELVM vm = this->engine->GetVM();
652  /* Is there save data that we should load? */
653  if (!this->is_save_data_on_stack) return true;
654  /* Whatever happens, after CallLoad the savegame data is removed from the stack. */
655  this->is_save_data_on_stack = false;
656 
657  if (!this->engine->MethodExists(*this->instance, "Load")) {
658  ScriptLog::Warning("Loading failed: there was data for the script to load, but the script does not have a Load() function.");
659 
660  /* Pop the savegame data and version. */
661  sq_pop(vm, 2);
662  return true;
663  }
664 
665  /* Go to the instance-root */
666  sq_pushobject(vm, *this->instance);
667  /* Find the function-name inside the script */
668  sq_pushstring(vm, "Load", -1);
669  /* Change the "Load" string in a function pointer */
670  sq_get(vm, -2);
671  /* Push the main instance as "this" object */
672  sq_pushobject(vm, *this->instance);
673  /* Push the version data and savegame data as arguments */
674  sq_push(vm, -5);
675  sq_push(vm, -5);
676 
677  /* Call the script load function. sq_call removes the arguments (but not the
678  * function pointer) from the stack. */
679  if (SQ_FAILED(sq_call(vm, 3, SQFalse, SQFalse, MAX_SL_OPS))) return false;
680 
681  /* Pop 1) The version, 2) the savegame data, 3) the object instance, 4) the function pointer. */
682  sq_pop(vm, 4);
683  return true;
684 }
685 
687 {
688  return this->engine->GetOpsTillSuspend();
689 }
690 
692 {
693  ScriptObject::ActiveInstance active(this);
694 
695  if (!ScriptObject::CheckLastCommand(tile, data, cmd)) {
696  Debug(script, 1, "DoCommandCallback terminating a script, last command does not match expected command");
697  return false;
698  }
699 
700  ScriptObject::SetLastCommandRes(result.Succeeded());
701  ScriptObject::SetLastCommandResData(std::move(result_data));
702 
703  if (result.Failed()) {
704  ScriptObject::SetLastError(ScriptError::StringToError(result.GetErrorMessage()));
705  } else {
706  ScriptObject::IncreaseDoCommandCosts(result.GetCost());
707  ScriptObject::SetLastCost(result.GetCost());
708  }
709 
710  ScriptObject::SetLastCommand(INVALID_TILE, {}, CMD_END);
711 
712  return true;
713 }
714 
715 void ScriptInstance::InsertEvent(class ScriptEvent *event)
716 {
717  ScriptObject::ActiveInstance active(this);
718 
719  ScriptEventController::InsertEvent(event);
720 }
721 
722 size_t ScriptInstance::GetAllocatedMemory() const
723 {
724  if (this->engine == nullptr) return this->last_allocated_memory;
725  return this->engine->GetAllocatedMemory();
726 }
727 
729 {
730  if (!this->in_shutdown) this->engine->ReleaseObject(obj);
731 }
ScriptInstance::LoadDummyScript
virtual void LoadDummyScript()=0
Load the dummy script.
Script_Suspend
A throw-class that is given when the script wants to suspend.
Definition: script_suspend.hpp:21
ScriptStorage::log_data
void * log_data
Pointer to the log data storage.
Definition: script_storage.hpp:58
ScriptInstance::SaveObject
static bool SaveObject(HSQUIRRELVM vm, SQInteger index, int max_depth, bool test)
Save one object (int / string / array / table) to the savegame.
Definition: script_instance.cpp:352
ScriptInstance::engine
class Squirrel * engine
A wrapper around the squirrel vm.
Definition: script_instance.hpp:215
_script_sl_byte
static byte _script_sl_byte
Used as source/target by the script saveload code to store/load a single byte.
Definition: script_instance.cpp:345
PrintFunc
static void PrintFunc(bool error_msg, const SQChar *message)
Callback called by squirrel when a script uses "print" and for error messages.
Definition: script_instance.cpp:45
ScriptInstance::last_allocated_memory
size_t last_allocated_memory
Last known allocated memory value (for display for crashed scripts)
Definition: script_instance.hpp:258
ScriptStorage
The storage for each script.
Definition: script_storage.hpp:31
ScriptInstance::CallLoad
bool CallLoad()
Call the script Load function if it exists and data was loaded from a savegame.
Definition: script_instance.cpp:649
ScriptInstance::is_dead
bool is_dead
True if the script has been stopped.
Definition: script_instance.hpp:252
ScriptInstance::InsertEvent
void InsertEvent(class ScriptEvent *event)
Insert an event for this script.
Definition: script_instance.cpp:715
ScriptInstance::GameLoop
void GameLoop()
Run the GameLoop of a script.
Definition: script_instance.cpp:169
Squirrel::SetPrintFunction
void SetPrintFunction(SQPrintFunc *func)
Set a custom print function, so you can handle outputs from SQ yourself.
Definition: squirrel.hpp:231
Script_Suspend::GetSuspendTime
int GetSuspendTime()
Get the amount of ticks the script should be suspended.
Definition: script_suspend.hpp:37
ScriptInstance::controller
class ScriptController * controller
The script main class.
Definition: script_instance.hpp:247
ScriptInstance::Save
void Save()
Call the script Save function and save all data in the savegame.
Definition: script_instance.cpp:474
Commands
Commands
List of commands.
Definition: command_type.h:176
CommandDataBuffer
std::vector< byte > CommandDataBuffer
Storage buffer for serialized command data.
Definition: command_type.h:443
ScriptScanner::engine
class Squirrel * engine
The engine we're scanning with.
Definition: script_scanner.hpp:86
SQSL_STRING
@ SQSL_STRING
The following data is an string.
Definition: script_instance.cpp:337
SQSL_ARRAY
@ SQSL_ARRAY
The following data is an array.
Definition: script_instance.cpp:338
SQSL_INT
@ SQSL_INT
The following data is an integer.
Definition: script_instance.cpp:336
SlCopy
void SlCopy(void *object, size_t length, VarType conv)
Copy a list of SL_VARs to/from a savegame.
Definition: saveload.cpp:1151
ScriptInstance
Runtime information about a script like a pointer to the squirrel vm and the current state.
Definition: script_instance.hpp:23
ScriptInstance::ScriptInstance
ScriptInstance(const char *APIName)
Create a new script.
Definition: script_instance.cpp:51
ScriptInstance::Unpause
void Unpause()
Resume execution of the script.
Definition: script_instance.cpp:553
ScriptInstance::DoCommandCallback
bool DoCommandCallback(const CommandCost &result, TileIndex tile, const CommandDataBuffer &data, CommandDataBuffer result_data, Commands cmd)
DoCommand callback function for all commands executed by scripts.
Definition: script_instance.cpp:691
ScriptInstance::DoCommandReturnStoryPageElementID
static void DoCommandReturnStoryPageElementID(ScriptInstance *instance)
Return a StoryPageElementID reply for a DoCommand.
Definition: script_instance.cpp:296
ScriptInstance::LoadObjects
static bool LoadObjects(HSQUIRRELVM vm)
Load all objects from a savegame.
Definition: script_instance.cpp:563
Searchpath
Searchpath
Types of searchpaths OpenTTD might use.
Definition: fileio_type.h:131
INVALID_TILE
static constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:108
ScriptInstance::instance
SQObject * instance
Squirrel-pointer to the script main class.
Definition: script_instance.hpp:249
TileIndex
The index/ID of a Tile.
Definition: tile_type.h:85
ScriptInstance::is_save_data_on_stack
bool is_save_data_on_stack
Is the save data still on the squirrel stack?
Definition: script_instance.hpp:253
Squirrel::GetVM
HSQUIRRELVM GetVM()
Get the squirrel VM.
Definition: squirrel.hpp:80
ScriptInstance::is_paused
bool is_paused
Is the script paused? (a paused script will not be executed until unpaused)
Definition: script_instance.hpp:255
SQSaveLoadType
SQSaveLoadType
The type of the data that follows in the savegame.
Definition: script_instance.cpp:335
Script_FatalError::GetErrorMessage
const std::string & GetErrorMessage() const
The error message associated with the fatal error.
Definition: script_fatalerror.hpp:30
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
CommandCost::GetErrorMessage
StringID GetErrorMessage() const
Returns the error message of a command.
Definition: command_type.h:141
SQSL_TABLE
@ SQSL_TABLE
The following data is an table.
Definition: script_instance.cpp:339
CMD_END
@ CMD_END
Must ALWAYS be on the end of this list!! (period)
Definition: command_type.h:340
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:151
ScriptInstance::GetOpsTillSuspend
SQInteger GetOpsTillSuspend()
Get the number of operations the script can execute before being suspended.
Definition: script_instance.cpp:686
SQSL_BOOL
@ SQSL_BOOL
The following data is a boolean.
Definition: script_instance.cpp:340
ScriptInstance::Pause
void Pause()
Suspends the script for the current tick and then pause the execution of script.
Definition: script_instance.cpp:544
ScriptInstance::DoCommandReturnGoalID
static void DoCommandReturnGoalID(ScriptInstance *instance)
Return a GoalID reply for a DoCommand.
Definition: script_instance.cpp:286
ScriptInstance::ReleaseSQObject
void ReleaseSQObject(HSQOBJECT *obj)
Decrease the ref count of a squirrel object.
Definition: script_instance.cpp:728
ScriptInstance::storage
class ScriptStorage * storage
Some global information for each running script.
Definition: script_instance.hpp:248
Squirrel::GetOpsTillSuspend
SQInteger GetOpsTillSuspend()
How many operations can we execute till suspension?
Definition: squirrel.cpp:831
Squirrel
Definition: squirrel.hpp:23
Squirrel::HasScriptCrashed
bool HasScriptCrashed()
Find out if the squirrel script made an error before.
Definition: squirrel.cpp:815
Squirrel::LoadScript
bool LoadScript(const char *script)
Load a script.
Definition: squirrel.cpp:753
ScriptInstance::DoCommandReturnSignID
static void DoCommandReturnSignID(ScriptInstance *instance)
Return a SignID reply for a DoCommand.
Definition: script_instance.cpp:276
CommandCost
Common return value for all commands.
Definition: command_type.h:24
ScriptInstance::in_shutdown
bool in_shutdown
Is this instance currently being destructed?
Definition: script_instance.hpp:256
script_storage.hpp
_script_byte
static const SaveLoad _script_byte[]
SaveLoad array that saves/loads exactly one byte.
Definition: script_instance.cpp:348
Squirrel::ThrowError
void ThrowError(const char *error)
Throw a Squirrel error that will be nicely displayed to the user.
Definition: squirrel.hpp:236
GameSettings::script
ScriptSettings script
settings for scripts
Definition: settings_type.h:584
StrMakeValidInPlace
void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:273
ScriptInstance::DoCommandReturn
static void DoCommandReturn(ScriptInstance *instance)
Return a true/false reply for a DoCommand.
Definition: script_instance.cpp:266
ScriptInstance::SaveEmpty
static void SaveEmpty()
Don't save any data in the savegame.
Definition: script_instance.cpp:468
SQSL_NULL
@ SQSL_NULL
A null variable.
Definition: script_instance.cpp:341
FileExists
bool FileExists(const std::string &filename)
Test whether the given filename exists.
Definition: fileio.cpp:122
SLEG_VAR
#define SLEG_VAR(name, variable, type)
Storage of a global variable in every savegame version.
Definition: saveload.h:941
Squirrel::SetGlobalPointer
void SetGlobalPointer(void *ptr)
Sets a pointer in the VM that is reachable from where ever you are in SQ.
Definition: squirrel.hpp:221
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:160
ScriptInstance::IsDead
bool IsDead() const
Return the "this script died" value.
Definition: script_instance.hpp:126
ScriptStorage::event_data
void * event_data
Pointer to the event data storage.
Definition: script_storage.hpp:57
Squirrel::GetAllocatedMemory
size_t GetAllocatedMemory() const noexcept
Get number of bytes allocated by this VM.
Definition: squirrel.cpp:202
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
ScriptInstance::is_started
bool is_started
Is the scripts constructor executed?
Definition: script_instance.hpp:251
IsSavegameVersionBefore
static bool IsSavegameVersionBefore(SaveLoadVersion major, byte minor=0)
Checks whether the savegame is below major.
Definition: saveload.h:1028
ScriptInstance::DoCommandReturnStoryPageID
static void DoCommandReturnStoryPageID(ScriptInstance *instance)
Return a StoryPageID reply for a DoCommand.
Definition: script_instance.cpp:291
ScriptInstance::RegisterAPI
virtual void RegisterAPI()
Register all API functions to the VM.
Definition: script_instance.cpp:110
Squirrel::CallMethod
bool CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend)
Call a method of an instance, in various flavors.
Definition: squirrel.cpp:421
ScriptInstance::Initialize
void Initialize(const char *main_script, const char *instance_name, CompanyID company)
Initialize the script and prepare it for its first run.
Definition: script_instance.cpp:70
ScriptScanner::main_script
std::string main_script
The full path of the script.
Definition: script_scanner.hpp:87
ScriptInstance::LoadEmpty
static void LoadEmpty()
Load and discard data from a savegame.
Definition: script_instance.cpp:621
ScriptInstance::DoCommandReturnGroupID
static void DoCommandReturnGroupID(ScriptInstance *instance)
Return a GroupID reply for a DoCommand.
Definition: script_instance.cpp:281
Script_Suspend::GetSuspendCallback
Script_SuspendCallbackProc * GetSuspendCallback()
Get the callback to call when the script can run again.
Definition: script_suspend.hpp:43
squirrel_register_std
void squirrel_register_std(Squirrel *engine)
Register all standard functions we want to give to a script.
Definition: squirrel_std.cpp:102
SLV_SCRIPT_INT64
@ SLV_SCRIPT_INT64
296 PR#9415 SQInteger is 64bit but was saved as 32bit.
Definition: saveload.h:339
Squirrel::ResumeError
void ResumeError()
Resume the VM with an error so it prints a stack trace.
Definition: squirrel.cpp:408
Squirrel::CreateClassInstance
bool CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
Exactly the same as CreateClassInstanceVM, only callable without instance of Squirrel.
Definition: squirrel.cpp:533
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
MAX_CONSTRUCTOR_OPS
static const int MAX_CONSTRUCTOR_OPS
The maximum number of operations for initial start of a script.
Definition: script_info.hpp:21
Squirrel::CollectGarbage
void CollectGarbage()
Tell the VM to do a garbage collection run.
Definition: squirrel.cpp:415
ScriptInstance::callback
Script_SuspendCallbackProc * callback
Callback that should be called in the next tick the script runs.
Definition: script_instance.hpp:257
Squirrel::MethodExists
bool MethodExists(HSQOBJECT instance, const char *method_name)
Check if a method exists in an instance.
Definition: squirrel.cpp:368
Squirrel::CrashOccurred
void CrashOccurred()
Set the script status to crashed.
Definition: squirrel.cpp:820
ScriptSettings::script_max_opcode_till_suspend
uint32 script_max_opcode_till_suspend
max opcode calls till scripts will suspend
Definition: settings_type.h:374
script_info.hpp
ScriptInstance::DoCommandReturnVehicleID
static void DoCommandReturnVehicleID(ScriptInstance *instance)
Return a VehicleID reply for a DoCommand.
Definition: script_instance.cpp:271
ScriptInstance::GetStorage
class ScriptStorage * GetStorage()
Get the storage of this script.
Definition: script_instance.cpp:301
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:553
script_instance.hpp
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
ScriptInstance::Died
virtual void Died()
Tell the script it died.
Definition: script_instance.cpp:154
ScriptInstance::suspend
int suspend
The amount of ticks to suspend this script before it's allowed to continue.
Definition: script_instance.hpp:254
Squirrel::Resume
bool Resume(int suspend=-1)
Resume a VM when it was suspended via a throw.
Definition: squirrel.cpp:386
Script_FatalError
A throw-class that is given when the script made a fatal error.
Definition: script_fatalerror.hpp:16
ScriptInstance::Continue
void Continue()
A script in multiplayer waits for the server to handle its DoCommand.
Definition: script_instance.cpp:148
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
script_fatalerror.hpp
Squirrel::ReleaseObject
void ReleaseObject(HSQOBJECT *ptr)
Release a SQ object.
Definition: squirrel.hpp:241
ScriptInstance::IsPaused
bool IsPaused()
Checks if the script is paused.
Definition: script_instance.cpp:558
Squirrel::IsSuspended
bool IsSuspended()
Did the squirrel code suspend or return normally.
Definition: squirrel.cpp:810
ScriptInstance::LoadCompatibilityScripts
bool LoadCompatibilityScripts(const char *api_version, Subdirectory dir)
Load squirrel scripts to emulate an older API.
Definition: script_instance.cpp:116
ScriptInstance::CollectGarbage
void CollectGarbage()
Let the VM collect any garbage.
Definition: script_instance.cpp:258
ScriptInstance::Load
void Load(int version)
Load data from a savegame and store it on the stack.
Definition: script_instance.cpp:630
SlObject
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
Definition: saveload.cpp:1838
SQSL_ARRAY_TABLE_END
@ SQSL_ARRAY_TABLE_END
Marks the end of an array or table, no data follows.
Definition: script_instance.cpp:342
SaveLoad
SaveLoad type struct.
Definition: saveload.h:657
Squirrel::DecreaseOps
static void DecreaseOps(HSQUIRRELVM vm, int amount)
Tell the VM to remove amount ops from the number of ops till suspend.
Definition: squirrel.cpp:805
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
ScriptInstance::GetLogPointer
void * GetLogPointer()
Get the log pointer of this script.
Definition: script_instance.cpp:306
SQUIRREL_MAX_DEPTH
static const uint SQUIRREL_MAX_DEPTH
The maximum recursive depth for items stored in the savegame.
Definition: script_instance.hpp:20
MAX_SL_OPS
static const int MAX_SL_OPS
The maximum number of operations for saving or loading the data of a script.
Definition: script_info.hpp:19