OpenTTD Source 20241224-master-gf74b0cf984
ScriptInstance Class Referenceabstract

Runtime information about a script like a pointer to the squirrel vm and the current state. More...

#include <script_instance.hpp>

Inheritance diagram for ScriptInstance:
AIInstance GameInstance

Public Types

typedef std::variant< SQInteger, std::string, SQBool, SQSaveLoadTypeScriptDataVariant
 
typedef std::list< ScriptDataVariant > ScriptData
 

Public Member Functions

 ScriptInstance (const char *APIName)
 Create a new script.
 
void Initialize (const std::string &main_script, const std::string &instance_name, CompanyID company)
 Initialize the script and prepare it for its first run.
 
virtual int GetSetting (const std::string &name)=0
 Get the value of a setting of the current instance.
 
virtual class ScriptInfoFindLibrary (const std::string &library, int version)=0
 Find a library.
 
void Continue ()
 A script in multiplayer waits for the server to handle its DoCommand.
 
void GameLoop ()
 Run the GameLoop of a script.
 
void CollectGarbage ()
 Let the VM collect any garbage.
 
class ScriptStorageGetStorage ()
 Get the storage of this script.
 
ScriptLogTypes::LogData & GetLogData ()
 Get the log pointer of this script.
 
class ScriptController * GetController ()
 Get the controller attached to the instance.
 
bool IsDead () const
 Return the "this script died" value.
 
bool IsAlive () const
 Return whether the script is alive.
 
void Save ()
 Call the script Save function and save all data in the savegame.
 
void LoadOnStack (ScriptData *data)
 Store loaded data on the stack.
 
void Pause ()
 Suspends the script for the current tick and then pause the execution of script.
 
bool IsPaused ()
 Checks if the script is paused.
 
void Unpause ()
 Resume execution of the script.
 
SQInteger GetOpsTillSuspend ()
 Get the number of operations the script can execute before being suspended.
 
bool DoCommandCallback (const CommandCost &result, const CommandDataBuffer &data, CommandDataBuffer result_data, Commands cmd)
 DoCommand callback function for all commands executed by scripts.
 
void InsertEvent (class ScriptEvent *event)
 Insert an event for this script.
 
bool IsSleeping ()
 Check if the instance is sleeping, which either happened because the script executed a DoCommand, executed this.Sleep() or it has been paused.
 
size_t GetAllocatedMemory () const
 
bool InShutdown () const
 Indicate whether this instance is currently being destroyed.
 
void ReleaseSQObject (HSQOBJECT *obj)
 Decrease the ref count of a squirrel object.
 

Static Public Member Functions

static void DoCommandReturn (ScriptInstance *instance)
 Return a true/false reply for a DoCommand.
 
static void DoCommandReturnVehicleID (ScriptInstance *instance)
 Return a VehicleID reply for a DoCommand.
 
static void DoCommandReturnSignID (ScriptInstance *instance)
 Return a SignID reply for a DoCommand.
 
static void DoCommandReturnGroupID (ScriptInstance *instance)
 Return a GroupID reply for a DoCommand.
 
static void DoCommandReturnGoalID (ScriptInstance *instance)
 Return a GoalID reply for a DoCommand.
 
static void DoCommandReturnStoryPageID (ScriptInstance *instance)
 Return a StoryPageID reply for a DoCommand.
 
static void DoCommandReturnStoryPageElementID (ScriptInstance *instance)
 Return a StoryPageElementID reply for a DoCommand.
 
static void DoCommandReturnLeagueTableID (ScriptInstance *instance)
 Return a LeagueTableID reply for a DoCommand.
 
static void DoCommandReturnLeagueTableElementID (ScriptInstance *instance)
 Return a LeagueTableElementID reply for a DoCommand.
 
static void SaveEmpty ()
 Don't save any data in the savegame.
 
static ScriptData * Load (int version)
 Load data from a savegame.
 
static void LoadEmpty ()
 Load and discard data from a savegame.
 

Protected Member Functions

virtual void RegisterAPI ()
 Register all API functions to the VM.
 
