OpenTTD Source 20250521-master-g82876c25e0
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 <http://www.gnu.org/licenses/>.
6 */
7
10#ifndef SQUIRREL_HPP
11#define SQUIRREL_HPP
12
13#include <squirrel.h>
14#include "../core/convertible_through_base.hpp"
15
17enum class ScriptType : uint8_t {
18 AI,
19 GS,
20};
21
22struct ScriptAllocator;
23
24class 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;
33 SQPrintFunc *print_func;
34 bool crashed;
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, int value);
108
113 void AddConst(std::string_view var_name, uint value) { this->AddConst(var_name, (int)value); }
114
115 void AddConst(std::string_view var_name, const ConvertibleThroughBase auto &value) { this->AddConst(var_name, static_cast<int>(value.base())); }
116
121 void AddConst(std::string_view var_name, bool value);
122
127 void AddClassBegin(std::string_view class_name);
128
133 void AddClassBegin(std::string_view class_name, std::string_view parent_class);
134
139 void AddClassEnd();
140
144 bool Resume(int suspend = -1);
145
149 void ResumeError();
150
154 void CollectGarbage();
155
156 void InsertResult(bool result);
157 void InsertResult(int result);
158 void InsertResult(uint result) { this->InsertResult((int)result); }
159 void InsertResult(ConvertibleThroughBase auto result) { this->InsertResult(static_cast<int>(result.base())); }
160
165 bool CallMethod(HSQOBJECT instance, std::string_view method_name, HSQOBJECT *ret, int suspend);
166 bool CallMethod(HSQOBJECT instance, std::string_view method_name, int suspend) { return this->CallMethod(instance, method_name, nullptr, suspend); }
167 bool CallStringMethod(HSQOBJECT instance, std::string_view method_name, std::string *res, int suspend);
168 bool CallIntegerMethod(HSQOBJECT instance, std::string_view method_name, int *res, int suspend);
169 bool CallBoolMethod(HSQOBJECT instance, std::string_view method_name, bool *res, int suspend);
170
174 bool MethodExists(HSQOBJECT instance, std::string_view method_name);
175
186 static bool CreateClassInstanceVM(HSQUIRRELVM vm, const std::string &class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name = false);
187
191 bool CreateClassInstance(const std::string &class_name, void *real_instance, HSQOBJECT *instance);
192
198 static SQUserPointer GetRealInstance(HSQUIRRELVM vm, int index, std::string_view tag);
199
205 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; }
206
210 static std::optional<std::string_view> ObjectToString(HSQOBJECT *ptr) { return sq_objtostring(ptr); }
211
215 static int ObjectToInteger(HSQOBJECT *ptr) { return sq_objtointeger(ptr); }
216
220 static bool ObjectToBool(HSQOBJECT *ptr) { return sq_objtobool(ptr) == 1; }
221
226 void SetGlobalPointer(void *ptr) { this->global_pointer = ptr; }
227
231 static void *GetGlobalPointer(HSQUIRRELVM vm) { return ((Squirrel *)sq_getforeignptr(vm))->global_pointer; }
232
236 void SetPrintFunction(SQPrintFunc *func) { this->print_func = func; }
237
241 void ThrowError(std::string_view error) { sq_throwerror(this->vm, error); }
242
246 void ReleaseObject(HSQOBJECT *ptr) { sq_release(this->vm, ptr); }
247
251 static void DecreaseOps(HSQUIRRELVM vm, int amount);
252
257 bool IsSuspended();
258
262 bool HasScriptCrashed();
263
267 void CrashOccurred();
268
272 bool CanSuspend();
273
277 SQInteger GetOpsTillSuspend();
278
282 void Reset();
283
287 size_t GetAllocatedMemory() const noexcept;
288};
289
290
291extern ScriptAllocator *_squirrel_allocator;
292
294 ScriptAllocator *old_allocator;
295
296public:
297 ScriptAllocatorScope(const Squirrel *engine)
298 {
299 this->old_allocator = _squirrel_allocator;
300 /* This may get called with a nullptr engine, in case of a crashed script */
301 _squirrel_allocator = engine != nullptr ? engine->allocator.get() : nullptr;
302 }
303
305 {
306 _squirrel_allocator = this->old_allocator;
307 }
308};
309
310#endif /* SQUIRREL_HPP */
Runtime information about a script like a pointer to the squirrel vm and the current state.
void AddClassEnd()
Finishes adding a class to the global scope.
Definition squirrel.cpp:315
bool Resume(int suspend=-1)
Resume a VM when it was suspended via a throw.
Definition squirrel.cpp:341
static void * GetGlobalPointer(HSQUIRRELVM vm)
Get the pointer as set by SetGlobalPointer.
Definition squirrel.hpp:231
static SQUserPointer GetRealInstance(HSQUIRRELVM vm, int index, std::string_view tag)
Get the real-instance pointer.
Definition squirrel.cpp:493
void * global_pointer
Can be set by who ever initializes Squirrel.
Definition squirrel.hpp:32
void SetPrintFunction(SQPrintFunc *func)
Set a custom print function, so you can handle outputs from SQ yourself.
Definition squirrel.hpp:236
void CollectGarbage()
Tell the VM to do a garbage collection run.
Definition squirrel.cpp:370
HSQUIRRELVM vm
The VirtualMachine instance for squirrel.
Definition squirrel.hpp:31
void Reset()
Completely reset the engine; start from scratch.
Definition squirrel.cpp:741
SQInteger GetOpsTillSuspend()
How many operations can we execute till suspension?
Definition squirrel.cpp:795
bool LoadScript(const std::string &script)
Load a script.
Definition squirrel.cpp:713
bool IsSuspended()
Did the squirrel code suspend or return normally.
Definition squirrel.cpp:774
void ReleaseObject(HSQOBJECT *ptr)
Release a SQ object.
Definition squirrel.hpp:246
bool CanSuspend()
Are we allowed to suspend the squirrel script at this moment?
Definition squirrel.cpp:789
std::string_view api_name
Name of the API used for this squirrel.
Definition squirrel.hpp:36
SQPrintFunc * print_func
Points to either nullptr, or a custom print handler.
Definition squirrel.hpp:33
void AddClassBegin(std::string_view class_name)
Adds a class to the global scope.
Definition squirrel.cpp:291
void ThrowError(std::string_view error)
Throw a Squirrel error that will be nicely displayed to the user.
Definition squirrel.hpp:241
static SQInteger _RunError(HSQUIRRELVM vm)
The internal RunError handler.
Definition squirrel.cpp:230
size_t GetAllocatedMemory() const noexcept
Get number of bytes allocated by this VM.
Definition squirrel.cpp:175
void SetGlobalPointer(void *ptr)
Sets a pointer in the VM that is reachable from where ever you are in SQ.
Definition squirrel.hpp:226
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
bool HasScriptCrashed()
Find out if the squirrel script made an error before.
Definition squirrel.cpp:779
void CrashOccurred()
Set the script status to crashed.
Definition squirrel.cpp:784
SQRESULT LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool printerror)
Load a file to a given VM.
Definition squirrel.cpp:622
HSQUIRRELVM GetVM()
Get the squirrel VM.
Definition squirrel.hpp:82
static void CompileError(HSQUIRRELVM vm, std::string_view desc, std::string_view source, SQInteger line, SQInteger column)
The CompileError handler.
Definition squirrel.cpp:182
static bool GetInstance(HSQUIRRELVM vm, HSQOBJECT *ptr, int pos=1)
Get the Squirrel-instance pointer.
Definition squirrel.hpp:205
static void RunError(HSQUIRRELVM vm, std::string_view error)
The RunError handler.
Definition squirrel.cpp:208
void Initialize()
Perform all initialization steps to create the engine.
Definition squirrel.cpp:516
bool crashed
True if the squirrel script made an error.
Definition squirrel.hpp:34
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
static bool ObjectToBool(HSQOBJECT *ptr)
Convert a Squirrel-object to a bool.
Definition squirrel.hpp:220
int overdrawn_ops
The amount of operations we have overdrawn.
Definition squirrel.hpp:35
static std::optional< std::string_view > ObjectToString(HSQOBJECT *ptr)
Convert a Squirrel-object to a string.
Definition squirrel.hpp:210
void Uninitialize()
Perform all the cleanups for the engine.
Definition squirrel.cpp:723
std::string_view GetAPIName()
Get the API name.
Definition squirrel.hpp:47
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
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
void AddConst(std::string_view var_name, uint value)
Adds a const to the stack.
Definition squirrel.hpp:113
bool MethodExists(HSQOBJECT instance, std::string_view method_name)
Check if a method exists in an instance.
Definition squirrel.cpp:323
void ResumeError()
Resume the VM with an error so it prints a stack trace.
Definition squirrel.cpp:363
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
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
static void ErrorPrintFunc(HSQUIRRELVM vm, std::string_view s)
If an error has to be print, this function is called.
Definition squirrel.cpp:197
void AddConst(std::string_view var_name, int value)
Adds a const to the stack.
Definition squirrel.cpp:273
static int ObjectToInteger(HSQOBJECT *ptr)
Convert a Squirrel-object to an integer.
Definition squirrel.hpp:215
std::unique_ptr< ScriptAllocator > allocator
Allocator object used by this script.
Definition squirrel.hpp:37
A type is considered 'convertible through base()' when it has a 'base()' function that returns someth...
ScriptType
The type of script we're working with, i.e.
Definition squirrel.hpp:17
@ AI
The script is for AI scripts.
@ GS
The script is for Game scripts.