OpenTTD Source 20260311-master-g511d3794ce
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
9
10#ifndef SQUIRREL_HPP
11#define SQUIRREL_HPP
12
13#include <squirrel.h>
15
17enum class ScriptType : uint8_t {
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
44 static SQInteger _RunError(HSQUIRRELVM vm);
45
50 std::string_view GetAPIName() { return this->api_name; }
51
53 void Initialize();
55 void Uninitialize();
56
57protected:
66 static void CompileError(HSQUIRRELVM vm, std::string_view desc, std::string_view source, SQInteger line, SQInteger column);
67
73 static void RunError(HSQUIRRELVM vm, std::string_view error);
74
80 static void PrintFunc(HSQUIRRELVM vm, std::string_view s);
81
87 static void ErrorPrintFunc(HSQUIRRELVM vm, std::string_view s);
88
89public:
90 Squirrel(std::string_view api_name);
91 ~Squirrel();
92
97 HSQUIRRELVM GetVM() { return this->vm; }
98
104 bool LoadScript(const std::string &script);
105 bool LoadScript(HSQUIRRELVM vm, const std::string &script, bool in_root = true);
106
114 SQRESULT LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool printerror);
115
126 void AddMethod(std::string_view method_name, SQFUNCTION proc, std::string_view params = {}, void *userdata = nullptr, int size = 0, bool suspendable = false);
127
134 void AddConst(std::string_view var_name, SQInteger value);
135
142 void AddConst(std::string_view var_name, uint value) { this->AddConst(var_name, (SQInteger)value); }
143
150 void AddConst(std::string_view var_name, int value) { this->AddConst(var_name, (SQInteger)value); }
151
158 void AddConst(std::string_view var_name, const ConvertibleThroughBase auto &value) { this->AddConst(var_name, static_cast<SQInteger>(value.base())); }
159
166 void AddConst(std::string_view var_name, bool value);
167
173 void AddClassBegin(std::string_view class_name);
174
181 void AddClassBegin(std::string_view class_name, std::string_view parent_class);
182
187 void AddClassEnd();
188
194 bool Resume(int suspend = -1);
195
199 void ResumeError();
200
204 void CollectGarbage();
205
206 void InsertResult(bool result);
207 void InsertResult(int result);
208 void InsertResult(uint result) { this->InsertResult((int)result); }
209 void InsertResult(ConvertibleThroughBase auto result) { this->InsertResult(static_cast<int>(result.base())); }
210
219 bool CallMethod(HSQOBJECT instance, std::string_view method_name, HSQOBJECT *ret, int suspend);
220
228 bool CallMethod(HSQOBJECT instance, std::string_view method_name, int suspend) { return this->CallMethod(instance, method_name, nullptr, suspend); }
229
238 bool CallStringMethod(HSQOBJECT instance, std::string_view method_name, std::string *res, int suspend);
239
248 bool CallIntegerMethod(HSQOBJECT instance, std::string_view method_name, int *res, int suspend);
249
258 bool CallBoolMethod(HSQOBJECT instance, std::string_view method_name, bool *res, int suspend);
259
266 bool MethodExists(HSQOBJECT instance, std::string_view method_name);
267
278 static bool CreateClassInstanceVM(HSQUIRRELVM vm, const std::string &class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name = false);
279
287 bool CreateClassInstance(const std::string &class_name, void *real_instance, HSQOBJECT *instance);
288
298 static SQUserPointer GetRealInstance(HSQUIRRELVM vm, int index, std::string_view tag);
299
308 static void GetInstance(HSQUIRRELVM vm, HSQOBJECT *ptr, int pos = 1) { sq_getclass(vm, pos); sq_getstackobj(vm, pos, ptr); sq_pop(vm, 1); }
309
315 static std::optional<std::string_view> ObjectToString(HSQOBJECT *ptr) { return sq_objtostring(ptr); }
316
322 static int ObjectToInteger(HSQOBJECT *ptr) { return sq_objtointeger(ptr); }
323
329 static bool ObjectToBool(HSQOBJECT *ptr) { return sq_objtobool(ptr) == 1; }
330
336 void SetGlobalPointer(void *ptr) { this->global_pointer = ptr; }
337
343 static void *GetGlobalPointer(HSQUIRRELVM vm) { return ((Squirrel *)sq_getforeignptr(vm))->global_pointer; }
344
349 void SetPrintFunction(SQPrintFunc *func) { this->print_func = func; }
350
355 void ThrowError(std::string_view error) { sq_throwerror(this->vm, error); }
356
361 void ReleaseObject(HSQOBJECT *ptr) { sq_release(this->vm, ptr); }
362
368 static void DecreaseOps(HSQUIRRELVM vm, int amount);
369
374 bool IsSuspended();
375
380 bool HasScriptCrashed();
381
385 void CrashOccurred();
386
391 bool CanSuspend();
392
397 SQInteger GetOpsTillSuspend();
398
402 void Reset();
403
408 size_t GetAllocatedMemory() const noexcept;
409
414 static void IncreaseAllocatedSize(size_t bytes);
415
420 static void DecreaseAllocatedSize(size_t bytes);
421};
422
423
424extern ScriptAllocator *_squirrel_allocator;
425
426class ScriptAllocatorScope {
427 ScriptAllocator *old_allocator;
428
429public:
430 ScriptAllocatorScope(const Squirrel *engine)
431 {
432 this->old_allocator = _squirrel_allocator;
433 /* This may get called with a nullptr engine, in case of a crashed script */
434 _squirrel_allocator = engine != nullptr ? engine->allocator.get() : nullptr;
435 }
436
439 {
440 _squirrel_allocator = this->old_allocator;
441 }
442};
443
444#endif /* SQUIRREL_HPP */
Main AI class.
Definition ai.hpp:19
~ScriptAllocatorScope()
Restore the previous allocator.
Definition squirrel.hpp:438
void AddClassEnd()
Finishes adding a class to the global scope.
Definition squirrel.cpp:336
bool Resume(int suspend=-1)
Resume a VM when it was suspended via a throw.
Definition squirrel.cpp:362
static void GetInstance(HSQUIRRELVM vm, HSQOBJECT *ptr, int pos=1)
Get the Squirrel-instance pointer.
Definition squirrel.hpp:308
static void * GetGlobalPointer(HSQUIRRELVM vm)
Get the pointer as set by SetGlobalPointer.
Definition squirrel.hpp:343
static SQUserPointer GetRealInstance(HSQUIRRELVM vm, int index, std::string_view tag)
Get the real-instance pointer.
Definition squirrel.cpp:514
void AddConst(std::string_view var_name, SQInteger value)
Adds a const to the stack.
Definition squirrel.cpp:294
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:349
bool CallIntegerMethod(HSQOBJECT instance, std::string_view method_name, int *res, int suspend)
Call a method of an instance returning a integer.
Definition squirrel.cpp:443
void CollectGarbage()
Tell the VM to do a garbage collection run.
Definition squirrel.cpp:391
HSQUIRRELVM vm
The VirtualMachine instance for squirrel.
Definition squirrel.hpp:31
void AddMethod(std::string_view method_name, SQFUNCTION proc, std::string_view params={}, void *userdata=nullptr, int size=0, bool suspendable=false)
Adds a function to the stack.
Definition squirrel.cpp:259
void Reset()
Completely reset the engine; start from scratch.
Definition squirrel.cpp:763
SQInteger GetOpsTillSuspend()
How many operations can we execute till suspension?
Definition squirrel.cpp:817
bool LoadScript(const std::string &script)
Load a script.
Definition squirrel.cpp:734
bool IsSuspended()
Did the squirrel code suspend or return normally.
Definition squirrel.cpp:796
void ReleaseObject(HSQOBJECT *ptr)
Release a SQ object.
Definition squirrel.hpp:361
bool CanSuspend()
Are we allowed to suspend the squirrel script at this moment?
Definition squirrel.cpp:811
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 AddConst(std::string_view var_name, const ConvertibleThroughBase auto &value)
Adds a const to the stack.
Definition squirrel.hpp:158
~Squirrel()
Clean up the Squirrel virtual machine state.
Definition squirrel.cpp:740
static void DecreaseAllocatedSize(size_t bytes)
Decrease number of bytes allocated in the current script allocator scope.
Definition squirrel.cpp:828
void AddClassBegin(std::string_view class_name)
Adds a class to the global scope.
Definition squirrel.cpp:312
void ThrowError(std::string_view error)
Throw a Squirrel error that will be nicely displayed to the user.
Definition squirrel.hpp:355
static SQInteger _RunError(HSQUIRRELVM vm)
The internal RunError handler.
Definition squirrel.cpp:233
size_t GetAllocatedMemory() const noexcept
Get number of bytes allocated by this VM.
Definition squirrel.cpp:178
void SetGlobalPointer(void *ptr)
Sets a pointer in the VM that is reachable from where ever you are in SQ.
Definition squirrel.hpp:336
static void DecreaseOps(HSQUIRRELVM vm, int amount)
Tell the VM to remove amount ops from the number of ops till suspend.
Definition squirrel.cpp:791
bool HasScriptCrashed()
Find out if the squirrel script made an error before.
Definition squirrel.cpp:801
bool CallBoolMethod(HSQOBJECT instance, std::string_view method_name, bool *res, int suspend)
Call a method of an instance returning a boolean.
Definition squirrel.cpp:452
void CrashOccurred()
Set the script status to crashed.
Definition squirrel.cpp:806
SQRESULT LoadFile(HSQUIRRELVM vm, const std::string &filename, SQBool printerror)
Load a file to a given VM.
Definition squirrel.cpp:643
HSQUIRRELVM GetVM()
Get the squirrel VM.
Definition squirrel.hpp:97
static void CompileError(HSQUIRRELVM vm, std::string_view desc, std::string_view source, SQInteger line, SQInteger column)
The CompileError handler.
Definition squirrel.cpp:185
static void IncreaseAllocatedSize(size_t bytes)
Increase number of bytes allocated in the current script allocator scope.
Definition squirrel.cpp:822
static void RunError(HSQUIRRELVM vm, std::string_view error)
The RunError handler.
Definition squirrel.cpp:211
void Initialize()
Perform all initialization steps to create the engine.
Definition squirrel.cpp:537
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:248
static bool ObjectToBool(HSQOBJECT *ptr)
Convert a Squirrel-object to a bool.
Definition squirrel.hpp:329
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:315
void Uninitialize()
Perform all the cleanups for the engine.
Definition squirrel.cpp:745
std::string_view GetAPIName()
Get the API name.
Definition squirrel.hpp:50
bool CallMethod(HSQOBJECT instance, std::string_view method_name, int suspend)
Call a method of an instance returning nothing.
Definition squirrel.hpp:228
bool CallMethod(HSQOBJECT instance, std::string_view method_name, HSQOBJECT *ret, int suspend)
Call a method of an instance returning a Squirrel object.
Definition squirrel.cpp:397
void AddConst(std::string_view var_name, uint value)
Adds a const to the stack.
Definition squirrel.hpp:142
bool MethodExists(HSQOBJECT instance, std::string_view method_name)
Check if a method exists in an instance.
Definition squirrel.cpp:344
void ResumeError()
Resume the VM with an error so it prints a stack trace.
Definition squirrel.cpp:384
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:461
bool CreateClassInstance(const std::string &class_name, void *real_instance, HSQOBJECT *instance)
Create a class instance.
Definition squirrel.cpp:508
static void ErrorPrintFunc(HSQUIRRELVM vm, std::string_view s)
If an error has to be print, this function is called.
Definition squirrel.cpp:200
void AddConst(std::string_view var_name, int value)
Adds a const to the stack.
Definition squirrel.hpp:150
bool CallStringMethod(HSQOBJECT instance, std::string_view method_name, std::string *res, int suspend)
Call a method of an instance returning a string.
Definition squirrel.cpp:431
static int ObjectToInteger(HSQOBJECT *ptr)
Convert a Squirrel-object to an integer.
Definition squirrel.hpp:322
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...
Concept for unifying the convert through 'base()' behaviour of several 'strong' types.
ScriptType
The type of script we're working with, i.e.
Definition squirrel.hpp:17
@ GS
The script is for Game scripts.
Definition squirrel.hpp:19