bool LoadCompatibilityScripts (const std::string &api_version, Subdirectory dir)
 Load squirrel scripts to emulate an older API.
 
virtual void Died ()
 Tell the script it died.
 
virtual CommandCallbackDataGetDoCommandCallback ()=0
 Get the callback handling DoCommands in case of networking.
 
virtual void LoadDummyScript ()=0
 Load the dummy script.
 

Protected Attributes

class Squirrelengine
 A wrapper around the squirrel vm.
 
std::string versionAPI
 Current API used by this script.
 

Private Types

enum  SQSaveLoadType {
  SQSL_INT = 0x00 , SQSL_STRING = 0x01 , SQSL_ARRAY = 0x02 , SQSL_TABLE = 0x03 ,
  SQSL_BOOL = 0x04 , SQSL_NULL = 0x05 , SQSL_ARRAY_TABLE_END = 0xFF
}
 The type of the data that follows in the savegame. More...
 

Private Member Functions

bool CallLoad ()
 Call the script Load function if it exists and data was loaded from a savegame.
 

Static Private Member Functions

static bool SaveObject (HSQUIRRELVM vm, SQInteger index, int max_depth, bool test)
 Save one object (int / string / array / table) to the savegame.
 
static bool LoadObjects (ScriptData *data)
 Load all objects from a savegame.
 
static bool LoadObjects (HSQUIRRELVM vm, ScriptData *data)
 

Private Attributes

class ScriptController * controller
 The script main class.
 
class ScriptStoragestorage
 Some global information for each running script.
 
SQObject * instance
 Squirrel-pointer to the script main class.
 
bool is_started
 Is the scripts constructor executed?
 
bool is_dead
 True if the script has been stopped.
 
bool is_save_data_on_stack
 Is the save data still on the squirrel stack?
 
int suspend
 The amount of ticks to suspend this script before it's allowed to continue.
 
bool is_paused
 Is the script paused? (a paused script will not be executed until unpaused)
 
bool in_shutdown
 Is this instance currently being destructed?
 
Script_SuspendCallbackProccallback
 Callback that should be called in the next tick the script runs.
 
size_t last_allocated_memory
 Last known allocated memory value (for display for crashed scripts)
 

Friends

class ScriptObject
 
class ScriptController
 

Detailed Description

Runtime information about a script like a pointer to the squirrel vm and the current state.

Definition at line 25 of file script_instance.hpp.

Member Typedef Documentation

◆ ScriptData

typedef std::list<ScriptDataVariant> ScriptInstance::ScriptData

Definition at line 43 of file script_instance.hpp.

◆ ScriptDataVariant

typedef std::variant<SQInteger, std::string, SQBool, SQSaveLoadType> ScriptInstance::ScriptDataVariant

Definition at line 42 of file script_instance.hpp.

Member Enumeration Documentation

◆ SQSaveLoadType

The type of the data that follows in the savegame.

Enumerator
SQSL_INT 

The following data is an integer.

SQSL_STRING 

The following data is an string.

SQSL_ARRAY 

The following data is an array.

SQSL_TABLE 

The following data is an table.

SQSL_BOOL 

The following data is a boolean.

SQSL_NULL 

A null variable.

SQSL_ARRAY_TABLE_END 

Marks the end of an array or table, no data follows.

Definition at line 28 of file script_instance.hpp.

Constructor & Destructor Documentation

◆ ScriptInstance()

ScriptInstance::ScriptInstance ( const char *  APIName)

Create a new script.

Definition at line 52 of file script_instance.cpp.

References engine, PrintFunc(), Squirrel::SetPrintFunction(), and storage.

◆ ~ScriptInstance()

ScriptInstance::~ScriptInstance ( )
virtual

Definition at line 138 of file script_instance.cpp.

Member Function Documentation

◆ CallLoad()

bool ScriptInstance::CallLoad ( )
private

Call the script Load function if it exists and data was loaded from a savegame.

Definition at line 706 of file script_instance.cpp.

References engine, Squirrel::GetVM(), instance, is_save_data_on_stack, MAX_SL_OPS, and Squirrel::MethodExists().

Referenced by GameLoop().

◆ CollectGarbage()

