OpenTTD Source: src/script/squirrel.hpp Source File

OpenTTD Source 15.3

squirrel.hpp
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#ifndef SQUIRREL_HPP
11#define SQUIRREL_HPP
12
13#include <squirrel.h>
14#include "../core/convertible_through_base.hpp"
15
17 enum class ScriptType : uint8_t {
18 AI,
19 GS,
20};
21
22struct ScriptAllocator;
23
24 class Squirrel {
25 friend class ScriptAllocatorScope;
26 friend class ScriptInstance;
27
28private:
29 using SQPrintFunc = void (bool error_msg, std::string_view message);
30
31 HSQUIRRELVM vm;
32 void *global_pointer;
33 SQPrintFunc *print_func;
34 bool crashed;
35 int overdrawn_ops;
36 std::string_view api_name;
37 std::unique_ptr<ScriptAllocator> allocator;
38
42 static SQInteger _RunError(HSQUIRRELVM vm);
43
47 std::string_view GetAPIName() { return this->api_name; }
48
50 void Initialize();
52 void Uninitialize();
53
54protected:
58 static void CompileError(HSQUIRRELVM vm, std::string_view desc, std::string_view source, SQInteger line, SQInteger column);
59
63 static void RunError(HSQUIRRELVM vm, std::string_view error);
64
68 static void PrintFunc(HSQUIRRELVM vm, std::string_view s);
69
73 static void ErrorPrintFunc(HSQUIRRELVM vm, std::string_view s);
74
75public:
76 Squirrel(std::string_view api_name);
77 ~Squirrel();
78
82 HSQUIRRELVM GetVM() { return this->vm; }
83
89 bool LoadScript(const std::string &script);
90 bool LoadScript(HSQUIRRELVM vm, const std::string &script, bool in_root = true);
91
95 SQRESULT LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool printerror);
96
101 void AddMethod(std::string_view method_name, SQFUNCTION proc, std::string_view params = {}, void *userdata = nullptr, int size = 0);
102
107 void AddConst(std::string_view var_name, SQInteger value);
108
113 void AddConst(std::string_view var_name, uint value) { this->AddConst(var_name, (SQInteger)value); }
114
119 void AddConst(std::string_view var_name, int value) { this->AddConst(var_name, (SQInteger)value); }
120
121 void AddConst(std::string_view var_name, const ConvertibleThroughBase auto &value) { this->AddConst(var_name, static_cast<SQInteger>(value.base())); }
122
127 void AddConst(std::string_view var_name, bool value);
128
133 void AddClassBegin(std::string_view class_name);
134
139 void AddClassBegin(std::string_view class_name, std::string_view parent_class);
140
145 void AddClassEnd();
146
150 bool Resume(int suspend = -1);
151
155 void ResumeError();
156
160 void CollectGarbage();
161
162 void InsertResult(bool result);
163 void InsertResult(int result);
164 void InsertResult(uint result) { this->InsertResult((int)result); }
165 void InsertResult(ConvertibleThroughBase auto result) { this->InsertResult(static_cast<int>(result.base())); }
166
171 bool CallMethod(HSQOBJECT instance, std::string_view method_name, HSQOBJECT *ret, int suspend);
172 bool CallMethod(HSQOBJECT instance, std::string_view method_name, int suspend) { return this->CallMethod(instance, method_name, nullptr, suspend); }
173 bool CallStringMethod(HSQOBJECT instance, std::string_view method_name, std::string *res, int suspend);
174 bool CallIntegerMethod(HSQOBJECT instance, std::string_view method_name, int *res, int suspend);
175 bool CallBoolMethod(HSQOBJECT instance, std::string_view method_name, bool *res, int suspend);
176
180 bool MethodExists(HSQOBJECT instance, std::string_view method_name);
181
192 static bool CreateClassInstanceVM(HSQUIRRELVM vm, const std::string &class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name = false);
193
197 bool CreateClassInstance(const std::string &class_name, void *real_instance, HSQOBJECT *instance);
198
204 static SQUserPointer GetRealInstance(HSQUIRRELVM vm, int index, std::string_view tag);
205
211 static bool GetInstance(HSQUIRRELVM vm, HSQOBJECT *ptr, int pos = 1) { sq_getclass(vm, pos); sq_getstackobj(vm, pos, ptr); sq_pop(vm, 1); return true; }
212
216 static std::optional<std::string_view> ObjectToString(HSQOBJECT *ptr) { return sq_objtostring(ptr); }
217
221 static int ObjectToInteger(HSQOBJECT *ptr) { return sq_objtointeger(ptr); }
222
226 static bool ObjectToBool(HSQOBJECT *ptr) { return sq_objtobool(ptr) == 1; }
227
232 void SetGlobalPointer(void *ptr) { this->global_pointer = ptr; }
233
237 static void *GetGlobalPointer(HSQUIRRELVM vm) { return ((Squirrel *)sq_getforeignptr(vm))->global_pointer; }
238
242 void SetPrintFunction(SQPrintFunc *func) { this->print_func = func; }
243
247 void ThrowError(std::string_view error) { sq_throwerror(this->vm, error); }
248
252 void ReleaseObject(HSQOBJECT *ptr) { sq_release(this->vm, ptr); }
253
257 static void DecreaseOps(HSQUIRRELVM vm, int amount);
258
263 bool IsSuspended();
264
268 bool HasScriptCrashed();
269
273 void CrashOccurred();
274
278 bool CanSuspend();
279
283 SQInteger GetOpsTillSuspend();
284
288 void Reset();
289
293 size_t GetAllocatedMemory() const noexcept;
294};
295
296
297extern ScriptAllocator *_squirrel_allocator;
298
299class ScriptAllocatorScope {
300 ScriptAllocator *old_allocator;
301
302public:
303 ScriptAllocatorScope(const Squirrel *engine)
304 {
305 this->old_allocator = _squirrel_allocator;
306 /* This may get called with a nullptr engine, in case of a crashed script */
307 _squirrel_allocator = engine != nullptr ? engine->allocator.get() : nullptr;
308 }
309
310 ~ScriptAllocatorScope()
311 {
312 _squirrel_allocator = this->old_allocator;
313 }
314};
315
316#endif /* SQUIRREL_HPP */
ScriptAllocatorScope
Definition squirrel.hpp:299
ScriptInstance
Runtime information about a script like a pointer to the squirrel vm and the current state.
Definition script_instance.hpp:25
Squirrel
Definition squirrel.hpp:24
Squirrel::AddClassEnd
void AddClassEnd()
Finishes adding a class to the global scope.
Definition squirrel.cpp:315
Squirrel::Resume
bool Resume(int suspend=-1)
Resume a VM when it was suspended via a throw.
Definition squirrel.cpp:341
Squirrel::GetGlobalPointer
static void * GetGlobalPointer(HSQUIRRELVM vm)
Get the pointer as set by SetGlobalPointer.
Definition squirrel.hpp:237
Squirrel::GetRealInstance
static SQUserPointer GetRealInstance(HSQUIRRELVM vm, int index, std::string_view tag)
Get the real-instance pointer.
Definition squirrel.cpp:493
Squirrel::AddConst
void AddConst(std::string_view var_name, SQInteger value)
Adds a const to the stack.
Definition squirrel.cpp:273
Squirrel::global_pointer
void * global_pointer
Can be set by who ever initializes Squirrel.
Definition squirrel.hpp:32
Squirrel::SetPrintFunction
void SetPrintFunction(SQPrintFunc *func)
Set a custom print function, so you can handle outputs from SQ yourself.
Definition squirrel.hpp:242
Squirrel::CollectGarbage
void CollectGarbage()
Tell the VM to do a garbage collection run.
Definition squirrel.cpp:370
Squirrel::vm
HSQUIRRELVM vm
The VirtualMachine instance for squirrel.
Definition squirrel.hpp:31
Squirrel::Reset
void Reset()
Completely reset the engine; start from scratch.
Definition squirrel.cpp:741
Squirrel::GetOpsTillSuspend
SQInteger GetOpsTillSuspend()
How many operations can we execute till suspension?
Definition squirrel.cpp:795
Squirrel::LoadScript
bool LoadScript(const std::string &script)
Load a script.
Definition squirrel.cpp:713
Squirrel::IsSuspended
bool IsSuspended()
Did the squirrel code suspend or return normally.
Definition squirrel.cpp:774
Squirrel::ReleaseObject
void ReleaseObject(HSQOBJECT *ptr)
Release a SQ object.
Definition squirrel.hpp:252
Squirrel::CanSuspend
bool CanSuspend()
Are we allowed to suspend the squirrel script at this moment?
Definition squirrel.cpp:789
Squirrel::api_name
std::string_view api_name
Name of the API used for this squirrel.
Definition squirrel.hpp:36
Squirrel::print_func
SQPrintFunc * print_func
Points to either nullptr, or a custom print handler.
Definition squirrel.hpp:33
Squirrel::AddClassBegin
void AddClassBegin(std::string_view class_name)
Adds a class to the global scope.
Definition squirrel.cpp:291
Squirrel::ThrowError
void ThrowError(std::string_view error)
Throw a Squirrel error that will be nicely displayed to the user.
Definition squirrel.hpp:247
Squirrel::_RunError
static SQInteger _RunError(HSQUIRRELVM vm)
The internal RunError handler.
Definition squirrel.cpp:230
Squirrel::GetAllocatedMemory
size_t GetAllocatedMemory() const noexcept
Get number of bytes allocated by this VM.
Definition squirrel.cpp:175
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:232
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:769
Squirrel::HasScriptCrashed
bool HasScriptCrashed()
Find out if the squirrel script made an error before.
Definition squirrel.cpp:779
Squirrel::CrashOccurred
void CrashOccurred()
Set the script status to crashed.
Definition squirrel.cpp:784
Squirrel::LoadFile
SQRESULT LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool printerror)
Load a file to a given VM.
Definition squirrel.cpp:622
Squirrel::GetVM
HSQUIRRELVM GetVM()
Get the squirrel VM.
Definition squirrel.hpp:82
Squirrel::CompileError
static void CompileError(HSQUIRRELVM vm, std::string_view desc, std::string_view source, SQInteger line, SQInteger column)
The CompileError handler.
Definition squirrel.cpp:182
Squirrel::GetInstance
static bool GetInstance(HSQUIRRELVM vm, HSQOBJECT *ptr, int pos=1)
Get the Squirrel-instance pointer.
Definition squirrel.hpp:211
Squirrel::RunError
static void RunError(HSQUIRRELVM vm, std::string_view error)
The RunError handler.
Definition squirrel.cpp:208
Squirrel::Initialize
void Initialize()
Perform all initialization steps to create the engine.
Definition squirrel.cpp:516
Squirrel::crashed
bool crashed
True if the squirrel script made an error.
Definition squirrel.hpp:34
Squirrel::PrintFunc
static void PrintFunc(HSQUIRRELVM vm, std::string_view s)
If a user runs 'print' inside a script, this function gets the params.
Definition squirrel.cpp:245
Squirrel::ObjectToBool
static bool ObjectToBool(HSQOBJECT *ptr)
Convert a Squirrel-object to a bool.
Definition squirrel.hpp:226
Squirrel::overdrawn_ops
int overdrawn_ops
The amount of operations we have overdrawn.
Definition squirrel.hpp:35
Squirrel::ObjectToString
static std::optional< std::string_view > ObjectToString(HSQOBJECT *ptr)
Convert a Squirrel-object to a string.
Definition squirrel.hpp:216
Squirrel::Uninitialize
void Uninitialize()
Perform all the cleanups for the engine.
Definition squirrel.cpp:723
Squirrel::GetAPIName
std::string_view GetAPIName()
Get the API name.
Definition squirrel.hpp:47
Squirrel::AddMethod
void AddMethod(std::string_view method_name, SQFUNCTION proc, std::string_view params={}, void *userdata=nullptr, int size=0)
Adds a function to the stack.
Definition squirrel.cpp:256
Squirrel::CallMethod
bool CallMethod(HSQOBJECT instance, std::string_view method_name, HSQOBJECT *ret, int suspend)
Call a method of an instance, in various flavors.
Definition squirrel.cpp:376
Squirrel::AddConst
void AddConst(std::string_view var_name, uint value)
Adds a const to the stack.
Definition squirrel.hpp:113
Squirrel::MethodExists
bool MethodExists(HSQOBJECT instance, std::string_view method_name)
Check if a method exists in an instance.
Definition squirrel.cpp:323
Squirrel::ResumeError
void ResumeError()
Resume the VM with an error so it prints a stack trace.
Definition squirrel.cpp:363
Squirrel::CreateClassInstanceVM
static bool CreateClassInstanceVM(HSQUIRRELVM vm, const std::string &class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name=false)
Creates a class instance.
Definition squirrel.cpp:440
Squirrel::CreateClassInstance
bool CreateClassInstance(const std::string &class_name, void *real_instance, HSQOBJECT *instance)
Exactly the same as CreateClassInstanceVM, only callable without instance of Squirrel.
Definition squirrel.cpp:487
Squirrel::ErrorPrintFunc
static void ErrorPrintFunc(HSQUIRRELVM vm, std::string_view s)
If an error has to be print, this function is called.
Definition squirrel.cpp:197
Squirrel::AddConst
void AddConst(std::string_view var_name, int value)
Adds a const to the stack.
Definition squirrel.hpp:119
Squirrel::ObjectToInteger
static int ObjectToInteger(HSQOBJECT *ptr)
Convert a Squirrel-object to an integer.
Definition squirrel.hpp:221
Squirrel::allocator
std::unique_ptr< ScriptAllocator > allocator
Allocator object used by this script.
Definition squirrel.hpp:37
ConvertibleThroughBase
A type is considered 'convertible through base()' when it has a 'base()' function that returns someth...
Definition convertible_through_base.hpp:19
ScriptType
ScriptType
The type of script we're working with, i.e.
Definition squirrel.hpp:17
ScriptType::AI
@ AI
The script is for AI scripts.
ScriptType::GS
@ GS
The script is for Game scripts.
ScriptAllocator
Definition squirrel.cpp:32