void ScriptInstance::CollectGarbage ( )

Let the VM collect any garbage.

Definition at line 260 of file script_instance.cpp.

References Squirrel::CollectGarbage(), engine, is_started, and IsDead().

Referenced by Game::GameLoop().

◆ Continue()

void ScriptInstance::Continue ( )

A script in multiplayer waits for the server to handle its DoCommand.

It keeps waiting for this until this function is called.

Definition at line 150 of file script_instance.cpp.

References suspend.

Referenced by CcGame().

◆ Died()

void ScriptInstance::Died ( )
protectedvirtual

Tell the script it died.

Reimplemented in AIInstance, and GameInstance.

Definition at line 156 of file script_instance.cpp.

References Debug, engine, in_shutdown, instance, is_dead, last_allocated_memory, and Squirrel::ReleaseObject().

Referenced by AIInstance::Died(), GameInstance::Died(), GameLoop(), and Initialize().

◆ DoCommandCallback()

bool ScriptInstance::DoCommandCallback ( const CommandCost result,
const CommandDataBuffer data,
CommandDataBuffer  result_data,
Commands  cmd 
)

DoCommand callback function for all commands executed by scripts.

Parameters
resultThe result of the command.
tileThe tile on which the command was executed.
dataCommand data as given to DoCommandPInternal.
result_dataExtra data return from the command.
cmdcmd as given to DoCommandPInternal.
Returns
true if we handled result.

Definition at line 748 of file script_instance.cpp.

References CMD_END, Debug, CommandCost::Failed(), CommandCost::GetCost(), CommandCost::GetErrorMessage(), and CommandCost::Succeeded().

◆ DoCommandReturn()

void ScriptInstance::DoCommandReturn ( ScriptInstance instance)
static

Return a true/false reply for a DoCommand.

Definition at line 268 of file script_instance.cpp.

References instance.

◆ DoCommandReturnGoalID()

void ScriptInstance::DoCommandReturnGoalID ( ScriptInstance instance)
static

Return a GoalID reply for a DoCommand.

Definition at line 288 of file script_instance.cpp.

References instance.

◆ DoCommandReturnGroupID()

void ScriptInstance::DoCommandReturnGroupID ( ScriptInstance instance)
static

Return a GroupID reply for a DoCommand.

Definition at line 283 of file script_instance.cpp.

References instance.

◆ DoCommandReturnLeagueTableElementID()

void ScriptInstance::DoCommandReturnLeagueTableElementID ( ScriptInstance instance)
static

Return a LeagueTableElementID reply for a DoCommand.

Definition at line 303 of file script_instance.cpp.

References instance.

◆ DoCommandReturnLeagueTableID()

void ScriptInstance::DoCommandReturnLeagueTableID ( ScriptInstance instance)
static

Return a LeagueTableID reply for a DoCommand.

Definition at line 308 of file script_instance.cpp.

References instance.

◆ DoCommandReturnSignID()

void ScriptInstance::DoCommandReturnSignID ( ScriptInstance instance)
static

Return a SignID reply for a DoCommand.

Definition at line 278 of file script_instance.cpp.

References instance.

◆ DoCommandReturnStoryPageElementID()

void ScriptInstance::DoCommandReturnStoryPageElementID ( ScriptInstance instance)
static

Return a StoryPageElementID reply for a DoCommand.

Definition at line 298 of file script_instance.cpp.

References instance.

◆ DoCommandReturnStoryPageID()

void ScriptInstance::DoCommandReturnStoryPageID ( ScriptInstance instance)
static

Return a StoryPageID reply for a DoCommand.

Definition at line 293 of file script_instance.cpp.

References instance.

◆ DoCommandReturnVehicleID()

void ScriptInstance::DoCommandReturnVehicleID ( ScriptInstance instance)
static

Return a VehicleID reply for a DoCommand.

Definition at line 273 of file script_instance.cpp.

References instance.

◆ FindLibrary()

virtual class ScriptInfo * ScriptInstance::FindLibrary ( const std::string &  library,
int  version 
)
pure virtual

Find a library.

Parameters
libraryThe library name to find.
versionThe version the library should have.
Returns
The library if found, nullptr otherwise.

Implemented in AIInstance, and GameInstance.

◆ GameLoop()

◆ GetAllocatedMemory()

size_t ScriptInstance::GetAllocatedMemory ( ) const

Definition at line 779 of file script_instance.cpp.

◆ GetController()

class ScriptController * ScriptInstance::GetController ( )
inline

Get the controller attached to the instance.

Definition at line 148 of file script_instance.hpp.

References controller.

◆ GetDoCommandCallback()

virtual CommandCallbackData * ScriptInstance::GetDoCommandCallback ( )
protectedpure virtual

Get the callback handling DoCommands in case of networking.

Implemented in AIInstance, and GameInstance.

◆ GetLogData()

ScriptLogTypes::LogData & ScriptInstance::GetLogData ( )

Get the log pointer of this script.

Definition at line 319 of file script_instance.cpp.

◆ GetOpsTillSuspend()

SQInteger ScriptInstance::GetOpsTillSuspend ( )

Get the number of operations the script can execute before being suspended.

This function is safe to call from within a function called by the script.

Returns
The number of operations to execute.

Definition at line 743 of file script_instance.cpp.

References engine, and Squirrel::GetOpsTillSuspend().

◆ GetSetting()

virtual int ScriptInstance::GetSetting ( const std::string &  name)
pure virtual

Get the value of a setting of the current instance.

Parameters
nameThe name of the setting.
Returns
the value for the setting, or -1 if the setting is not known.

Implemented in AIInstance, and GameInstance.

◆ GetStorage()

ScriptStorage * ScriptInstance::GetStorage ( )

Get the storage of this script.

Definition at line 314 of file script_instance.cpp.

References storage.

◆ Initialize()

void ScriptInstance::Initialize ( const std::string &  main_script,
const std::string &  instance_name,
CompanyID  company 
)

Initialize the script and prepare it for its first run.

Parameters
main_scriptThe full path of the script to load.
instance_nameThe name of the instance out of the script to load.
companyWhich company this script is serving.

Definition at line 70 of file script_instance.cpp.

References controller, Squirrel::CreateClassInstance(), Died(), engine, Script_FatalError::GetErrorMessage(), instance, is_dead, IsDead(), Squirrel::IsSuspended(), LoadDummyScript(), Squirrel::LoadScript(), RegisterAPI(), Squirrel::ResumeError(), Squirrel::SetGlobalPointer(), and Squirrel::ThrowError().

Referenced by AIInstance::Initialize(), and GameInstance::Initialize().

◆ InsertEvent()

void ScriptInstance::InsertEvent ( class ScriptEvent *  event)

Insert an event for this script.

Parameters
eventThe event to insert.

Definition at line 772 of file script_instance.cpp.

Referenced by Game::NewEvent().

◆ InShutdown()

bool ScriptInstance::InShutdown ( ) const
inline

Indicate whether this instance is currently being destroyed.

Definition at line 245 of file script_instance.hpp.

References in_shutdown.

◆ IsAlive()

bool ScriptInstance::IsAlive ( ) const
inline

Return whether the script is alive.

Definition at line 158 of file script_instance.hpp.

References in_shutdown, and IsDead().

◆ IsDead()

bool ScriptInstance::IsDead ( ) const
inline

◆ IsPaused()

bool ScriptInstance::IsPaused ( )

Checks if the script is paused.

Returns
true if the script is paused, otherwise false

Definition at line 560 of file script_instance.cpp.

References is_paused.

Referenced by Game::IsPaused(), and ScriptDebugWindow::UpdateGSButtonState().

◆ IsSleeping()

bool ScriptInstance::IsSleeping ( )
inline

Check if the instance is sleeping, which either happened because the script executed a DoCommand, executed this.Sleep() or it has been paused.

Definition at line 238 of file script_instance.hpp.

References suspend.

◆ Load()

ScriptInstance::ScriptData * ScriptInstance::Load ( int  version)
static

Load data from a savegame.

Parameters
versionThe version of the script when saving, or -1 if this was not the original script saving the game.
Returns
a pointer to loaded data.

Definition at line 667 of file script_instance.cpp.

References _script_byte, _script_sl_byte, LoadEmpty(), LoadObjects(), and SlObject().

Referenced by AIPLChunkHandler::Load(), and GSDTChunkHandler::Load().

◆ LoadCompatibilityScripts()

bool ScriptInstance::LoadCompatibilityScripts ( const std::string &  api_version,
Subdirectory  dir 
)
protected

Load squirrel scripts to emulate an older API.

Parameters
api_versionAPI version to load scripts for
dirSubdirectory to find the scripts in
Returns
true iff script loading should proceed

Definition at line 119 of file script_instance.cpp.

References Debug, engine, FileExists(), and Squirrel::LoadScript().

Referenced by AIInstance::RegisterAPI(), and GameInstance::RegisterAPI().

◆ LoadDummyScript()

virtual void ScriptInstance::LoadDummyScript ( )
protectedpure virtual

Load the dummy script.

Implemented in AIInstance, and GameInstance.

Referenced by Initialize().

◆ LoadEmpty()

void ScriptInstance::LoadEmpty ( )
static

Load and discard data from a savegame.

Definition at line 658 of file script_instance.cpp.

References _script_byte, _script_sl_byte, LoadObjects(), and SlObject().

Referenced by AIPLChunkHandler::Load(), GSDTChunkHandler::Load(), and Load().

◆ LoadObjects() [1/2]

bool ScriptInstance::LoadObjects ( HSQUIRRELVM  vm,
ScriptData *  data 
)
staticprivate

Definition at line 611 of file script_instance.cpp.

◆ LoadObjects() [2/2]

bool ScriptInstance::LoadObjects ( ScriptData *  data)
staticprivate

Load all objects from a savegame.

Returns
True if the loading was successful.

Definition at line 565 of file script_instance.cpp.

References _script_byte, _script_sl_byte, IsSavegameVersionBefore(), LoadObjects(), SlCopy(), SlErrorCorrupt(), SlObject(), SLV_SCRIPT_INT64, SQSL_ARRAY, SQSL_ARRAY_TABLE_END, SQSL_BOOL, SQSL_INT, SQSL_NULL, SQSL_STRING, SQSL_TABLE, and StrMakeValid().

Referenced by Load(), LoadEmpty(), LoadObjects(), and LoadOnStack().

◆ LoadOnStack()

void ScriptInstance::LoadOnStack ( ScriptData *  data)

Store loaded data on the stack.

Parameters
dataThe loaded data to store on the stack.

Definition at line 684 of file script_instance.cpp.

References engine, Script_FatalError::GetErrorMessage(), Squirrel::GetVM(), is_save_data_on_stack, IsDead(), and LoadObjects().

Referenced by Game::StartNew().

◆ Pause()

void ScriptInstance::Pause ( )

Suspends the script for the current tick and then pause the execution of script.

The script will not be resumed from its suspended state until the script has been unpaused.

Definition at line 546 of file script_instance.cpp.

References _settings_game, Squirrel::DecreaseOps(), engine, Squirrel::GetVM(), is_paused, GameSettings::script, and ScriptSettings::script_max_opcode_till_suspend.

Referenced by Game::Pause().

◆ RegisterAPI()

void ScriptInstance::RegisterAPI ( )
protectedvirtual

Register all API functions to the VM.

Reimplemented in AIInstance, and GameInstance.

Definition at line 114 of file script_instance.cpp.

References engine, and squirrel_register_std().

Referenced by Initialize(), AIInstance::RegisterAPI(), and GameInstance::RegisterAPI().

◆ ReleaseSQObject()

void ScriptInstance::ReleaseSQObject ( HSQOBJECT *  obj)

Decrease the ref count of a squirrel object.

Parameters
objThe object to release.

Definition at line 785 of file script_instance.cpp.

References engine, in_shutdown, and Squirrel::ReleaseObject().

◆ Save()

◆ SaveEmpty()

void ScriptInstance::SaveEmpty ( )
static

Don't save any data in the savegame.

Definition at line 470 of file script_instance.cpp.

References _script_byte, _script_sl_byte, and SlObject().

Referenced by Game::Save(), Save(), and AI::Save().

◆ SaveObject()

bool ScriptInstance::SaveObject ( HSQUIRRELVM  vm,
SQInteger  index,
int  max_depth,
bool  test 
)
staticprivate

Save one object (int / string / array / table) to the savegame.

Parameters
vmThe virtual machine to get all the data from.
indexThe index on the squirrel stack of the element to save.
max_depthThe maximum depth recursive arrays / tables will be stored with before an error is returned.
testIf true, don't really store the data but only check if it is valid.
Returns
True if the saving was successful.

Definition at line 354 of file script_instance.cpp.

References _script_byte, _script_sl_byte, SaveObject(), SlCopy(), SlObject(), SQSL_ARRAY, SQSL_ARRAY_TABLE_END, SQSL_BOOL, SQSL_INT, SQSL_NULL, SQSL_STRING, and SQSL_TABLE.

Referenced by Save(), and SaveObject().

◆ Unpause()

void ScriptInstance::Unpause ( )

Resume execution of the script.

This function will not actually execute the script, but set a flag so that the script is executed my the usual mechanism that executes the script.

Definition at line 555 of file script_instance.cpp.

References is_paused.

Referenced by Game::Unpause().

Friends And Related Symbol Documentation

◆ ScriptController

friend class ScriptController
friend

Definition at line 40 of file script_instance.hpp.

◆ ScriptObject

friend class ScriptObject
friend

Definition at line 39 of file script_instance.hpp.

Field Documentation

◆ callback

Script_SuspendCallbackProc* ScriptInstance::callback
private

Callback that should be called in the next tick the script runs.

Definition at line 296 of file script_instance.hpp.

Referenced by GameLoop().

◆ controller

class ScriptController* ScriptInstance::controller
private

The script main class.

Definition at line 286 of file script_instance.hpp.

Referenced by GameLoop(), GetController(), and Initialize().

◆ engine

◆ in_shutdown

bool ScriptInstance::in_shutdown
private

Is this instance currently being destructed?

Definition at line 295 of file script_instance.hpp.

Referenced by Died(), InShutdown(), IsAlive(), and ReleaseSQObject().

◆ instance

◆ is_dead

bool ScriptInstance::is_dead
private

True if the script has been stopped.

Definition at line 291 of file script_instance.hpp.

Referenced by Died(), GameLoop(), Initialize(), IsDead(), and Save().

◆ is_paused

bool ScriptInstance::is_paused
private

Is the script paused? (a paused script will not be executed until unpaused)

Definition at line 294 of file script_instance.hpp.

Referenced by GameLoop(), IsPaused(), Pause(), and Unpause().

◆ is_save_data_on_stack

bool ScriptInstance::is_save_data_on_stack
private

Is the save data still on the squirrel stack?

Definition at line 292 of file script_instance.hpp.

Referenced by CallLoad(), GameLoop(), LoadOnStack(), and Save().

◆ is_started

bool ScriptInstance::is_started
private

Is the scripts constructor executed?

Definition at line 290 of file script_instance.hpp.

Referenced by CollectGarbage(), GameLoop(), and Save().

◆ last_allocated_memory

size_t ScriptInstance::last_allocated_memory
private

Last known allocated memory value (for display for crashed scripts)

Definition at line 297 of file script_instance.hpp.

Referenced by Died().

◆ storage

class ScriptStorage* ScriptInstance::storage
private

Some global information for each running script.

Definition at line 287 of file script_instance.hpp.

Referenced by GetStorage(), and ScriptInstance().

◆ suspend

int ScriptInstance::suspend
private

The amount of ticks to suspend this script before it's allowed to continue.

Definition at line 293 of file script_instance.hpp.

Referenced by Continue(), GameLoop(), and IsSleeping().

◆ versionAPI

std::string ScriptInstance::versionAPI
protected

Current API used by this script.

Definition at line 255 of file script_instance.hpp.

Referenced by AIInstance::Initialize(), GameInstance::Initialize(), AIInstance::RegisterAPI(), and GameInstance::RegisterAPI().


The documentation for this class was generated from the following files: