1
0
mirror of https://github.com/VCMP-SqMod/SqMod.git synced 2025-06-16 07:07:13 +02:00

Major plugin refactor and cleanup.

Switched to POCO library for unified platform/library interface.
Deprecated the external module API. It was creating more problems than solving.
Removed most built-in libraries in favor of system libraries for easier maintenance.
Cleaned and secured code with help from static analyzers.
This commit is contained in:
Sandu Liviu Catalin
2021-01-30 08:51:39 +02:00
parent e0e34b4030
commit 4a6bfc086c
6219 changed files with 1209835 additions and 454916 deletions

View File

@ -4,7 +4,7 @@
// ------------------------------------------------------------------------------------------------
#include "Entity/Blip.hpp"
#include "Entity/Checkpoint.hpp"
#include "Entity/Keybind.hpp"
#include "Entity/KeyBind.hpp"
#include "Entity/Object.hpp"
#include "Entity/Pickup.hpp"
#include "Entity/Player.hpp"
@ -53,7 +53,7 @@ struct FakeString
/* --------------------------------------------------------------------------------------------
* Retrieve the size of the name.
*/
std::size_t size() const
SQMOD_NODISCARD std::size_t size() const
{
return mSize;
}
@ -61,7 +61,7 @@ struct FakeString
/* --------------------------------------------------------------------------------------------
* Retrieve the string buffer.
*/
CSStr c_str() const
SQMOD_NODISCARD const SQChar * c_str() const
{
return mBuffer;
}
@ -69,16 +69,16 @@ struct FakeString
/* --------------------------------------------------------------------------------------------
* Find in buffer contents of another string.
*/
std::size_t find(CSStr s) const
std::size_t find(const SQChar * s) const
{
CCStr r = std::strstr(mBuffer, s);
const char * r = std::strstr(mBuffer, s);
return (r == nullptr) ? String::npos : (r - mBuffer);
}
/* --------------------------------------------------------------------------------------------
* Compare the buffer contents with another string.
*/
int compare(CSStr s) const
int compare(const SQChar * s) const
{
return std::strcmp(mBuffer, s);
}
@ -86,7 +86,7 @@ struct FakeString
/* --------------------------------------------------------------------------------------------
* Compare the buffer contents with another string.
*/
int compare(std::size_t pos, std::size_t len, CSStr s) const
int compare(std::size_t pos, std::size_t len, const SQChar * s) const
{
return std::strncmp(mBuffer + pos, s, len);
}
@ -111,12 +111,12 @@ struct PlayerName
};
// ------------------------------------------------------------------------------------------------
static const LightObj & Blip_FindBySprID(Int32 sprid)
static const LightObj & Blip_FindBySprID(int32_t spr_id)
{
// Perform a range check on the specified identifier
if (sprid < 0)
if (spr_id < 0)
{
STHROWF("The specified sprite identifier is invalid: %d", sprid);
STHROWF("The specified sprite identifier is invalid: %d", spr_id);
}
// Obtain the ends of the entity pool
auto itr = Core::Get().GetBlips().cbegin();
@ -125,7 +125,7 @@ static const LightObj & Blip_FindBySprID(Int32 sprid)
for (; itr != end; ++itr)
{
// Does the identifier match the specified one?
if (itr->mSprID == sprid)
if (itr->mSprID == spr_id)
{
return itr->mObj; // Stop searching and return this entity
}
@ -137,7 +137,7 @@ static const LightObj & Blip_FindBySprID(Int32 sprid)
/* ------------------------------------------------------------------------------------------------
* Collect all players where the name matches or not the specified one.
*/
static inline Array Player_AllWhereNameEquals(bool neg, bool cs, CSStr name)
static inline Array Player_AllWhereNameEquals(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Remember the current stack size
@ -155,7 +155,7 @@ static inline Array Player_AllWhereNameEquals(bool neg, bool cs, CSStr name)
/* ------------------------------------------------------------------------------------------------
* Collect all players where the name begins or not with the specified string.
*/
static inline Array Player_AllWhereNameBegins(bool neg, bool cs, CSStr name)
static inline Array Player_AllWhereNameBegins(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Remember the current stack size
@ -173,7 +173,7 @@ static inline Array Player_AllWhereNameBegins(bool neg, bool cs, CSStr name)
/* ------------------------------------------------------------------------------------------------
* Collect all players where the name ends or not with the specified string.
*/
static inline Array Player_AllWhereNameEnds(bool neg, bool cs, CSStr name)
static inline Array Player_AllWhereNameEnds(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Remember the current stack size
@ -191,7 +191,7 @@ static inline Array Player_AllWhereNameEnds(bool neg, bool cs, CSStr name)
/* ------------------------------------------------------------------------------------------------
* Collect all players where the name contains or not the specified string.
*/
static inline Array Player_AllWhereNameContains(bool neg, bool cs, CSStr name)
static inline Array Player_AllWhereNameContains(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Remember the current stack size
@ -209,7 +209,7 @@ static inline Array Player_AllWhereNameContains(bool neg, bool cs, CSStr name)
/* ------------------------------------------------------------------------------------------------
* Collect all players where the name matches or not the specified filter.
*/
static inline Array Player_AllWhereNameMatches(bool neg, bool cs, CSStr name)
static inline Array Player_AllWhereNameMatches(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Remember the current stack size
@ -227,7 +227,7 @@ static inline Array Player_AllWhereNameMatches(bool neg, bool cs, CSStr name)
/* ------------------------------------------------------------------------------------------------
* Retrieve the first player where the name matches or not the specified one.
*/
static inline LightObj Player_FirstWhereNameEquals(bool neg, bool cs, CSStr name)
static inline LightObj Player_FirstWhereNameEquals(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element receiver
@ -243,7 +243,7 @@ static inline LightObj Player_FirstWhereNameEquals(bool neg, bool cs, CSStr name
/* ------------------------------------------------------------------------------------------------
* Retrieve the first player where the name begins or not with the specified string.
*/
static inline LightObj Player_FirstWhereNameBegins(bool neg, bool cs, CSStr name)
static inline LightObj Player_FirstWhereNameBegins(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element receiver
@ -259,7 +259,7 @@ static inline LightObj Player_FirstWhereNameBegins(bool neg, bool cs, CSStr name
/* ------------------------------------------------------------------------------------------------
* Retrieve the first player where the name ends or not with the specified string.
*/
static inline LightObj Player_FirstWhereNameEnds(bool neg, bool cs, CSStr name)
static inline LightObj Player_FirstWhereNameEnds(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element receiver
@ -275,7 +275,7 @@ static inline LightObj Player_FirstWhereNameEnds(bool neg, bool cs, CSStr name)
/* ------------------------------------------------------------------------------------------------
* Retrieve the first player where the name contains or not the specified string.
*/
static inline LightObj Player_FirstWhereNameContains(bool neg, bool cs, CSStr name)
static inline LightObj Player_FirstWhereNameContains(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element receiver
@ -291,7 +291,7 @@ static inline LightObj Player_FirstWhereNameContains(bool neg, bool cs, CSStr na
/* ------------------------------------------------------------------------------------------------
* Retrieve the first player where the name matches or not the specified filter.
*/
static inline LightObj Player_FirstWhereNameMatches(bool neg, bool cs, CSStr name)
static inline LightObj Player_FirstWhereNameMatches(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element receiver
@ -307,7 +307,7 @@ static inline LightObj Player_FirstWhereNameMatches(bool neg, bool cs, CSStr nam
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name matches or not the specified one.
*/
static inline Uint32 Player_EachWhereNameEquals(bool neg, bool cs, CSStr name, Function & func)
static inline uint32_t Player_EachWhereNameEquals(bool neg, bool cs, const SQChar * name, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -323,7 +323,7 @@ static inline Uint32 Player_EachWhereNameEquals(bool neg, bool cs, CSStr name, F
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name matches or not the specified one.
*/
static inline Uint32 Player_EachWhereNameEqualsData(bool neg, bool cs, CSStr name, LightObj & data, Function & func)
static inline uint32_t Player_EachWhereNameEqualsData(bool neg, bool cs, const SQChar * name, LightObj & data, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -339,7 +339,7 @@ static inline Uint32 Player_EachWhereNameEqualsData(bool neg, bool cs, CSStr nam
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name begins with the specified string.
*/
static inline Uint32 Player_EachWhereNameBegins(bool neg, bool cs, CSStr name, Function & func)
static inline uint32_t Player_EachWhereNameBegins(bool neg, bool cs, const SQChar * name, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -355,7 +355,7 @@ static inline Uint32 Player_EachWhereNameBegins(bool neg, bool cs, CSStr name, F
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name begins with the specified string.
*/
static inline Uint32 Player_EachWhereNameBeginsData(bool neg, bool cs, CSStr name, LightObj & data, Function & func)
static inline uint32_t Player_EachWhereNameBeginsData(bool neg, bool cs, const SQChar * name, LightObj & data, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -371,7 +371,7 @@ static inline Uint32 Player_EachWhereNameBeginsData(bool neg, bool cs, CSStr nam
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name ends or not with the specified string.
*/
static inline Uint32 Player_EachWhereNameEnds(bool neg, bool cs, CSStr name, Function & func)
static inline uint32_t Player_EachWhereNameEnds(bool neg, bool cs, const SQChar * name, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -387,7 +387,7 @@ static inline Uint32 Player_EachWhereNameEnds(bool neg, bool cs, CSStr name, Fun
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name ends or not with the specified string.
*/
static inline Uint32 Player_EachWhereNameEndsData(bool neg, bool cs, CSStr name, LightObj & data, Function & func)
static inline uint32_t Player_EachWhereNameEndsData(bool neg, bool cs, const SQChar * name, LightObj & data, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -403,7 +403,7 @@ static inline Uint32 Player_EachWhereNameEndsData(bool neg, bool cs, CSStr name,
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name contains the specified string.
*/
static inline Uint32 Player_EachWhereNameContains(bool neg, bool cs, CSStr name, Function & func)
static inline uint32_t Player_EachWhereNameContains(bool neg, bool cs, const SQChar * name, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -419,7 +419,7 @@ static inline Uint32 Player_EachWhereNameContains(bool neg, bool cs, CSStr name,
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name contains the specified string.
*/
static inline Uint32 Player_EachWhereNameContainsData(bool neg, bool cs, CSStr name, LightObj & data, Function & func)
static inline uint32_t Player_EachWhereNameContainsData(bool neg, bool cs, const SQChar * name, LightObj & data, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -435,7 +435,7 @@ static inline Uint32 Player_EachWhereNameContainsData(bool neg, bool cs, CSStr n
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name matches the specified filter.
*/
static inline Uint32 Player_EachWhereNameMatches(bool neg, bool cs, CSStr name, Function & func)
static inline uint32_t Player_EachWhereNameMatches(bool neg, bool cs, const SQChar * name, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -451,7 +451,7 @@ static inline Uint32 Player_EachWhereNameMatches(bool neg, bool cs, CSStr name,
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the name matches the specified filter.
*/
static inline Uint32 Player_EachWhereNameMatchesData(bool neg, bool cs, CSStr name, LightObj & data, Function & func)
static inline uint32_t Player_EachWhereNameMatchesData(bool neg, bool cs, const SQChar * name, LightObj & data, Function & func)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element forwarder
@ -467,7 +467,7 @@ static inline Uint32 Player_EachWhereNameMatchesData(bool neg, bool cs, CSStr na
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the name matches or not the specified one.
*/
static inline CountElemFunc <CPlayer> Player_CountWhereNameEquals(bool neg, bool cs, CSStr name)
static inline CountElemFunc <CPlayer> Player_CountWhereNameEquals(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element counter
@ -483,7 +483,7 @@ static inline CountElemFunc <CPlayer> Player_CountWhereNameEquals(bool neg, bool
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the name begins with the specified string.
*/
static inline Uint32 Player_CountWhereNameBegins(bool neg, bool cs, CSStr name)
static inline uint32_t Player_CountWhereNameBegins(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element counter
@ -499,7 +499,7 @@ static inline Uint32 Player_CountWhereNameBegins(bool neg, bool cs, CSStr name)
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the name ends or not with the specified string.
*/
static inline Uint32 Player_CountWhereNameEnds(bool neg, bool cs, CSStr name)
static inline uint32_t Player_CountWhereNameEnds(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element counter
@ -515,7 +515,7 @@ static inline Uint32 Player_CountWhereNameEnds(bool neg, bool cs, CSStr name)
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the name contains the specified string.
*/
static inline Uint32 Player_CountWhereNameContains(bool neg, bool cs, CSStr name)
static inline uint32_t Player_CountWhereNameContains(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element counter
@ -531,7 +531,7 @@ static inline Uint32 Player_CountWhereNameContains(bool neg, bool cs, CSStr name
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the name matches the specified filter.
*/
static inline Uint32 Player_CountWhereNameMatches(bool neg, bool cs, CSStr name)
static inline uint32_t Player_CountWhereNameMatches(bool neg, bool cs, const SQChar * name)
{
SQMOD_VALID_NAME_STR(name)
// Create a new element counter
@ -567,13 +567,13 @@ void Register(HSQUIRRELVM vm)
.Func(_SC("TagMatches"), &Entity< CCheckpoint >::AllWhereTagMatches)
);
collect_ns.Bind(_SC("Keybind"), Table(vm)
.Func(_SC("Active"), &Entity< CKeybind >::AllActive)
.Func(_SC("TagEquals"), &Entity< CKeybind >::AllWhereTagEquals)
.Func(_SC("TagBegins"), &Entity< CKeybind >::AllWhereTagBegins)
.Func(_SC("TagEnds"), &Entity< CKeybind >::AllWhereTagEnds)
.Func(_SC("TagContains"), &Entity< CKeybind >::AllWhereTagContains)
.Func(_SC("TagMatches"), &Entity< CKeybind >::AllWhereTagMatches)
collect_ns.Bind(_SC("KeyBind"), Table(vm)
.Func(_SC("Active"), &Entity< CKeyBind >::AllActive)
.Func(_SC("TagEquals"), &Entity< CKeyBind >::AllWhereTagEquals)
.Func(_SC("TagBegins"), &Entity< CKeyBind >::AllWhereTagBegins)
.Func(_SC("TagEnds"), &Entity< CKeyBind >::AllWhereTagEnds)
.Func(_SC("TagContains"), &Entity< CKeyBind >::AllWhereTagContains)
.Func(_SC("TagMatches"), &Entity< CKeyBind >::AllWhereTagMatches)
);
collect_ns.Bind(_SC("Object"), Table(vm)
@ -640,13 +640,13 @@ void Register(HSQUIRRELVM vm)
.Func(_SC("TagMatches"), &Entity< CCheckpoint >::FirstWhereTagMatches)
);
find_ns.Bind(_SC("Keybind"), Table(vm)
.Func(_SC("WithID"), &Entity< CKeybind >::FindByID)
.Func(_SC("TagEquals"), &Entity< CKeybind >::FirstWhereTagEquals)
.Func(_SC("TagBegins"), &Entity< CKeybind >::FirstWhereTagBegins)
.Func(_SC("TagEnds"), &Entity< CKeybind >::FirstWhereTagEnds)
.Func(_SC("TagContains"), &Entity< CKeybind >::FirstWhereTagContains)
.Func(_SC("TagMatches"), &Entity< CKeybind >::FirstWhereTagMatches)
find_ns.Bind(_SC("KeyBind"), Table(vm)
.Func(_SC("WithID"), &Entity< CKeyBind >::FindByID)
.Func(_SC("TagEquals"), &Entity< CKeyBind >::FirstWhereTagEquals)
.Func(_SC("TagBegins"), &Entity< CKeyBind >::FirstWhereTagBegins)
.Func(_SC("TagEnds"), &Entity< CKeyBind >::FirstWhereTagEnds)
.Func(_SC("TagContains"), &Entity< CKeyBind >::FirstWhereTagContains)
.Func(_SC("TagMatches"), &Entity< CKeyBind >::FirstWhereTagMatches)
);
find_ns.Bind(_SC("Object"), Table(vm)
@ -712,13 +712,13 @@ void Register(HSQUIRRELVM vm)
.Func(_SC("TagMatches"), &Entity< CCheckpoint >::EachWhereTagMatches)
);
each_ns.Bind(_SC("Keybind"), Table(vm)
.Func(_SC("Active"), &Entity< CKeybind >::EachActive)
.Func(_SC("TagEquals"), &Entity< CKeybind >::EachWhereTagEquals)
.Func(_SC("TagBegins"), &Entity< CKeybind >::EachWhereTagBegins)
.Func(_SC("TagEnds"), &Entity< CKeybind >::EachWhereTagEnds)
.Func(_SC("TagContains"), &Entity< CKeybind >::EachWhereTagContains)
.Func(_SC("TagMatches"), &Entity< CKeybind >::EachWhereTagMatches)
each_ns.Bind(_SC("KeyBind"), Table(vm)
.Func(_SC("Active"), &Entity< CKeyBind >::EachActive)
.Func(_SC("TagEquals"), &Entity< CKeyBind >::EachWhereTagEquals)
.Func(_SC("TagBegins"), &Entity< CKeyBind >::EachWhereTagBegins)
.Func(_SC("TagEnds"), &Entity< CKeyBind >::EachWhereTagEnds)
.Func(_SC("TagContains"), &Entity< CKeyBind >::EachWhereTagContains)
.Func(_SC("TagMatches"), &Entity< CKeyBind >::EachWhereTagMatches)
);
each_ns.Bind(_SC("Object"), Table(vm)
@ -784,13 +784,13 @@ void Register(HSQUIRRELVM vm)
.Func(_SC("TagMatches"), &Entity< CCheckpoint >::EachWhereTagMatchesData)
);
exeach_ns.Bind(_SC("Keybind"), Table(vm)
.Func(_SC("Active"), &Entity< CKeybind >::EachActiveData)
.Func(_SC("TagEquals"), &Entity< CKeybind >::EachWhereTagEqualsData)
.Func(_SC("TagBegins"), &Entity< CKeybind >::EachWhereTagBeginsData)
.Func(_SC("TagEnds"), &Entity< CKeybind >::EachWhereTagEndsData)
.Func(_SC("TagContains"), &Entity< CKeybind >::EachWhereTagContainsData)
.Func(_SC("TagMatches"), &Entity< CKeybind >::EachWhereTagMatchesData)
exeach_ns.Bind(_SC("KeyBind"), Table(vm)
.Func(_SC("Active"), &Entity< CKeyBind >::EachActiveData)
.Func(_SC("TagEquals"), &Entity< CKeyBind >::EachWhereTagEqualsData)
.Func(_SC("TagBegins"), &Entity< CKeyBind >::EachWhereTagBeginsData)
.Func(_SC("TagEnds"), &Entity< CKeyBind >::EachWhereTagEndsData)
.Func(_SC("TagContains"), &Entity< CKeyBind >::EachWhereTagContainsData)
.Func(_SC("TagMatches"), &Entity< CKeyBind >::EachWhereTagMatchesData)
);
exeach_ns.Bind(_SC("Object"), Table(vm)
@ -856,13 +856,13 @@ void Register(HSQUIRRELVM vm)
.Func(_SC("TagMatches"), &Entity< CCheckpoint >::CountWhereTagMatches)
);
count_ns.Bind(_SC("Keybind"), Table(vm)
.Func(_SC("Active"), &Entity< CKeybind >::CountActive)
.Func(_SC("TagEquals"), &Entity< CKeybind >::CountWhereTagEquals)
.Func(_SC("TagBegins"), &Entity< CKeybind >::CountWhereTagBegins)
.Func(_SC("TagEnds"), &Entity< CKeybind >::CountWhereTagEnds)
.Func(_SC("TagContains"), &Entity< CKeybind >::CountWhereTagContains)
.Func(_SC("TagMatches"), &Entity< CKeybind >::CountWhereTagMatches)
count_ns.Bind(_SC("KeyBind"), Table(vm)
.Func(_SC("Active"), &Entity< CKeyBind >::CountActive)
.Func(_SC("TagEquals"), &Entity< CKeyBind >::CountWhereTagEquals)
.Func(_SC("TagBegins"), &Entity< CKeyBind >::CountWhereTagBegins)
.Func(_SC("TagEnds"), &Entity< CKeyBind >::CountWhereTagEnds)
.Func(_SC("TagContains"), &Entity< CKeyBind >::CountWhereTagContains)
.Func(_SC("TagMatches"), &Entity< CKeyBind >::CountWhereTagMatches)
);
count_ns.Bind(_SC("Object"), Table(vm)

View File

@ -12,13 +12,13 @@
#define SQMOD_VALID_TAG_STR(t) if (!(t)) { STHROWF("The specified tag is invalid"); }
// ------------------------------------------------------------------------------------------------
namespace SqMod {
namespace SqMod { // NOLINT(modernize-concat-nested-namespaces)
namespace Algo {
/* ------------------------------------------------------------------------------------------------
* Returns a pointer to the first occurrence of 'needle' in 'haystack'.
*/
inline CSStr sqmod_stristr(CSStr haystack, CSStr needle)
inline const SQChar * sqmod_stristr(const SQChar * haystack, const SQChar * needle)
{
for (const auto chr = static_cast< const SQChar >(std::tolower(*needle)); *haystack != '\0'; ++haystack)
{
@ -27,7 +27,7 @@ inline CSStr sqmod_stristr(CSStr haystack, CSStr needle)
continue;
}
for (CSStr itr = haystack, str = needle;; ++itr, ++str)
for (const SQChar * itr = haystack, * str = needle;; ++itr, ++str)
{
if (*str == '\0')
{
@ -50,7 +50,7 @@ inline CSStr sqmod_stristr(CSStr haystack, CSStr needle)
/* ------------------------------------------------------------------------------------------------
* Find the specified string in another string.
*/
inline bool FindStr(CSStr str1, CSStr str2, bool cs)
inline bool FindStr(const SQChar * str1, const SQChar * str2, bool cs)
{
if (!str1 || !str2 || (*str1 == '\0' && *str2 == '\0'))
{
@ -67,7 +67,7 @@ inline bool FindStr(CSStr str1, CSStr str2, bool cs)
/* ------------------------------------------------------------------------------------------------
* Compare the specified strings.
*/
inline Int32 CompareStr(CSStr lhs, CSStr rhs, bool cs)
inline int32_t CompareStr(const SQChar * lhs, const SQChar * rhs, bool cs)
{
if (!lhs)
{
@ -90,7 +90,7 @@ inline Int32 CompareStr(CSStr lhs, CSStr rhs, bool cs)
/* ------------------------------------------------------------------------------------------------
* Compare a portion from the specified strings.
*/
inline Int32 CompareStr(CSStr lhs, CSStr rhs, Uint32 len, bool cs)
inline int32_t CompareStr(const SQChar * lhs, const SQChar * rhs, uint32_t len, bool cs)
{
if (!lhs)
{
@ -113,7 +113,7 @@ inline Int32 CompareStr(CSStr lhs, CSStr rhs, Uint32 len, bool cs)
/* ------------------------------------------------------------------------------------------------
* Compare a portion from the specified strings starting from a certain position.
*/
inline Int32 CompareStr(CSStr lhs, CSStr rhs, Uint32 pos, Uint32 len, bool cs)
inline int32_t CompareStr(const SQChar * lhs, const SQChar * rhs, uint32_t pos, uint32_t len, bool cs)
{
if (!lhs)
{
@ -146,7 +146,7 @@ inline Int32 CompareStr(CSStr lhs, CSStr rhs, Uint32 pos, Uint32 len, bool cs)
/* ------------------------------------------------------------------------------------------------
* Compare the specified strings.
*/
inline bool ApplyStrFilter(CSStr name, CSStr filter, bool cs)
inline bool ApplyStrFilter(const SQChar * name, const SQChar * filter, bool cs)
{
return cs ? NameFilterCheck(filter, name) : NameFilterCheckInsensitive(filter, name);
}
@ -190,7 +190,7 @@ void CollectWhile(Iterator first, Iterator last, Inspector inspect, Collector co
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachEquals(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -207,7 +207,7 @@ void EachEquals(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachEqualsWhile(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -228,7 +228,7 @@ void EachEqualsWhile(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachBegins(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, std::size_t len, bool neg, bool cs)
const SQChar * str, std::size_t len, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -241,7 +241,7 @@ void EachBegins(Iterator first, Iterator last,
// Compare the string
if (s.size() >= len)
{
if ((CompareStr(s.c_str(), str, static_cast< Uint32 >(len), cs) == 0) == neg)
if ((CompareStr(s.c_str(), str, static_cast< uint32_t >(len), cs) == 0) == neg)
{
collect(*first);
}
@ -260,7 +260,7 @@ void EachBegins(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachBeginsWhile(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, std::size_t len, bool neg, bool cs)
const SQChar * str, std::size_t len, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -273,7 +273,7 @@ void EachBeginsWhile(Iterator first, Iterator last,
// Compare the string
if (s.size() >= len)
{
if ((CompareStr(s.c_str(), str, static_cast< Uint32 >(len), cs) == 0) == neg)
if ((CompareStr(s.c_str(), str, static_cast< uint32_t >(len), cs) == 0) == neg)
{
if (!collect(*first))
{
@ -298,7 +298,7 @@ void EachBeginsWhile(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachEnds(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, std::size_t len, bool neg, bool cs)
const SQChar * str, std::size_t len, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -311,7 +311,7 @@ void EachEnds(Iterator first, Iterator last,
// Compare the tag
if (s.size() >= len)
{
if ((CompareStr(s.c_str(), str, static_cast< Uint32 >(s.size() - len), static_cast< Uint32 >(len), cs) == 0) == neg)
if ((CompareStr(s.c_str(), str, static_cast< uint32_t >(s.size() - len), static_cast< uint32_t >(len), cs) == 0) == neg)
{
collect(*first);
}
@ -330,7 +330,7 @@ void EachEnds(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachEndsWhile(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, std::size_t len, bool neg, bool cs)
const SQChar * str, std::size_t len, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -343,7 +343,7 @@ void EachEndsWhile(Iterator first, Iterator last,
// Compare the tag
if (s.size() >= len)
{
if ((CompareStr(s.c_str(), str, static_cast< Uint32 >(s.size() - len), static_cast< Uint32 >(len), cs) == 0) == neg)
if ((CompareStr(s.c_str(), str, static_cast< uint32_t >(s.size() - len), static_cast< uint32_t >(len), cs) == 0) == neg)
{
if (!collect(*first))
{
@ -368,7 +368,7 @@ void EachEndsWhile(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachContains(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -386,7 +386,7 @@ void EachContains(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachContainsWhile(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -407,7 +407,7 @@ void EachContainsWhile(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachMatches(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -425,7 +425,7 @@ void EachMatches(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Collector >
void EachMatchesWhile(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Collector collect,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -445,7 +445,7 @@ void EachMatchesWhile(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Receiver >
void FirstEquals(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Receiver receive,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -464,7 +464,7 @@ void FirstEquals(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Receiver >
void FirstBegins(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Receiver receive,
CSStr str, std::size_t len, bool neg, bool cs)
const SQChar * str, std::size_t len, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -477,7 +477,7 @@ void FirstBegins(Iterator first, Iterator last,
// Compare the string
if (s.size() >= len)
{
if ((CompareStr(s.c_str(), str, static_cast< Uint32 >(len), cs) == 0) == neg)
if ((CompareStr(s.c_str(), str, static_cast< uint32_t >(len), cs) == 0) == neg)
{
receive(*first);
break;
@ -498,7 +498,7 @@ void FirstBegins(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Receiver >
void FirstEnds(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Receiver receive,
CSStr str, std::size_t len, bool neg, bool cs)
const SQChar * str, std::size_t len, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -511,7 +511,7 @@ void FirstEnds(Iterator first, Iterator last,
// Compare the string
if (s.size() >= len)
{
if ((CompareStr(s.c_str(), str, static_cast< Uint32 >(s.size() - len), static_cast< Uint32 >(len), cs) == 0) == neg)
if ((CompareStr(s.c_str(), str, static_cast< uint32_t >(s.size() - len), static_cast< uint32_t >(len), cs) == 0) == neg)
{
receive(*first);
break;
@ -532,7 +532,7 @@ void FirstEnds(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Receiver >
void FirstContains(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Receiver receive,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -551,7 +551,7 @@ void FirstContains(Iterator first, Iterator last,
template < typename Iterator, typename Inspector, typename Retriever, typename Receiver >
void FirstMatches(Iterator first, Iterator last,
Inspector inspect, Retriever retrieve, Receiver receive,
CSStr str, bool neg, bool cs)
const SQChar * str, bool neg, bool cs)
{
for (; first != last; ++first)
{
@ -581,8 +581,8 @@ template <> struct InstSpec< CBlip >
static constexpr int Max = SQMOD_BLIP_POOL; // Maximum identifier for this entity type.
// --------------------------------------------------------------------------------------------
static constexpr CSStr LcName = "blip"; // Lowercase name of this entity type.
static constexpr CSStr UcName = "Blip"; // Uppercase name of this entity type.
static constexpr const SQChar * LcName = "blip"; // Lowercase name of this entity type.
static constexpr const SQChar * UcName = "Blip"; // Uppercase name of this entity type.
/* --------------------------------------------------------------------------------------------
* Iterator to the beginning of the instance container.
@ -622,8 +622,8 @@ template <> struct InstSpec< CCheckpoint >
static constexpr int Max = SQMOD_CHECKPOINT_POOL; // Maximum identifier for this entity type.
// --------------------------------------------------------------------------------------------
static constexpr CSStr LcName = "checkpoint"; // Lowercase name of this entity type.
static constexpr CSStr UcName = "Checkpoint"; // Uppercase name of this entity type.
static constexpr const SQChar * LcName = "checkpoint"; // Lowercase name of this entity type.
static constexpr const SQChar * UcName = "Checkpoint"; // Uppercase name of this entity type.
/* --------------------------------------------------------------------------------------------
* Iterator to the beginning of the instance container.
@ -651,27 +651,27 @@ template <> struct InstSpec< CCheckpoint >
};
/* ------------------------------------------------------------------------------------------------
* Specialization for the Keybind entity type.
* Specialization for the KeyBind entity type.
*/
template <> struct InstSpec< CKeybind >
template <> struct InstSpec< CKeyBind >
{
// --------------------------------------------------------------------------------------------
typedef Core::Keybinds Instances; // Container to store instances of this entity type.
typedef Core::Keybinds::value_type Instance; // Type that manages this type of entity instance.
typedef Core::KeyBinds Instances; // Container to store instances of this entity type.
typedef Core::KeyBinds::value_type Instance; // Type that manages this type of entity instance.
// --------------------------------------------------------------------------------------------
static constexpr int Max = SQMOD_KEYBIND_POOL; // Maximum identifier for this entity type.
// --------------------------------------------------------------------------------------------
static constexpr CSStr LcName = "keybind"; // Lowercase name of this entity type.
static constexpr CSStr UcName = "Keybind"; // Uppercase name of this entity type.
static constexpr const SQChar * LcName = "keybind"; // Lowercase name of this entity type.
static constexpr const SQChar * UcName = "KeyBind"; // Uppercase name of this entity type.
/* --------------------------------------------------------------------------------------------
* Iterator to the beginning of the instance container.
*/
static inline Instances::const_iterator CBegin()
{
return Core::Get().GetKeybinds().cbegin();
return Core::Get().GetKeyBinds().cbegin();
}
/* --------------------------------------------------------------------------------------------
@ -679,7 +679,7 @@ template <> struct InstSpec< CKeybind >
*/
static inline Instances::const_iterator CEnd()
{
return Core::Get().GetKeybinds().cend();
return Core::Get().GetKeyBinds().cend();
}
/* --------------------------------------------------------------------------------------------
@ -687,7 +687,7 @@ template <> struct InstSpec< CKeybind >
*/
static inline LightObj & Null()
{
return Core::Get().GetNullKeybind();
return Core::Get().GetNullKeyBind();
}
};
@ -704,8 +704,8 @@ template <> struct InstSpec< CObject >
static constexpr int Max = SQMOD_OBJECT_POOL; // Maximum identifier for this entity type.
// --------------------------------------------------------------------------------------------
static constexpr CSStr LcName = "object"; // Lowercase name of this entity type.
static constexpr CSStr UcName = "Object"; // Uppercase name of this entity type.
static constexpr const SQChar * LcName = "object"; // Lowercase name of this entity type.
static constexpr const SQChar * UcName = "Object"; // Uppercase name of this entity type.
/* --------------------------------------------------------------------------------------------
* Iterator to the beginning of the instance container.
@ -745,8 +745,8 @@ template <> struct InstSpec< CPickup >
static constexpr int Max = SQMOD_PICKUP_POOL; // Maximum identifier for this entity type.
// --------------------------------------------------------------------------------------------
static constexpr CSStr LcName = "pickup"; // Lowercase name of this entity type.
static constexpr CSStr UcName = "Pickup"; // Uppercase name of this entity type.
static constexpr const SQChar * LcName = "pickup"; // Lowercase name of this entity type.
static constexpr const SQChar * UcName = "Pickup"; // Uppercase name of this entity type.
/* --------------------------------------------------------------------------------------------
* Iterator to the beginning of the instance container.
@ -786,8 +786,8 @@ template <> struct InstSpec< CPlayer >
static constexpr int Max = SQMOD_PLAYER_POOL; // Maximum identifier for this entity type.
// --------------------------------------------------------------------------------------------
static constexpr CSStr LcName = "player"; // Lowercase name of this entity type.
static constexpr CSStr UcName = "Player"; // Uppercase name of this entity type.
static constexpr const SQChar * LcName = "player"; // Lowercase name of this entity type.
static constexpr const SQChar * UcName = "Player"; // Uppercase name of this entity type.
/* --------------------------------------------------------------------------------------------
* Iterator to the beginning of the instance container.
@ -827,8 +827,8 @@ template <> struct InstSpec< CVehicle >
static constexpr int Max = SQMOD_VEHICLE_POOL; // Maximum identifier for this entity type.
// --------------------------------------------------------------------------------------------
static constexpr CSStr LcName = "vehicle"; // Lowercase name of this entity type.
static constexpr CSStr UcName = "Vehicle"; // Uppercase name of this entity type.
static constexpr const SQChar * LcName = "vehicle"; // Lowercase name of this entity type.
static constexpr const SQChar * UcName = "Vehicle"; // Uppercase name of this entity type.
/* --------------------------------------------------------------------------------------------
* Iterator to the beginning of the instance container.
@ -952,12 +952,12 @@ public:
// --------------------------------------------------------------------------------------------
LightObj mEnv; // The script callback environment object.
LightObj mFunc; // The script callback object to receive the element.
Uint32 mCount; // The number of elements forwarded by this functor.
uint32_t mCount; // The number of elements forwarded by this functor.
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
ForwardElemFunc(Function & func)
explicit ForwardElemFunc(Function & func)
: mEnv(func.GetEnv()), mFunc(func.GetFunc()), mCount(0)
{
if (mFunc.IsNull())
@ -1009,7 +1009,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit cast to the count value.
*/
operator Uint32 () const // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
operator uint32_t () const // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
{
return mCount;
}
@ -1026,7 +1026,7 @@ public:
LightObj mEnv; // The script callback environment object.
LightObj mFunc; // The script callback object to receive the element.
LightObj mData; // The script payload to accompany the element.
Uint32 mCount; // The number of elements forwarded by this functor.
uint32_t mCount; // The number of elements forwarded by this functor.
/* --------------------------------------------------------------------------------------------
* Base constructor.
@ -1085,7 +1085,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit cast to the count value.
*/
operator Uint32 () const // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
operator uint32_t () const // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
{
return mCount;
}
@ -1099,7 +1099,7 @@ template < typename T > struct CountElemFunc
public:
// --------------------------------------------------------------------------------------------
Uint32 mCount; // The number of elements received by this functor.
uint32_t mCount; // The number of elements received by this functor.
/* --------------------------------------------------------------------------------------------
* Base constructor.
@ -1121,7 +1121,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Implicit cast to the count value.
*/
operator Uint32 () const // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
operator uint32_t () const // NOLINT(google-explicit-constructor,hicpp-explicit-conversions)
{
return mCount;
}
@ -1182,7 +1182,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Find the entity that matches the specified identifier.
*/
static inline const LightObj & FindByID(Int32 id)
static inline const LightObj & FindByID(int32_t id)
{
// Perform a range check on the specified identifier
if (INVALID_ENTITYEX(id, Inst::Max))
@ -1222,7 +1222,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Collect all entities of this type where the tag matches or not the specified one.
*/
static inline Array AllWhereTagEquals(bool neg, bool cs, CSStr tag)
static inline Array AllWhereTagEquals(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Remember the current stack size
@ -1238,7 +1238,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Collect all entities of this type where the tag begins or not with the specified string.
*/
static inline Array AllWhereTagBegins(bool neg, bool cs, CSStr tag)
static inline Array AllWhereTagBegins(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Remember the current stack size
@ -1254,7 +1254,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Collect all entities of this type where the tag ends or not with the specified string.
*/
static inline Array AllWhereTagEnds(bool neg, bool cs, CSStr tag)
static inline Array AllWhereTagEnds(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Remember the current stack size
@ -1270,7 +1270,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Collect all entities of this type where the tag contains or not the specified string.
*/
static inline Array AllWhereTagContains(bool neg, bool cs, CSStr tag)
static inline Array AllWhereTagContains(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Remember the current stack size
@ -1286,7 +1286,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Collect all entities of this type where the tag matches or not the specified filter.
*/
static inline Array AllWhereTagMatches(bool neg, bool cs, CSStr tag)
static inline Array AllWhereTagMatches(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Remember the current stack size
@ -1302,7 +1302,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the first entity of this type where the tag matches or not the specified one.
*/
static inline LightObj FirstWhereTagEquals(bool neg, bool cs, CSStr tag)
static inline LightObj FirstWhereTagEquals(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element receiver
@ -1317,7 +1317,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the first entity of this type where the tag begins or not with the specified string.
*/
static inline LightObj FirstWhereTagBegins(bool neg, bool cs, CSStr tag)
static inline LightObj FirstWhereTagBegins(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element receiver
@ -1332,7 +1332,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the first entity of this type where the tag ends or not with the specified string.
*/
static inline LightObj FirstWhereTagEnds(bool neg, bool cs, CSStr tag)
static inline LightObj FirstWhereTagEnds(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element receiver
@ -1347,7 +1347,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the first entity of this type where the tag contains or not the specified string.
*/
static inline LightObj FirstWhereTagContains(bool neg, bool cs, CSStr tag)
static inline LightObj FirstWhereTagContains(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element receiver
@ -1362,7 +1362,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Retrieve the first entity of this type where the tag matches or not the specified filter.
*/
static inline LightObj FirstWhereTagMatches(bool neg, bool cs, CSStr tag)
static inline LightObj FirstWhereTagMatches(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element receiver
@ -1377,7 +1377,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all active entities of this type.
*/
static inline Uint32 EachActive(Function & func)
static inline uint32_t EachActive(Function & func)
{
// Create a new element forwarder
ForwardElem fwd(func);
@ -1391,7 +1391,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all active entities of this type.
*/
static inline Uint32 EachActiveData(LightObj & data, Function & func)
static inline uint32_t EachActiveData(LightObj & data, Function & func)
{
// Create a new element forwarder
ForwardElemData fwd(data, func);
@ -1405,7 +1405,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag matches or not the specified one.
*/
static inline Uint32 EachWhereTagEquals(bool neg, bool cs, CSStr tag, Function & func)
static inline uint32_t EachWhereTagEquals(bool neg, bool cs, const SQChar * tag, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1420,7 +1420,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag matches or not the specified one.
*/
static inline Uint32 EachWhereTagEqualsData(bool neg, bool cs, CSStr tag, LightObj & data, Function & func)
static inline uint32_t EachWhereTagEqualsData(bool neg, bool cs, const SQChar * tag, LightObj & data, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1435,7 +1435,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag begins with the specified string.
*/
static inline Uint32 EachWhereTagBegins(bool neg, bool cs, CSStr tag, Function & func)
static inline uint32_t EachWhereTagBegins(bool neg, bool cs, const SQChar * tag, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1450,7 +1450,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag begins with the specified string.
*/
static inline Uint32 EachWhereTagBeginsData(bool neg, bool cs, CSStr tag, LightObj & data, Function & func)
static inline uint32_t EachWhereTagBeginsData(bool neg, bool cs, const SQChar * tag, LightObj & data, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1465,7 +1465,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag ends or not with the specified string.
*/
static inline Uint32 EachWhereTagEnds(bool neg, bool cs, CSStr tag, Function & func)
static inline uint32_t EachWhereTagEnds(bool neg, bool cs, const SQChar * tag, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1480,7 +1480,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag ends or not with the specified string.
*/
static inline Uint32 EachWhereTagEndsData(bool neg, bool cs, CSStr tag, LightObj & data, Function & func)
static inline uint32_t EachWhereTagEndsData(bool neg, bool cs, const SQChar * tag, LightObj & data, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1495,7 +1495,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag contains the specified string.
*/
static inline Uint32 EachWhereTagContains(bool neg, bool cs, CSStr tag, Function & func)
static inline uint32_t EachWhereTagContains(bool neg, bool cs, const SQChar * tag, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1510,7 +1510,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag contains the specified string.
*/
static inline Uint32 EachWhereTagContainsData(bool neg, bool cs, CSStr tag, LightObj & data, Function & func)
static inline uint32_t EachWhereTagContainsData(bool neg, bool cs, const SQChar * tag, LightObj & data, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1525,7 +1525,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag match the specified filter.
*/
static inline Uint32 EachWhereTagMatches(bool neg, bool cs, CSStr tag, Function & func)
static inline uint32_t EachWhereTagMatches(bool neg, bool cs, const SQChar * tag, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1540,7 +1540,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Process all entities of this type where the tag match the specified filter.
*/
static inline Uint32 EachWhereTagMatchesData(bool neg, bool cs, CSStr tag, LightObj & data, Function & func)
static inline uint32_t EachWhereTagMatchesData(bool neg, bool cs, const SQChar * tag, LightObj & data, Function & func)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element forwarder
@ -1555,7 +1555,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Count all active entities of this type.
*/
static inline Uint32 CountActive()
static inline uint32_t CountActive()
{
// Create a new element counter
CountElem cnt;
@ -1569,7 +1569,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the tag matches or not the specified one.
*/
static inline Uint32 CountWhereTagEquals(bool neg, bool cs, CSStr tag)
static inline uint32_t CountWhereTagEquals(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element counter
@ -1584,7 +1584,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the tag begins with the specified string.
*/
static inline Uint32 CountWhereTagBegins(bool neg, bool cs, CSStr tag)
static inline uint32_t CountWhereTagBegins(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element counter
@ -1599,7 +1599,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the tag ends or not with the specified string.
*/
static inline Uint32 CountWhereTagEnds(bool neg, bool cs, CSStr tag)
static inline uint32_t CountWhereTagEnds(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element counter
@ -1614,7 +1614,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the tag contains the specified string.
*/
static inline Uint32 CountWhereTagContains(bool neg, bool cs, CSStr tag)
static inline uint32_t CountWhereTagContains(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element counter
@ -1629,7 +1629,7 @@ public:
/* --------------------------------------------------------------------------------------------
* Count all entities of this type where the tag matches the specified filter.
*/
static inline CountElem CountWhereTagMatches(bool neg, bool cs, CSStr tag)
static inline CountElem CountWhereTagMatches(bool neg, bool cs, const SQChar * tag)
{
SQMOD_VALID_TAG_STR(tag)
// Create a new element counter

View File

@ -1,483 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Misc/Areas.hpp"
// ------------------------------------------------------------------------------------------------
#include <algorithm>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(AreaTypename, _SC("SqArea"))
// ------------------------------------------------------------------------------------------------
AreaManager AreaManager::s_Inst;
// ------------------------------------------------------------------------------------------------
void Area::AddArray(const Sqrat::Array & a)
{
float values[2];
a.Foreach([this, &values, n = int(0)](HSQUIRRELVM vm, SQInteger i) mutable -> SQRESULT {
// Retrieve the type of the value
const SQObjectType type = sq_gettype(vm, -1);
// Are we dealing with a vector?
if (type == OT_INSTANCE)
{
// Next time, start again for floats
n = 0;
// Grab the instance from the stack
this->AddPoint(*ClassType< Vector2 >::GetInstance(vm, -1));
}
else if (type & SQOBJECT_NUMERIC)
{
// Retrieve the value from the stack
values[n] = Var< float >(vm, -1).value;
// Do we have enough to form a vector?
if (++n == 2)
{
this->AddPointEx(values[0], values[1]);
// Reset the counter
n = 0;
}
}
// Ignore anything else
return SQ_OK;
});
}
// ------------------------------------------------------------------------------------------------
void Area::AddCircleEx(SQFloat cx, SQFloat cy, SQFloat cr, SQInteger num_segments)
{
for(SQInteger i = 0; i < num_segments; ++i)
{
CheckLock();
// Get the current angle
#ifdef SQUSEDOUBLE
SQFloat theta = 2.0d * SQMOD_PI64 * static_cast< SQFloat >(i) / static_cast< SQFloat >(num_segments);
#else
SQFloat theta = 2.0f * SQMOD_PI * static_cast< SQFloat >(i) / static_cast< SQFloat >(num_segments);
#endif // SQUSEDOUBLE
// Calculate the x component
SQFloat x = (cr * std::cos(theta)) + cx;
// Calculate the y component
SQFloat y = (cr * std::sin(theta)) + cy;
// Insert the point into the list
mPoints.emplace_back(x, y);
// Update the bounding box
Expand(x, y);
}
}
// ------------------------------------------------------------------------------------------------
bool Area::Manage()
{
// Are we connected to any cells?
if (!mCells.empty())
{
STHROWF("The area is already managed");
}
// We expect this to be called only from the script so that the first parameter in the vm
// is the area instance
LightObj obj(1, SqVM());
// Attempt to manage this area
AreaManager::Get().InsertArea(*this, obj);
// Return whether the area is now managed by any cells
return !mCells.empty();
}
// ------------------------------------------------------------------------------------------------
bool Area::Unmanage()
{
// Are we connected to any cells?
if (mCells.empty())
{
return true; // Already unmanaged
}
// Attempt to unmanage this area
AreaManager::Get().RemoveArea(*this);
// Return whether the area is not managed by any cells
return mCells.empty();
}
// ------------------------------------------------------------------------------------------------
bool Area::IsInside(float x, float y) const
{
// Is the an area to test?
if (mPoints.size() < 3)
{
return false; // Can't possibly be in an area that doesn't exist
}
// http://sidvind.com/wiki/Point-in-polygon:_Jordan_Curve_Theorem
// The points creating the polygon
float x1, x2;
// How many times the ray crosses a line segment
int crossings = 0;
// Iterate through each line
for (Uint32 i = 0, n = static_cast< Uint32 >(mPoints.size()); i < n; ++i)
{
Points::const_reference a = mPoints[i];
Points::const_reference b = mPoints[(i + 1) % n];
// This is done to ensure that we get the same result when
// the line goes from left to right and right to left.
if (a.x < b.x)
{
x1 = a.x;
x2 = b.x;
}
else
{
x1 = b.x;
x2 = a.x;
}
// First check if the ray is able to cross the line
if (x > x1 && x <= x2 && (y < a.y || y <= b.y))
{
// Calculate the equation of the line
const float dx = (b.x - a.x);
const float dy = (b.y - a.y);
float k;
if (fabsf(dx) < 0.000001f)
{
k = 0xffffffffu; // NOLINT(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions)
}
else
{
k = (dy / dx);
}
const float m = (a.y - k * a.x);
const float y2 = (k * x + m);
// Does the ray cross the line?
if (y <= y2)
{
++crossings;
}
}
}
// Return if the crossings are not even
return (crossings % 2 == 1);
}
// ------------------------------------------------------------------------------------------------
AreaManager::AreaManager(size_t sz) noexcept
: m_Queue(), m_ProcList(), m_Grid{}
{
// Negative half grid size (left)
int l = (-GRIDH * CELLD);
// Positive half grid size minus one cell (bottom)
int b = (abs(l) - CELLD);
// Negative half grid size minus one cell (right)
int r = (l + CELLD);
// Positive half grid size (top)
int t = abs(l);
// Initialize the grid cells
for (auto & a : m_Grid)
{
for (auto & c : a)
{
// Grab a reference to the cell
// Configure the range of the cell
c.mL = static_cast< float >(l);
c.mB = static_cast< float >(b);
c.mR = static_cast< float >(r);
c.mT = static_cast< float >(t);
// Reserve area memory if requested
c.mAreas.reserve(sz);
// Reset the locks on this area
c.mLocks = 0;
// Advance the left side
l = r;
// Advance the right side
r += CELLD;
// Should we advance to the next row?
if (r > (GRIDH * CELLD))
{
// Reset the left side
l = (-GRIDH * CELLD);
// Reset the right side
r = (l + CELLD);
// Advance the bottom
b -= CELLD;
// Advance the top
t -= CELLD;
}
}
}
// Reserve some space in the queue
m_Queue.reserve(128);
m_ProcList.reserve(128);
}
// ------------------------------------------------------------------------------------------------
void AreaManager::Insert(AreaCell & c, Area & a, LightObj & obj)
{
// Is this cell currently locked?
if (c.mLocks)
{
m_Queue.emplace_back(c, a, obj); // Queue this request for now
}
else
{
c.mAreas.emplace_back(&a, obj);
}
// Associate the area with this cell so it can't be managed again (even while in the queue)
a.mCells.push_back(&c);
}
// ------------------------------------------------------------------------------------------------
void AreaManager::Remove(AreaCell & c, Area & a)
{
// Is this cell currently locked?
if (c.mLocks)
{
m_Queue.emplace_back(c, a); // Queue this request for now
}
else
{
// Attempt to locate this area in the cell
auto itr = std::find_if(c.mAreas.begin(), c.mAreas.end(),
[&a](AreaCell::Areas::reference p) -> bool {
return (p.first == &a);
});
// Have we found it?
if (itr != c.mAreas.end())
{
c.mAreas.erase(itr); // Erase it
}
}
// Dissociate the area with this cell so it can be managed again (even while in the queue)
auto itr = std::find(a.mCells.begin(), a.mCells.end(), &c);
// Was is associated?
if (itr != a.mCells.end())
{
a.mCells.erase(itr); // Dissociate them
}
}
// ------------------------------------------------------------------------------------------------
void AreaManager::ProcQueue()
{
// Look for actions that can be completed
for (auto itr = m_Queue.begin(); itr != m_Queue.end(); ++itr)
{
// Was this cell unlocked in the meantime?
if (itr->mCell->mLocks <= 0)
{
m_ProcList.push_back(itr);
}
}
// Process the actions that are ready
for (auto & itr : m_ProcList)
{
// Was this a remove request?
if (itr->mObj.IsNull())
{
Remove(*(itr->mCell), *(itr->mArea));
}
else
{
Insert(*(itr->mCell), *(itr->mArea), itr->mObj);
}
}
// Remove processed requests
for (auto & itr : m_ProcList)
{
m_Queue.erase(itr);
}
// Actions were processed
m_ProcList.clear();
}
// ------------------------------------------------------------------------------------------------
void AreaManager::Clear()
{
// Clear the cells
for (AreaCell (&row)[GRIDN] : m_Grid)
{
for (AreaCell & c : row)
{
c.mAreas.clear();
}
}
// Clear the queue as well
m_Queue.clear();
m_ProcList.clear();
}
// ------------------------------------------------------------------------------------------------
void AreaManager::InsertArea(Area & a, LightObj & obj)
{
// See if this area is already managed
if (!a.mCells.empty() || a.mPoints.empty())
{
return; // Already managed or nothing to manage
}
// Go through each cell and check if the area touches it
for (auto & y : m_Grid)
{
for (auto & c : y)
{
// Does the bounding box of this cell intersect with the one of the area?
if (a.mL <= c.mR && c.mL <= a.mR && a.mB <= c.mT && c.mB <= a.mT)
{
Insert(c, a, obj); // Attempt to insert the area into this cell
}
}
}
}
// ------------------------------------------------------------------------------------------------
void AreaManager::RemoveArea(Area & a)
{
// Just remove the associated cells
for (auto c : a.mCells)
{
Remove(*c, a);
}
}
// ------------------------------------------------------------------------------------------------
Vector2i AreaManager::LocateCell(float x, float y)
{
// Transform the world coordinates into a cell coordinates
// and cast to integral after rounding the value
int xc = static_cast< int >(std::round(x / CELLD));
int yc = static_cast< int >(std::round(y / CELLD));
// Grab the absolute cell coordinates for range checking
const int xca = std::abs(xc);
const int yca = std::abs(yc);
// Make sure the cell coordinates are within range
if (xca > (GRIDH+1) || yca > (GRIDH+1))
{
return {NOCELL, NOCELL}; // Out of our scanning area
}
// Clamp the x coordinate if necessary
if (xca >= (GRIDH))
{
xc = xc < 0 ? -(GRIDH-1) : (GRIDH-1);
}
// Clamp the y coordinate if necessary
if (yca >= (GRIDH))
{
yc = xc < 0 ? -(GRIDH-1) : (GRIDH-1);
}
// Return the identified cell row and column
return {GRIDH+xc, GRIDH-yc};
}
// ------------------------------------------------------------------------------------------------
static void Areas_TestPointEx(float x, float y, Function & func)
{
// Is the function valid?
if (func.IsNull())
{
STHROWF("Invalid callback object");
}
// Begin testing
AreaManager::Get().TestPoint([&func](AreaCell::Areas::reference ap) -> void {
func.Execute(ap.second);
}, x, y);
}
// ------------------------------------------------------------------------------------------------
static void Areas_TestPoint(const Vector2 & v, Function & func)
{
Areas_TestPointEx(v.x, v.y, func);
}
// ------------------------------------------------------------------------------------------------
static void Areas_TestPointOnEx(float x, float y, Object & ctx, Function & func)
{
// Begin testing
AreaManager::Get().TestPoint([&ctx, &func](AreaCell::Areas::reference ap) -> void {
func.Execute(ctx, ap.second);
}, x, y);
}
// ------------------------------------------------------------------------------------------------
static void Areas_TestPointOn(const Vector2 & v, Object & ctx, Function & func)
{
Areas_TestPointOnEx(v.x, v.y, ctx, func);
}
// ------------------------------------------------------------------------------------------------
static Vector2i Areas_LocatePointCell(const Vector2 & v)
{
return AreaManager::Get().LocateCell(v.x, v.y);
}
// ------------------------------------------------------------------------------------------------
static Vector2i Areas_LocatePointCellEx(float x, float y)
{
return AreaManager::Get().LocateCell(x, y);
}
// ------------------------------------------------------------------------------------------------
void TerminateAreas()
{
AreaManager::Get().Clear();
}
// ================================================================================================
void Register_Areas(HSQUIRRELVM vm)
{
RootTable(vm).Bind(_SC("SqArea"),
Class< Area >(vm, AreaTypename::Str)
// Constructors
.Ctor()
.Ctor< StackStrF & >()
.Ctor< SQInteger, StackStrF & >()
.Ctor< const Vector2 &, const Vector2 &, const Vector2 & >()
.Ctor< const Vector2 &, const Vector2 &, const Vector2 &, StackStrF & >()
.Ctor< const Vector2 &, const Vector2 &, const Vector2 &, SQInteger, StackStrF & >()
.Ctor< float, float, float, float, float, float >()
.Ctor< float, float, float, float, float, float, StackStrF & >()
.Ctor< float, float, float, float, float, float, SQInteger, StackStrF & >()
// Meta-methods
.SquirrelFunc(_SC("_typename"), &AreaTypename::Fn)
.Func(_SC("_tostring"), &Area::ToString)
// Member Properties
.Prop(_SC("Name"), &Area::GetName, &Area::SetName)
.Prop(_SC("ID"), &Area::GetID, &Area::SetID)
.Prop(_SC("Locked"), &Area::IsLocked)
.Prop(_SC("IsLocked"), &Area::IsLocked)
.Prop(_SC("Center"), &Area::GetCenter)
.Prop(_SC("Box"), &Area::GetBoundingBox, &Area::SetBoundingBox)
.Prop(_SC("Empty"), &Area::Empty)
.Prop(_SC("Empty"), &Area::Empty)
.Prop(_SC("Size"), &Area::Size)
.Prop(_SC("Points"), &Area::Size)
.Prop(_SC("Capacity"), &Area::Capacity)
// Member Methods
.FmtFunc(_SC("SetName"), &Area::ApplyName)
.Func(_SC("SetID"), &Area::ApplyID)
.Func(_SC("Clear"), &Area::Clear)
.Func(_SC("Reserve"), &Area::Reserve)
.Func(_SC("SetBox"), &Area::SetBoundingBoxEx)
.Func(_SC("SetBoundingBox"), &Area::SetBoundingBoxEx)
.Func(_SC("Add"), &Area::AddPoint)
.Func(_SC("AddEx"), &Area::AddPointEx)
.Func(_SC("AddVirtual"), &Area::AddVirtualPoint)
.Func(_SC("AddVirtualEx"), &Area::AddVirtualPointEx)
.Func(_SC("AddCircle"), &Area::AddCircle)
.Func(_SC("AddCircleEx"), &Area::AddCircleEx)
.Func(_SC("AddFake"), &Area::AddVirtualPoint)
.Func(_SC("AddFakeEx"), &Area::AddVirtualPointEx)
.Func(_SC("AddArray"), &Area::AddArray)
.Func(_SC("Test"), &Area::Test)
.Func(_SC("TestEx"), &Area::TestEx)
.Func(_SC("Manage"), &Area::Manage)
.Func(_SC("Unmanage"), &Area::Unmanage)
// Static Functions
.StaticFunc(_SC("GlobalTest"), &Areas_TestPoint)
.StaticFunc(_SC("GlobalTestEx"), &Areas_TestPointEx)
.StaticFunc(_SC("GlobalTestOn"), &Areas_TestPointOn)
.StaticFunc(_SC("GlobalTestOnEx"), &Areas_TestPointOnEx)
.StaticFunc(_SC("LocatePointCell"), &Areas_LocatePointCell)
.StaticFunc(_SC("LocatePointCellEx"), &Areas_LocatePointCellEx)
.StaticFunc(_SC("UnmanageAll"), &TerminateAreas)
);
}
} // Namespace:: SqMod

View File

@ -1,701 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Base/Circle.hpp"
#include "Base/Vector2.hpp"
#include "Base/Vector4.hpp"
#include "Base/Vector2i.hpp"
// ------------------------------------------------------------------------------------------------
#include <vector>
#include <utility>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Various information associated with an area cell.
*/
struct AreaCell
{
// --------------------------------------------------------------------------------------------
typedef std::pair< Area *, LightObj > AreaPair; // A reference to an area object.
typedef std::vector< AreaPair > Areas; // A list of area objects.
// --------------------------------------------------------------------------------------------
float mL, mB, mR, mT; // Left-Bottom, Right-Top components of the cell bounding box.
// --------------------------------------------------------------------------------------------
Areas mAreas; // Areas that intersect with the cell.
// --------------------------------------------------------------------------------------------
int mLocks; // The amount of locks on the cell.
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
AreaCell()
: mL(0), mB(0), mR(0), mT(0), mAreas(0), mLocks(0)
{
//...
}
};
/* ------------------------------------------------------------------------------------------------
* Area implementation used to store area points.
*/
struct Area
{
typedef std::vector< Vector2 > Points;
typedef std::vector< AreaCell * > Cells;
// --------------------------------------------------------------------------------------------
static constexpr float DEF_L = std::numeric_limits< float >::infinity();
static constexpr float DEF_B = std::numeric_limits< float >::infinity();
static constexpr float DEF_R = -std::numeric_limits< float >::infinity();
static constexpr float DEF_T = -std::numeric_limits< float >::infinity();
// --------------------------------------------------------------------------------------------
float mL, mB, mR, mT; // Left-Bottom, Right-Top components of the bounding box.
// --------------------------------------------------------------------------------------------
Points mPoints; // Collection of points that make up the area.
// --------------------------------------------------------------------------------------------
SQInteger mID; // The user identifier given to this area.
// --------------------------------------------------------------------------------------------
Cells mCells; // The cells covered by this area.
// --------------------------------------------------------------------------------------------
String mName; // The user name given to this area.
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
Area()
: mL(DEF_L), mB(DEF_B), mR(DEF_R), mT(DEF_T), mPoints(), mID(0), mCells(), mName()
{
//...
}
/* --------------------------------------------------------------------------------------------
* Named constructor.
*/
explicit Area(StackStrF & name)
: Area(16, name)
{
//...
}
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
Area(SQInteger sz, StackStrF & name)
: mL(DEF_L), mB(DEF_B), mR(DEF_R), mT(DEF_T), mPoints(), mID(0), mCells()
, mName(name.mPtr, static_cast< size_t >(name.mLen <= 0 ? 0 : name.mLen))
{
// Should we reserve some space for points in advance?
if (sz > 0)
{
mPoints.reserve(static_cast< size_t >(sz));
}
}
/* --------------------------------------------------------------------------------------------
* Vector2 constructor.
*/
Area(const Vector2 & a, const Vector2 & b, const Vector2 & c)
: Area(a.x, a.y, b.x, b.y, c.x, c.y, 16, StackStrF::Dummy())
{
//...
}
/* --------------------------------------------------------------------------------------------
* Vector2 constructor with name.
*/
Area(const Vector2 & a, const Vector2 & b, const Vector2 & c, StackStrF & name)
: Area(a.x, a.y, b.x, b.y, c.x, c.y, 16, name)
{
//...
}
/* --------------------------------------------------------------------------------------------
* Vector2 constructor with name and memory to reserve.
*/
Area(const Vector2 & a, const Vector2 & b, const Vector2 & c, SQInteger sz, StackStrF & name)
: Area(a.x, a.y, b.x, b.y, c.x, c.y, sz, name)
{
//...
}
/* --------------------------------------------------------------------------------------------
* Extended constructor.
*/
Area(float ax, float ay, float bx, float by, float cx, float cy)
: Area(ax, ay, bx, by, cx, cy, 16, StackStrF::Dummy())
{
//...
}
/* --------------------------------------------------------------------------------------------
* Extended constructor with name.
*/
Area(float ax, float ay, float bx, float by, float cx, float cy, StackStrF & name)
: Area(ax, ay, bx, by, cx, cy, 16, name)
{
//...
}
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
Area(float ax, float ay, float bx, float by, float cx, float cy, SQInteger sz, StackStrF & name)
: mL(DEF_L), mB(DEF_B), mR(DEF_R), mT(DEF_T), mPoints(), mID(0), mCells()
, mName(name.mPtr, static_cast<size_t>(name.mLen <= 0 ? 0 : name.mLen))
{
// Should we reserve some space for points in advance?
if (sz > 0)
{
mPoints.reserve(static_cast< size_t >(sz));
}
// Insert the given points
AddPointEx(ax, ay);
AddPointEx(bx, by);
AddPointEx(cx, cy);
}
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
Area(const Area & o)
: mL(o.mL), mB(o.mB), mR(o.mR), mT(o.mT), mPoints(o.mPoints), mID(o.mID), mCells(0), mName(o.mName)
{
//...
}
/* --------------------------------------------------------------------------------------------
* Move constructor. (disabled)
*/
Area(Area && o) = delete;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
Area & operator = (const Area & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator. (disabled)
*/
Area & operator = (Area && o) = delete;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert this instance to a string.
*/
const String & ToString() const
{
return mName;
}
/* --------------------------------------------------------------------------------------------
* Checks if the area is locked from changes and throws an exception if it is.
*/
void CheckLock()
{
// Are we connected to any cells?
if (!mCells.empty())
{
STHROWF("The area cannot be modified while being managed");
}
}
/* --------------------------------------------------------------------------------------------
* Retrieve the name of this area.
*/
const String & GetName() const
{
return mName;
}
/* --------------------------------------------------------------------------------------------
* Modify the name of this area.
*/
void SetName(StackStrF & name)
{
if (name.mLen <= 0)
{
mName.clear();
}
else
{
mName.assign(name.mPtr, static_cast< size_t >(name.mLen));
}
}
/* --------------------------------------------------------------------------------------------
* Modify the name of this area. (allows chaining function calls)
*/
Area & ApplyName(StackStrF & name)
{
SetName(name);
return *this;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the identifier of this area.
*/
SQInteger GetID() const
{
return mID;
}
/* --------------------------------------------------------------------------------------------
* Modify the identifier of this area.
*/
void SetID(SQInteger id)
{
mID = id;
}
/* --------------------------------------------------------------------------------------------
* Modify the identifier of this area. (allows chaining function calls)
*/
Area & ApplyID(SQInteger id)
{
mID = id;
return *this;
}
/* --------------------------------------------------------------------------------------------
* Check if the area is locked from changes
*/
bool IsLocked() const
{
return mCells.empty();
}
/* --------------------------------------------------------------------------------------------
* Retrieve the center of this area.
*/
Vector2 GetCenter() const
{
return {(mL * 0.5f) + (mR * 0.5f), (mB * 0.5f) + (mT * 0.5f)};
}
/* --------------------------------------------------------------------------------------------
* Retrieve the bounding box of this area.
*/
Vector4 GetBoundingBox() const
{
return {mL, mB, mR, mT};
}
/* --------------------------------------------------------------------------------------------
* Modify the bounding box of this area.
*/
void SetBoundingBox(const Vector4 & b)
{
CheckLock();
// Apply the given bounding box
mL = b.x;
mB = b.y;
mR = b.z;
mT = b.w;
}
/* --------------------------------------------------------------------------------------------
* Modify the bounding box of this area.
*/
void SetBoundingBoxEx(float l, float b, float r, float t)
{
CheckLock();
// Apply the given bounding box
mL = l;
mB = b;
mR = r;
mT = t;
}
/* --------------------------------------------------------------------------------------------
* See whether the area has no points.
*/
bool Empty() const
{
return mPoints.empty();
}
/* --------------------------------------------------------------------------------------------
* Retrieve the number of points in this area.
*/
SQInteger Size() const
{
return ConvTo< SQInteger >::From(mPoints.size());
}
/* --------------------------------------------------------------------------------------------
* Retrieve the number of points this area has allocated for.
*/
SQInteger Capacity() const
{
return ConvTo< SQInteger >::From(mPoints.capacity());
}
/* --------------------------------------------------------------------------------------------
* Clear all points in this area.
*/
void Clear()
{
CheckLock();
// Perform the requested action
mPoints.clear();
}
/* --------------------------------------------------------------------------------------------
* Clear all points in this area.
*/
void Reserve(SQInteger sz)
{
// Perform the requested action
if (sz > 0)
{
mPoints.reserve(static_cast< size_t >(sz));
}
}
/* --------------------------------------------------------------------------------------------
* Add a 2D vector to the point list.
*/
void AddPoint(const Vector2 & v)
{
CheckLock();
// Perform the requested action
mPoints.emplace_back(v);
// Update the bounding box
Expand(v.x, v.y);
}
/* --------------------------------------------------------------------------------------------
* Add a point to the point list.
*/
void AddPointEx(float x, float y)
{
CheckLock();
// Perform the requested action
mPoints.emplace_back(x, y);
// Update the bounding box
Expand(x, y);
}
/* --------------------------------------------------------------------------------------------
* Add a 2D vector to the bounding box only. Not stored in the list.
*/
void AddVirtualPoint(const Vector2 & v)
{
CheckLock();
// Update the bounding box
Expand(v.x, v.y);
}
/* --------------------------------------------------------------------------------------------
* Add a point to the bounding box only. Not stored in the list.
*/
void AddVirtualPointEx(float x, float y)
{
CheckLock();
// Update the bounding box
Expand(x, y);
}
/* --------------------------------------------------------------------------------------------
* Add an array of points to the point list.
*/
void AddArray(const Sqrat::Array & a);
/* --------------------------------------------------------------------------------------------
* Add a 2D circle to the point list.
*/
void AddCircle(const Circle & c, SQInteger num_segments)
{
AddCircleEx(c.pos.x, c.pos.y, c.rad, num_segments);
}
/* --------------------------------------------------------------------------------------------
* Add a 2D circle to the point list.
*/
void AddCircleEx(SQFloat cx, SQFloat cy, SQFloat cr, SQInteger num_segments);
/* --------------------------------------------------------------------------------------------
* Test if a point is inside the bounding box and then the area.
*/
bool Test(const Vector2 & v)
{
// Is the given point in this bounding box at least?
if (mL <= v.x && mR >= v.x && mB <= v.y && mT >= v.y)
{
return mPoints.empty() ? true : IsInside(v.x, v.y);
}
// Not in this area
return false;
}
/* --------------------------------------------------------------------------------------------
* Test if a point is inside the bounding box and then the area.
*/
bool TestEx(float x, float y)
{
// Is the given point in this bounding box at least?
if (mL <= x && mR >= x && mB <= y && mT >= y)
{
return mPoints.empty() ? true : IsInside(x, y);
}
// Not in this area
return false;
}
/* --------------------------------------------------------------------------------------------
* Add this area to the manager to be scanned. MUST BE CALLED ONLY FROM SCRIPT!
*/
bool Manage();
/* --------------------------------------------------------------------------------------------
* Remove this area from the manager to no longer be scanned.
*/
bool Unmanage();
protected:
/* --------------------------------------------------------------------------------------------
* Test if a point is inside the area.
*/
bool IsInside(float x, float y) const;
/* --------------------------------------------------------------------------------------------
* Expand the bounding box area to include the given point.
*/
void Expand(float x, float y)
{
mL = std::fmin(mL, x);
mB = std::fmin(mB, y);
mR = std::fmax(mR, x);
mT = std::fmax(mT, y);
}
};
/* ------------------------------------------------------------------------------------------------
* Manager responsible for storing and partitioning areas.
*/
class AreaManager
{
// --------------------------------------------------------------------------------------------
static AreaManager s_Inst; // Manager instance.
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
explicit AreaManager(size_t sz = 16) noexcept;
protected:
/* --------------------------------------------------------------------------------------------
* Helper used to make sure a cell is properly processed after leaving the scope.
*/
struct CellGuard
{
AreaCell & mCell;
/* ----------------------------------------------------------------------------------------
* Base constructor.
*/
explicit CellGuard(AreaCell & cell)
: mCell(cell)
{
++(cell.mLocks); // Place a lock on the cell to prevent iterator invalidation
}
/* ----------------------------------------------------------------------------------------
* Destructor.
*/
~CellGuard()
{
// Remove the lock from the cell so it can be processed
--(mCell.mLocks);
// Process requested actions during the lock
AreaManager::Get().ProcQueue();
}
};
// --------------------------------------------------------------------------------------------
static constexpr int GRIDN = 16; // Number of horizontal and vertical number of cells.
static constexpr int GRIDH = GRIDN/2; // Half of the grid horizontal and vertical size.
static constexpr int CELLS = GRIDN*GRIDN; // Total number of cells in the grid.
static constexpr int CELLH = CELLS/2; // Half total number of cells in the grid.
static constexpr int CELLD = 256; // Area covered by a cell in the world.
static constexpr int NOCELL = std::numeric_limits< int >::max(); // Inexistent cell index.
/* --------------------------------------------------------------------------------------------
* Helper used to queue a certain action if the cell is locked.
*/
struct QueueElement
{
// ----------------------------------------------------------------------------------------
AreaCell * mCell; // The cell to be affected.
Area * mArea; // The area that made the request.
LightObj mObj; // Strong reference to the object.
/* ----------------------------------------------------------------------------------------
* Base constructor.
*/
QueueElement(AreaCell & cell, Area & area)
: mCell(&cell), mArea(&area), mObj()
{
//...
}
/* ----------------------------------------------------------------------------------------
* Base constructor.
*/
QueueElement(AreaCell & cell, Area & area, LightObj & obj)
: mCell(&cell), mArea(&area), mObj(obj)
{
//...
}
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
QueueElement(const QueueElement & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
QueueElement(QueueElement && o) noexcept
: mCell(o.mCell), mArea(o.mArea), mObj(std::move(o.mObj))
{
// Take ownership
o.mCell = nullptr;
o.mArea = nullptr;
}
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
QueueElement & operator = (const QueueElement & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
QueueElement & operator = (QueueElement && o) noexcept
{
// Avoid self assignment
if (this != &o)
{
// Transfer values
mCell = o.mCell;
mArea = o.mArea;
mObj = std::move(o.mObj);
// Take ownership
o.mCell = nullptr;
o.mArea = nullptr;
}
return *this;
}
};
// --------------------------------------------------------------------------------------------
typedef std::vector< QueueElement > Queue; // Queued actions.
typedef std::vector< Queue::iterator > ProcList; // Elements in the queue redy to process.
/* --------------------------------------------------------------------------------------------
* Attempt to insert an area into a cell or queue the action if not possible.
*/
void Insert(AreaCell & c, Area & a, LightObj & obj);
/* --------------------------------------------------------------------------------------------
* Attempt to remove an area from a cell or queue the action if not possible.
*/
void Remove(AreaCell & c, Area & a);
private:
// --------------------------------------------------------------------------------------------
Queue m_Queue; // Actions currently queued.
ProcList m_ProcList; // Actions ready to be completed.
// --------------------------------------------------------------------------------------------
AreaCell m_Grid[GRIDN][GRIDN]; // A grid of area lists.
public:
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
AreaManager(const AreaManager & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor. (disabled)
*/
AreaManager(AreaManager && o) = delete;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
AreaManager & operator = (const AreaManager & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator. (disabled)
*/
AreaManager & operator = (AreaManager && o) = delete;
/* --------------------------------------------------------------------------------------------
* Retrieve the core instance.
*/
static AreaManager & Get()
{
return s_Inst;
}
/* --------------------------------------------------------------------------------------------
* Attempt to process elements in the queue that can be completed.
*/
void ProcQueue();
/* --------------------------------------------------------------------------------------------
* Clear all cell lists and release any script references.
*/
void Clear();
/* --------------------------------------------------------------------------------------------
* Add an area to be managed.
*/
void InsertArea(Area & a, LightObj & obj);
/* --------------------------------------------------------------------------------------------
* Add an area to be managed.
*/
void RemoveArea(Area & a);
/* --------------------------------------------------------------------------------------------
* Clear all cell lists and release any script references.
*/
static Vector2i LocateCell(float x, float y);
/* --------------------------------------------------------------------------------------------
* Test a point to see whether it intersects with any areas
*/
template < typename F > void TestPoint(F && f, float x, float y)
{
// Transform the world coordinates into a cell coordinates
const Vector2i cc(LocateCell(x, y));
// Were these coordinates valid?
if (cc.x == NOCELL)
{
return; // Not our problem
}
// Retrieve a reference to the identified cell
AreaCell & c = m_Grid[cc.y][cc.x];
// Is this cell empty?
if (c.mAreas.empty())
{
return; // Nothing to test
}
// Guard the cell while processing
const CellGuard cg(c);
// Finally, begin processing the areas in this cell
for (auto & a : c.mAreas)
{
if (a.first->TestEx(x, y))
{
f(a);
}
}
}
};
} // Namespace:: SqMod

View File

@ -7,7 +7,7 @@
namespace SqMod {
// ------------------------------------------------------------------------------------------------
static inline bool SqCanBeInteger(HSQUIRRELVM vm, Int32 idx)
static inline bool SqCanBeInteger(HSQUIRRELVM vm, int32_t idx)
{
switch (sq_gettype(vm, idx))
{
@ -22,9 +22,9 @@ static inline bool SqCanBeInteger(HSQUIRRELVM vm, Int32 idx)
}
// ------------------------------------------------------------------------------------------------
SQRESULT SqGrabPlayerMessageColor(HSQUIRRELVM vm, Int32 idx, Uint32 & color, Int32 & msgidx)
SQRESULT SqGrabPlayerMessageColor(HSQUIRRELVM vm, int32_t idx, uint32_t & color, int32_t & msg_idx)
{
const auto top = static_cast< Int32 >(sq_gettop(vm));
const auto top = static_cast< int32_t >(sq_gettop(vm));
// Is the color argument a Color3/Color4 instance?
if (sq_gettype(vm, idx) == OT_INSTANCE)
{
@ -47,50 +47,50 @@ SQRESULT SqGrabPlayerMessageColor(HSQUIRRELVM vm, Int32 idx, Uint32 & color, Int
{
color = Var< Color4 >(vm, idx).value.GetRGBA();
}
catch (const Sqrat::Exception & e)
catch (const std::exception & e)
{
return sq_throwerror(vm, e.what());
}
}
// The message starts right after the color
msgidx += 1;
msg_idx += 1;
}
// Is the color argument an unpacked RGBA color?
else if ((top - msgidx) >= 4 && SqCanBeInteger(vm, idx)
else if ((top - msg_idx) >= 4 && SqCanBeInteger(vm, idx)
&& SqCanBeInteger(vm, idx+1)
&& SqCanBeInteger(vm, idx+2)
&& SqCanBeInteger(vm, idx+3))
{
color = SQMOD_PACK_RGBA(ConvTo< Uint8 >::From(PopStackInteger(vm, idx)), // NOLINT(hicpp-signed-bitwise)
ConvTo< Uint8 >::From(PopStackInteger(vm, idx+1)),
ConvTo< Uint8 >::From(PopStackInteger(vm, idx+2)),
ConvTo< Uint8 >::From(PopStackInteger(vm, idx+3)));
color = SQMOD_PACK_RGBA(ConvTo< uint8_t >::From(PopStackInteger(vm, idx)), // NOLINT(hicpp-signed-bitwise)
ConvTo< uint8_t >::From(PopStackInteger(vm, idx+1)),
ConvTo< uint8_t >::From(PopStackInteger(vm, idx+2)),
ConvTo< uint8_t >::From(PopStackInteger(vm, idx+3)));
// The message starts right after the color
msgidx += 4;
msg_idx += 4;
}
// Is the color argument an unpacked RGB color?
else if ((top - msgidx) >= 3 && SqCanBeInteger(vm, idx)
else if ((top - msg_idx) >= 3 && SqCanBeInteger(vm, idx)
&& SqCanBeInteger(vm, idx+1)
&& SqCanBeInteger(vm, idx+2))
{
color = SQMOD_PACK_RGBA(ConvTo< Uint8 >::From(PopStackInteger(vm, idx)), // NOLINT(hicpp-signed-bitwise)
ConvTo< Uint8 >::From(PopStackInteger(vm, idx+1)),
ConvTo< Uint8 >::From(PopStackInteger(vm, idx+2)),
color = SQMOD_PACK_RGBA(ConvTo< uint8_t >::From(PopStackInteger(vm, idx)), // NOLINT(hicpp-signed-bitwise)
ConvTo< uint8_t >::From(PopStackInteger(vm, idx+1)),
ConvTo< uint8_t >::From(PopStackInteger(vm, idx+2)),
0xFFu);
// The message starts right after the color
msgidx += 3;
msg_idx += 3;
}
// Is the color argument an packed RGBA color?
else if (SqCanBeInteger(vm, idx))
{
color = static_cast< Uint32 >(PopStackInteger(vm, idx));
color = static_cast< uint32_t >(PopStackInteger(vm, idx));
// The message starts right after the color
msgidx += 1;
msg_idx += 1;
}
// Is the first argument a string which can be interpreted as a color?
else if (sq_gettype(vm, idx) == OT_STRING)
{
CSStr str = nullptr;
const SQChar * str = nullptr;
SQInteger len = 0;
// Attempt to retrieve the color argument as a string
if (SQ_FAILED(sq_getstringandsize(vm, idx, &str, &len)))
@ -111,7 +111,7 @@ SQRESULT SqGrabPlayerMessageColor(HSQUIRRELVM vm, Int32 idx, Uint32 & color, Int
if (*str == '#')
{
// Attempt to treat the value as a hex color
color = ConvTo< Uint32 >::From(std::strtoull(++str, nullptr, 16));
color = ConvTo< uint32_t >::From(std::strtoull(++str, nullptr, 16));
// Adjust the color if necessary
switch (ClampMin(--len, static_cast< SQInteger >(0)))
{
@ -161,7 +161,7 @@ SQRESULT SqGrabPlayerMessageColor(HSQUIRRELVM vm, Int32 idx, Uint32 & color, Int
else if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
{
// Attempt to treat the value as a hex color
color = ConvTo< Uint32 >::From(std::strtoull(str, nullptr, 16));
color = ConvTo< uint32_t >::From(std::strtoull(str, nullptr, 16));
// Adjust the color if necessary
switch (ClampMin(len-2, static_cast< SQInteger >(0)))
{
@ -220,7 +220,7 @@ SQRESULT SqGrabPlayerMessageColor(HSQUIRRELVM vm, Int32 idx, Uint32 & color, Int
}
}
// The message starts right after the color
msgidx += 1;
msg_idx += 1;
}
else
{
@ -234,7 +234,7 @@ SQRESULT SqGrabPlayerMessageColor(HSQUIRRELVM vm, Int32 idx, Uint32 & color, Int
static SQInteger SqBroadcastMsg(HSQUIRRELVM vm)
{
// The function needs at least 2 arguments
const auto top = static_cast< Int32 >(sq_gettop(vm));
const auto top = static_cast< int32_t >(sq_gettop(vm));
// Was the message color specified?
if (top <= 1)
{
@ -247,11 +247,11 @@ static SQInteger SqBroadcastMsg(HSQUIRRELVM vm)
}
// The index where the message should start
Int32 msgidx = 2;
int32_t msg_idx = 2;
// The message color
Uint32 color = 0;
uint32_t color = 0;
// Attempt to identify and extract the color
const SQRESULT res = SqGrabPlayerMessageColor(vm, 2, color, msgidx);
const SQRESULT res = SqGrabPlayerMessageColor(vm, 2, color, msg_idx);
// Did we fail to identify a color?
if (SQ_FAILED(res))
{
@ -259,7 +259,7 @@ static SQInteger SqBroadcastMsg(HSQUIRRELVM vm)
}
// Attempt to generate the string value
StackStrF val(vm, msgidx);
StackStrF val(vm, msg_idx);
// Have we failed to retrieve the string?
if (SQ_FAILED(val.Proc(true)))
{
@ -270,9 +270,9 @@ static SQInteger SqBroadcastMsg(HSQUIRRELVM vm)
auto itr = Core::Get().GetPlayers().cbegin();
auto end = Core::Get().GetPlayers().cend();
// The number of players that the message was sent to
Uint32 count = 0;
uint32_t count = 0;
// Currently processed player
CPlayer * player = nullptr;
CPlayer * player;
// Process each entity in the pool
for (; itr != end; ++itr)
@ -291,7 +291,7 @@ static SQInteger SqBroadcastMsg(HSQUIRRELVM vm)
// Check the result
if (result == vcmpErrorTooLargeInput)
{
return sq_throwerror(vm, ToStrF("Client message too big [%s]", player->GetTag().c_str()));
return sq_throwerrorf(vm, "Client message too big [%s]", player->GetTag().c_str());
}
// Add this player to the count
++count;
@ -307,7 +307,7 @@ static SQInteger SqBroadcastMsg(HSQUIRRELVM vm)
// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastMsgP(HSQUIRRELVM vm)
{
const auto top = static_cast< Int32 >(sq_gettop(vm));
const auto top = static_cast< int32_t >(sq_gettop(vm));
// Was the index of the message prefix specified?
if (top <= 1)
{
@ -320,13 +320,13 @@ static SQInteger SqBroadcastMsgP(HSQUIRRELVM vm)
}
// The prefix index
Uint32 index = 0;
uint32_t index;
// Attempt to extract the argument values
try
{
index = ConvTo< Uint32 >::From(Var< SQInteger >(vm, 2).value);
index = ConvTo< uint32_t >::From(Var< SQInteger >(vm, 2).value);
}
catch (const Sqrat::Exception & e)
catch (const std::exception & e)
{
return sq_throwerror(vm, e.what());
}
@ -334,8 +334,8 @@ static SQInteger SqBroadcastMsgP(HSQUIRRELVM vm)
// Perform a range check on the specified prefix index
if (index >= SQMOD_PLAYER_MSG_PREFIXES)
{
return sq_throwerror(vm, ToStrF("Prefix index is out of range: %u >= %u",
index, SQMOD_PLAYER_MSG_PREFIXES));
return sq_throwerrorf(vm, "Prefix index is out of range: %u >= %u",
index, SQMOD_PLAYER_MSG_PREFIXES);
}
// Attempt to generate the string value
@ -351,9 +351,9 @@ static SQInteger SqBroadcastMsgP(HSQUIRRELVM vm)
auto itr = Core::Get().GetPlayers().cbegin();
auto end = Core::Get().GetPlayers().cend();
// The number of players that the message was sent to
Uint32 count = 0;
uint32_t count = 0;
// Currently processed player
CPlayer * player = nullptr;
CPlayer * player;
// Process each entity in the pool
for (; itr != end; ++itr)
@ -379,7 +379,7 @@ static SQInteger SqBroadcastMsgP(HSQUIRRELVM vm)
// Check the result
if (result == vcmpErrorTooLargeInput)
{
return sq_throwerror(vm, ToStrF("Client message too big [%s]", player->GetTag().c_str()));
return sq_throwerrorf(vm, "Client message too big [%s]", player->GetTag().c_str());
}
// Add this player to the count
++count;
@ -395,7 +395,7 @@ static SQInteger SqBroadcastMsgP(HSQUIRRELVM vm)
// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)
{
const auto top = static_cast< Int32 >(sq_gettop(vm));
const auto top = static_cast< int32_t >(sq_gettop(vm));
// Was the index of the message prefix specified?
if (top <= 1)
{
@ -413,13 +413,13 @@ static SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)
}
// The prefix index
Uint32 index = 0;
uint32_t index;
// Attempt to extract the argument values
try
{
index = ConvTo< Uint32 >::From(Var< SQInteger >(vm, 2).value);
index = ConvTo< uint32_t >::From(Var< SQInteger >(vm, 2).value);
}
catch (const Sqrat::Exception & e)
catch (const std::exception & e)
{
return sq_throwerror(vm, e.what());
}
@ -427,16 +427,16 @@ static SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)
// Perform a range check on the specified prefix index
if (index >= SQMOD_PLAYER_MSG_PREFIXES)
{
return sq_throwerror(vm, ToStrF("Prefix index is out of range: %u >= %u",
index, SQMOD_PLAYER_MSG_PREFIXES));
return sq_throwerrorf(vm, "Prefix index is out of range: %u >= %u",
index, SQMOD_PLAYER_MSG_PREFIXES);
}
// The index where the message should start
Int32 msgidx = 3;
int32_t msg_idx = 3;
// The message color
Uint32 color = 0;
uint32_t color = 0;
// Attempt to identify and extract the color
const SQRESULT res = SqGrabPlayerMessageColor(vm, 3, color, msgidx);
const SQRESULT res = SqGrabPlayerMessageColor(vm, 3, color, msg_idx);
// Did we fail to identify a color?
if (SQ_FAILED(res))
{
@ -444,7 +444,7 @@ static SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)
}
// Attempt to generate the string value
StackStrF val(vm, msgidx);
StackStrF val(vm, msg_idx);
// Have we failed to retrieve the string?
if (SQ_FAILED(val.Proc(true)))
{
@ -456,9 +456,9 @@ static SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)
auto itr = Core::Get().GetPlayers().cbegin();
auto end = Core::Get().GetPlayers().cend();
// The number of players that the message was sent to
Uint32 count = 0;
uint32_t count = 0;
// Currently processed player
CPlayer * player = nullptr;
CPlayer * player;
// Process each entity in the pool
for (; itr != end; ++itr)
@ -484,7 +484,7 @@ static SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)
// Check the result
if (result == vcmpErrorTooLargeInput)
{
return sq_throwerror(vm, ToStrF("Client message too big [%s]", player->GetTag().c_str()));
return sq_throwerrorf(vm, "Client message too big [%s]", player->GetTag().c_str());
}
// Add this player to the count
++count;
@ -500,7 +500,7 @@ static SQInteger SqBroadcastMsgEx(HSQUIRRELVM vm)
// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastMessage(HSQUIRRELVM vm)
{
const auto top = static_cast< Int32 >(sq_gettop(vm));
const auto top = static_cast< int32_t >(sq_gettop(vm));
// Was the message value specified?
if (top <= 1)
{
@ -519,9 +519,9 @@ static SQInteger SqBroadcastMessage(HSQUIRRELVM vm)
auto itr = Core::Get().GetPlayers().cbegin();
auto end = Core::Get().GetPlayers().cend();
// The number of players that the message was sent to
Uint32 count = 0;
uint32_t count = 0;
// Currently processed player
CPlayer * player = nullptr;
CPlayer * player;
// Process each entity in the pool
for (; itr != end; ++itr)
@ -540,7 +540,7 @@ static SQInteger SqBroadcastMessage(HSQUIRRELVM vm)
// Check the result
if (result == vcmpErrorTooLargeInput)
{
return sq_throwerror(vm, ToStrF("Client message too big [%s]", player->GetTag().c_str()));
return sq_throwerrorf(vm, "Client message too big [%s]", player->GetTag().c_str());
}
// Add this player to the count
++count;
@ -556,7 +556,7 @@ static SQInteger SqBroadcastMessage(HSQUIRRELVM vm)
// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastAnnounce(HSQUIRRELVM vm)
{
const auto top = static_cast< Int32 >(sq_gettop(vm));
const auto top = static_cast< int32_t >(sq_gettop(vm));
// Was the announcement value specified?
if (top <= 1)
{
@ -575,9 +575,9 @@ static SQInteger SqBroadcastAnnounce(HSQUIRRELVM vm)
auto itr = Core::Get().GetPlayers().cbegin();
auto end = Core::Get().GetPlayers().cend();
// The number of players that the message was sent to
Uint32 count = 0;
uint32_t count = 0;
// Currently processed player
CPlayer * player = nullptr;
CPlayer * player;
// Process each entity in the pool
for (; itr != end; ++itr)
@ -596,12 +596,12 @@ static SQInteger SqBroadcastAnnounce(HSQUIRRELVM vm)
// Validate the result
if (result == vcmpErrorArgumentOutOfBounds)
{
return sq_throwerror(vm, ToStrF("Invalid announcement style %d [%s]",
player->mAnnounceStyle, player->GetTag().c_str()));
return sq_throwerrorf(vm, "Invalid announcement style %d [%s]",
player->mAnnounceStyle, player->GetTag().c_str());
}
else if (result == vcmpErrorTooLargeInput)
{
return sq_throwerror(vm, ToStrF("Game message too big [%s]", player->GetTag().c_str()));
return sq_throwerrorf(vm, "Game message too big [%s]", player->GetTag().c_str());
}
// Add this player to the count
++count;
@ -617,7 +617,7 @@ static SQInteger SqBroadcastAnnounce(HSQUIRRELVM vm)
// ------------------------------------------------------------------------------------------------
static SQInteger SqBroadcastAnnounceEx(HSQUIRRELVM vm)
{
const auto top = static_cast< Int32 >(sq_gettop(vm));
const auto top = static_cast< int32_t >(sq_gettop(vm));
// Was the announcement style specified?
if (top <= 1)
{
@ -629,13 +629,13 @@ static SQInteger SqBroadcastAnnounceEx(HSQUIRRELVM vm)
return sq_throwerror(vm, "Missing announcement value");
}
Int32 style;
int32_t style;
// style to extract the argument values
try
{
style = Var< Int32 >(vm, 2).value;
style = Var< int32_t >(vm, 2).value;
}
catch (const Sqrat::Exception & e)
catch (const std::exception & e)
{
return sq_throwerror(vm, e.what());
}
@ -652,9 +652,9 @@ static SQInteger SqBroadcastAnnounceEx(HSQUIRRELVM vm)
auto itr = Core::Get().GetPlayers().cbegin();
auto end = Core::Get().GetPlayers().cend();
// The number of players that the message was sent to
Uint32 count = 0;
uint32_t count = 0;
// Currently processed player
CPlayer * player = nullptr;
CPlayer * player;
// Process each entity in the pool
for (; itr != end; ++itr)
@ -673,12 +673,12 @@ static SQInteger SqBroadcastAnnounceEx(HSQUIRRELVM vm)
// Validate the result
if (result == vcmpErrorArgumentOutOfBounds)
{
return sq_throwerror(vm, ToStrF("Invalid announcement style %d [%s]",
style, player->GetTag().c_str()));
return sq_throwerrorf(vm, "Invalid announcement style %d [%s]",
style, player->GetTag().c_str());
}
else if (result == vcmpErrorTooLargeInput)
{
return sq_throwerror(vm, ToStrF("Game message too big [%s]", player->GetTag().c_str()));
return sq_throwerrorf(vm, "Game message too big [%s]", player->GetTag().c_str());
}
// Add this player to the count
++count;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
#include "Core/Common.hpp"
// ------------------------------------------------------------------------------------------------
#include <limits>
#include <sqratConst.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -18,14 +18,14 @@ static const EnumElement g_SqMod[] = {
{_SC("Platform"), SQMOD_PLATFORM},
{_SC("MinChar"), std::numeric_limits< SQChar >::min()},
{_SC("MaxChar"), std::numeric_limits< SQChar >::max()},
{_SC("MinAchar"), std::numeric_limits< Int8 >::min()},
{_SC("MaxAchar"), std::numeric_limits< Int8 >::max()},
{_SC("MinByte"), std::numeric_limits< Uint8 >::min()},
{_SC("MaxByte"), std::numeric_limits< Uint8 >::max()},
{_SC("MinShort"), std::numeric_limits< Int16 >::min()},
{_SC("MaxShort"), std::numeric_limits< Int16 >::max()},
{_SC("MinWord"), std::numeric_limits< Uint16 >::min()},
{_SC("MaxWord"), std::numeric_limits< Uint16 >::max()},
{_SC("MinAchar"), std::numeric_limits< int8_t >::min()},
{_SC("MaxAchar"), std::numeric_limits< int8_t >::max()},
{_SC("MinByte"), std::numeric_limits< uint8_t >::min()},
{_SC("MaxByte"), std::numeric_limits< uint8_t >::max()},
{_SC("MinShort"), std::numeric_limits< int16_t >::min()},
{_SC("MaxShort"), std::numeric_limits< int16_t >::max()},
{_SC("MinWord"), std::numeric_limits< uint16_t >::min()},
{_SC("MaxWord"), std::numeric_limits< uint16_t >::max()},
{_SC("MinInt"), std::numeric_limits< SQInteger >::min()},
{_SC("MaxInt"), std::numeric_limits< SQInteger >::max()},
{_SC("MinInteger"), std::numeric_limits< SQInteger >::min()},
@ -34,8 +34,8 @@ static const EnumElement g_SqMod[] = {
{_SC("MaxInt32"), std::numeric_limits< SQInt32 >::max()},
{_SC("MinFloat"), std::numeric_limits< SQFloat >::min()},
{_SC("MaxFloat"), std::numeric_limits< SQFloat >::max()},
{_SC("MinFloat32"), std::numeric_limits< Float32 >::min()},
{_SC("MaxFloat32"), std::numeric_limits< Float32 >::max()},
{_SC("MinFloat32"), std::numeric_limits< float >::min()},
{_SC("MaxFloat32"), std::numeric_limits< float >::max()},
{_SC("FpNormal"), FP_NORMAL},
{_SC("FpSubnormal"), FP_SUBNORMAL}, // NOLINT(hicpp-signed-bitwise)
{_SC("FpZero"), FP_ZERO},

View File

@ -1,303 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Core.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstring>
// ------------------------------------------------------------------------------------------------
#include <sqstdio.h>
#include <sqstdblob.h>
#include <sqstdstring.h>
#include <sqmodapi.h>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
static HSQUIRRELVM GetSquirrelVM()
{
return Core::Get().GetVM();
}
// ------------------------------------------------------------------------------------------------
static SQRESULT SqModImpl_LoadScript(const SQChar * filepath, SQBool delay)
{
// Attempt to add the specified script to the load queue
if (Core::Get().LoadScript(filepath, static_cast< bool >(delay)))
{
return SQ_OK; // The script as added or already existed
}
// The path was invalid or was unable to pool the script
return SQ_ERROR;
}
// ------------------------------------------------------------------------------------------------
static int32_t SqExport_PopulateModuleAPI(HSQMODAPI api, size_t size)
{
if (!api)
{
return 0; // Nothing to populate!
}
else if (size != sizeof(SQMODAPI))
{
return -1; // Incompatible API!
}
//primitive functions
api->GetSquirrelVM = GetSquirrelVM;
//logging utilities
api->LogDbg = LogDbg;
api->LogUsr = LogUsr;
api->LogScs = LogScs;
api->LogInf = LogInf;
api->LogWrn = LogWrn;
api->LogErr = LogErr;
api->LogFtl = LogFtl;
api->LogSDbg = LogSDbg;
api->LogSUsr = LogSUsr;
api->LogSScs = LogSScs;
api->LogSInf = LogSInf;
api->LogSWrn = LogSWrn;
api->LogSErr = LogSErr;
api->LogSFtl = LogSFtl;
api->LogDbgV = LogDbgV;
api->LogUsrV = LogUsrV;
api->LogScsV = LogScsV;
api->LogInfV = LogInfV;
api->LogWrnV = LogWrnV;
api->LogErrV = LogErrV;
api->LogFtlV = LogFtlV;
api->LogSDbgV = LogSDbgV;
api->LogSUsrV = LogSUsrV;
api->LogSScsV = LogSScsV;
api->LogSInfV = LogSInfV;
api->LogSWrnV = LogSWrnV;
api->LogSErrV = LogSErrV;
api->LogSFtlV = LogSFtlV;
//script loading
api->LoadScript = SqModImpl_LoadScript;
return 1; // Successfully populated!
}
// ------------------------------------------------------------------------------------------------
static int32_t SqExport_PopulateSquirrelAPI(HSQLIBAPI api, size_t size)
{
if (!api)
{
return 0; // Nothing to populate!
}
else if (size != sizeof(SQLIBAPI))
{
return -1; // Incompatible API!
}
//vm
api->open = sq_open;
api->newthread = sq_newthread;
api->seterrorhandler = sq_seterrorhandler;
api->close = sq_close;
api->setforeignptr = sq_setforeignptr;
api->getforeignptr = sq_getforeignptr;
api->setsharedforeignptr = sq_setsharedforeignptr;
api->getsharedforeignptr = sq_getsharedforeignptr;
api->setvmreleasehook = sq_setvmreleasehook;
api->getvmreleasehook = sq_getvmreleasehook;
api->setsharedreleasehook = sq_setsharedreleasehook;
api->getsharedreleasehook = sq_getsharedreleasehook;
api->setprintfunc = sq_setprintfunc;
api->getprintfunc = sq_getprintfunc;
api->geterrorfunc = sq_geterrorfunc;
api->suspendvm = sq_suspendvm;
api->wakeupvm = sq_wakeupvm;
api->getvmstate = sq_getvmstate;
api->getversion = sq_getversion;
//compiler
api->compile = sq_compile;
api->compilebuffer = sq_compilebuffer;
api->enabledebuginfo = sq_enabledebuginfo;
api->notifyallexceptions = sq_notifyallexceptions;
api->setcompilererrorhandler = sq_setcompilererrorhandler;
//stack operations
api->push = sq_push;
api->pop = sq_pop;
api->poptop = sq_poptop;
api->remove = sq_remove;
api->gettop = sq_gettop;
api->settop = sq_settop;
api->reservestack = sq_reservestack;
api->cmp = sq_cmp;
api->move = sq_move;
//object creation handling
api->newuserdata = sq_newuserdata;
api->newtable = sq_newtable;
api->newtableex = sq_newtableex;
api->newarray = sq_newarray;
api->newclosure = sq_newclosure;
api->setparamscheck = sq_setparamscheck;
api->bindenv = sq_bindenv;
api->setclosureroot = sq_setclosureroot;
api->getclosureroot = sq_getclosureroot;
api->pushstring = sq_pushstring;
api->pushstringf = sq_pushstringf;
api->pushfloat = sq_pushfloat;
api->pushinteger = sq_pushinteger;
api->pushbool = sq_pushbool;
api->pushuserpointer = sq_pushuserpointer;
api->pushnull = sq_pushnull;
api->pushthread = sq_pushthread;
api->gettype = sq_gettype;
api->typeof_ = sq_typeof;
api->getsize = sq_getsize;
api->gethash = sq_gethash;
api->getbase = sq_getbase;
api->instanceof = sq_instanceof;
api->tostring = sq_tostring;
api->tobool = sq_tobool;
api->getstringandsize = sq_getstringandsize;
api->getstring = sq_getstring;
api->getinteger = sq_getinteger;
api->getfloat = sq_getfloat;
api->getbool = sq_getbool;
api->getthread = sq_getthread;
api->getuserpointer = sq_getuserpointer;
api->getuserdata = sq_getuserdata;
api->settypetag = sq_settypetag;
api->gettypetag = sq_gettypetag;
api->setreleasehook = sq_setreleasehook;
api->getreleasehook = sq_getreleasehook;
api->getscratchpad = sq_getscratchpad;
api->getfunctioninfo = sq_getfunctioninfo;
api->getclosureinfo = sq_getclosureinfo;
api->getclosurename = sq_getclosurename;
api->setnativeclosurename = sq_setnativeclosurename;
api->getnativeclosurepointer = sq_getnativeclosurepointer;
api->setinstanceup = sq_setinstanceup;
api->getinstanceup = sq_getinstanceup;
api->setclassudsize = sq_setclassudsize;
api->newclass = sq_newclass;
api->createinstance = sq_createinstance;
api->setattributes = sq_setattributes;
api->getattributes = sq_getattributes;
api->getclass = sq_getclass;
api->weakref = sq_weakref;
api->getdefaultdelegate = sq_getdefaultdelegate;
api->getmemberhandle = sq_getmemberhandle;
api->getbyhandle = sq_getbyhandle;
api->setbyhandle = sq_setbyhandle;
//object manipulation
api->pushroottable = sq_pushroottable;
api->pushregistrytable = sq_pushregistrytable;
api->pushconsttable = sq_pushconsttable;
api->setroottable = sq_setroottable;
api->setconsttable = sq_setconsttable;
api->newslot = sq_newslot;
api->deleteslot = sq_deleteslot;
api->set = sq_set;
api->get = sq_get;
api->rawget = sq_rawget;
api->rawset = sq_rawset;
api->rawdeleteslot = sq_rawdeleteslot;
api->newmember = sq_newmember;
api->rawnewmember = sq_rawnewmember;
api->arrayappend = sq_arrayappend;
api->arraypop = sq_arraypop;
api->arrayresize = sq_arrayresize;
api->arrayreverse = sq_arrayreverse;
api->arrayremove = sq_arrayremove;
api->arrayinsert = sq_arrayinsert;
api->setdelegate = sq_setdelegate;
api->getdelegate = sq_getdelegate;
api->clone = sq_clone;
api->setfreevariable = sq_setfreevariable;
api->next = sq_next;
api->getweakrefval = sq_getweakrefval;
api->clear = sq_clear;
//calls
api->call = sq_call;
api->resume = sq_resume;
api->getlocal = sq_getlocal;
api->getcallee = sq_getcallee;
api->getfreevariable = sq_getfreevariable;
api->getonefreevariable = sq_getonefreevariable;
api->throwerror = sq_throwerror;
api->throwerrorf = sq_throwerrorf;
api->throwobject = sq_throwobject;
api->reseterror = sq_reseterror;
api->getlasterror = sq_getlasterror;
//raw object handling
api->getstackobj = sq_getstackobj;
api->pushobject = sq_pushobject;
api->addref = sq_addref;
api->release = sq_release;
api->getrefcount = sq_getrefcount;
api->resetobject = sq_resetobject;
api->objtostring = sq_objtostring;
api->objtobool = sq_objtobool;
api->objtointeger = sq_objtointeger;
api->objtofloat = sq_objtofloat;
api->objtouserpointer = sq_objtouserpointer;
api->getobjtypetag = sq_getobjtypetag;
api->getvmrefcount = sq_getvmrefcount;
//GC
api->collectgarbage = sq_collectgarbage;
api->resurrectunreachable = sq_resurrectunreachable;
//serialization
api->writeclosure = sq_writeclosure;
api->readclosure = sq_readclosure;
//mem allocation
api->malloc = sq_malloc;
api->realloc = sq_realloc;
api->free = sq_free;
//debug
api->stackinfos = sq_stackinfos;
api->setdebughook = sq_setdebughook;
api->setnativedebughook = sq_setnativedebughook;
//compiler helpers
api->loadfile = sqstd_loadfile;
api->dofile = sqstd_dofile;
api->writeclosuretofile = sqstd_writeclosuretofile;
//blob
api->createblob = sqstd_createblob;
api->getblob = sqstd_getblob;
api->getblobsize = sqstd_getblobsize;
//string
api->format = sqstd_format;
return 1; // Successfully populated!
}
// ------------------------------------------------------------------------------------------------
static const SQMODEXPORTS g_SqModExports{
sizeof(SQMODEXPORTS),
SqExport_PopulateModuleAPI,
SqExport_PopulateSquirrelAPI
};
// ------------------------------------------------------------------------------------------------
void InitExports()
{
// The server needs a pointer to a pointer, and a persistent one
static const SQMODEXPORTS * sqmodexports = &g_SqModExports;
// Tell the server about the pointer to the exports structure
_Func->ExportFunctions(_Info->pluginId, reinterpret_cast< const void ** >(&sqmodexports),
sizeof(HSQMODEXPORTS));
}
} // Namespace:: SqMod

View File

@ -1,12 +1,10 @@
// ------------------------------------------------------------------------------------------------
#include "Misc/Functions.hpp"
#include "Base/Shared.hpp"
#include "Core.hpp"
#include "Base/Color3.hpp"
#include "Base/Vector2.hpp"
#include "Base/Vector3.hpp"
#include "Entity/Player.hpp"
#include "Core.hpp"
#include "Library/Numeric/LongInt.hpp"
#include "Library/Numeric/Long.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -17,9 +15,9 @@ namespace SqMod {
struct District
{
// District boundaries.
Float32 mMinX, mMinY, mMaxX, mMaxY;
float mMinX, mMinY, mMaxX, mMaxY;
// District name
CSStr mName;
const SQChar * mName;
};
// ------------------------------------------------------------------------------------------------
@ -48,7 +46,7 @@ static const District g_Districts[] = {
};
// ------------------------------------------------------------------------------------------------
static String CS_Keycode_Names[] = {"", /* index 0 is not used */
static String CS_Keycode_Names[] = {"", /* index 0 is not used */ // NOLINT(cert-err58-cpp)
"Left Button **", "Right Button **", "Break", "Middle Button **", "X Button 1 **",
"X Button 2 **", "", "Backspace", "Tab", "",
"", "Clear", "Enter", "", "",
@ -103,19 +101,19 @@ static String CS_Keycode_Names[] = {"", /* index 0 is not used */
};
// ------------------------------------------------------------------------------------------------
CSStr GetKeyCodeName(Uint8 keycode)
const SQChar * GetKeyCodeName(uint8_t keycode)
{
return CS_Keycode_Names[keycode].c_str();
}
// ------------------------------------------------------------------------------------------------
void SetKeyCodeName(Uint8 keycode, StackStrF & name)
void SetKeyCodeName(uint8_t keycode, StackStrF & name)
{
CS_Keycode_Names[keycode].assign(name.mPtr);
}
// ------------------------------------------------------------------------------------------------
Uint32 GetServerVersion()
uint32_t GetServerVersion()
{
return _Func->GetServerVersion();
}
@ -137,13 +135,13 @@ Table GetServerSettings()
}
// ------------------------------------------------------------------------------------------------
Uint32 GetNumberOfPlugins()
uint32_t GetNumberOfPlugins()
{
return _Func->GetNumberOfPlugins();
}
// ------------------------------------------------------------------------------------------------
Table GetPluginInfo(Int32 plugin_id)
Table GetPluginInfo(int32_t plugin_id)
{
// Attempt to update the plug-in info structure
if (_Func->GetPluginInfo(plugin_id, &g_PluginInfo) == vcmpErrorNoSuchEntity)
@ -163,13 +161,13 @@ Table GetPluginInfo(Int32 plugin_id)
}
// ------------------------------------------------------------------------------------------------
Int32 FindPlugin(StackStrF & name)
int32_t FindPlugin(StackStrF & name)
{
return _Func->FindPlugin(name.mPtr);
}
// ------------------------------------------------------------------------------------------------
void SendPluginCommand(Uint32 identifier, StackStrF & payload)
void SendPluginCommand(uint32_t identifier, StackStrF & payload)
{
_Func->SendPluginCommand(identifier, payload.mPtr);
}
@ -190,43 +188,43 @@ void SendLogMessage(StackStrF & msg)
}
// ------------------------------------------------------------------------------------------------
Int32 GetLastError()
int32_t GetLastError()
{
return _Func->GetLastError();
}
// ------------------------------------------------------------------------------------------------
Uint32 GetPluginVersion()
uint32_t GetPluginVersion()
{
return SQMOD_VERSION;
}
// ------------------------------------------------------------------------------------------------
CSStr GetPluginVersionStr()
const SQChar * GetPluginVersionStr()
{
return SQMOD_VERSION_STR;
}
// ------------------------------------------------------------------------------------------------
CSStr GetPluginName()
const SQChar * GetPluginName()
{
return SQMOD_NAME;
}
// ------------------------------------------------------------------------------------------------
CSStr GetPluginAuthor()
const SQChar * GetPluginAuthor()
{
return SQMOD_AUTHOR;
}
// ------------------------------------------------------------------------------------------------
Int32 GetPluginID()
int32_t GetPluginID()
{
return _Info->pluginId;
}
// ------------------------------------------------------------------------------------------------
Uint32 GetServerPort()
uint32_t GetServerPort()
{
// Update the server settings structure
_Func->GetServerSettings(&g_SvSettings);
@ -235,7 +233,7 @@ Uint32 GetServerPort()
}
// ------------------------------------------------------------------------------------------------
Uint32 GetServerFlags()
uint32_t GetServerFlags()
{
// Update the server settings structure
_Func->GetServerSettings(&g_SvSettings);
@ -244,19 +242,19 @@ Uint32 GetServerFlags()
}
// ------------------------------------------------------------------------------------------------
Int32 GetMaxPlayers()
int32_t GetMaxPlayers()
{
return _Func->GetMaxPlayers();
}
// ------------------------------------------------------------------------------------------------
void SetMaxPlayers(Int32 max)
void SetMaxPlayers(int32_t max)
{
_Func->SetMaxPlayers(static_cast< uint32_t >(max));
}
// ------------------------------------------------------------------------------------------------
CSStr GetServerName()
const SQChar * GetServerName()
{
// The server is retarded and returns `vcmpErrorBufferTooSmall` regardless of the buffer size.
// Populate the buffer
@ -283,7 +281,7 @@ void SetServerName(StackStrF & name)
}
// ------------------------------------------------------------------------------------------------
CSStr GetServerPassword()
const SQChar * GetServerPassword()
{
// The server is retarded and returns `vcmpErrorBufferTooSmall` regardless of the buffer size.
// Populate the buffer
@ -310,7 +308,7 @@ void SetServerPassword(StackStrF & passwd)
}
// ------------------------------------------------------------------------------------------------
CSStr GetGameModeText()
const SQChar * GetGameModeText()
{
// The server is retarded and returns `vcmpErrorBufferTooSmall` regardless of the buffer size.
// Populate the buffer
@ -343,13 +341,13 @@ SQInteger CreateRadioStream(bool listed, StackStrF & name, StackStrF & url)
}
// ------------------------------------------------------------------------------------------------
SQInteger CreateRadioStreamEx(Int32 id, bool listed, StackStrF & name, StackStrF & url)
SQInteger CreateRadioStreamEx(int32_t id, bool listed, StackStrF & name, StackStrF & url)
{
return static_cast< SQInteger >(_Func->AddRadioStream(id, name.mPtr, url.mPtr, static_cast< uint8_t >(listed)));
}
// ------------------------------------------------------------------------------------------------
void RemoveRadioStream(Int32 id)
void RemoveRadioStream(int32_t id)
{
if (_Func->RemoveRadioStream(id) == vcmpErrorNoSuchEntity)
{
@ -364,7 +362,7 @@ void ShutdownServer()
}
// ------------------------------------------------------------------------------------------------
bool GetServerOption(Int32 option_id)
bool GetServerOption(int32_t option_id)
{
// Attempt to obtain the current value of the specified option
const bool value = _Func->GetServerOption(static_cast< vcmpServerOption >(option_id));
@ -378,7 +376,7 @@ bool GetServerOption(Int32 option_id)
}
// ------------------------------------------------------------------------------------------------
void SetServerOption(Int32 option_id, bool toggle)
void SetServerOption(int32_t option_id, bool toggle)
{
if (_Func->SetServerOption(static_cast< vcmpServerOption >(option_id),
static_cast< uint8_t >(toggle)) == vcmpErrorArgumentOutOfBounds)
@ -392,7 +390,7 @@ void SetServerOption(Int32 option_id, bool toggle)
}
// ------------------------------------------------------------------------------------------------
void SetServerOptionEx(Int32 option_id, bool toggle, Int32 header, LightObj & payload)
void SetServerOptionEx(int32_t option_id, bool toggle, int32_t header, LightObj & payload)
{
if (_Func->SetServerOption(static_cast< vcmpServerOption >(option_id),
static_cast< uint8_t >(toggle)) == vcmpErrorArgumentOutOfBounds)
@ -427,15 +425,15 @@ void SetWorldBounds(const Vector2 & max, const Vector2 & min)
}
// ------------------------------------------------------------------------------------------------
void SetWorldBoundsEx(Float32 max_x, Float32 max_y, Float32 min_x, Float32 min_y)
void SetWorldBoundsEx(float max_x, float max_y, float min_x, float min_y)
{
_Func->SetWorldBounds(max_x, min_x, max_y, min_y);
}
Table GetWastedSettings()
{
Uint32 fc, dt, ft, cfs, cft;
Float32 fis, fos;
uint32_t fc, dt, ft, cfs, cft;
float fis, fos;
Color3 c;
// Retrieve the current wasted settings bounds
_Func->GetWastedSettings(&dt, &ft, &fis, &fos, &fc, &cfs, &cft);
@ -457,134 +455,134 @@ Table GetWastedSettings()
}
// ------------------------------------------------------------------------------------------------
void SetWastedSettings(Uint32 dt, Uint32 ft, Float32 fis, Float32 fos,
const Color3 & fc, Uint32 cfs, Uint32 cft)
void SetWastedSettings(uint32_t dt, uint32_t ft, float fis, float fos,
const Color3 & fc, uint32_t cfs, uint32_t cft)
{
_Func->SetWastedSettings(dt, ft, fis, fos, fc.GetRGB(), cfs, cft);
}
// ------------------------------------------------------------------------------------------------
Int32 GetTimeRate()
int32_t GetTimeRate()
{
return _Func->GetTimeRate();
}
// ------------------------------------------------------------------------------------------------
void SetTimeRate(Uint32 rate)
void SetTimeRate(uint32_t rate)
{
_Func->SetTimeRate(rate);
}
// ------------------------------------------------------------------------------------------------
Int32 GetHour()
int32_t GetHour()
{
return _Func->GetHour();
}
// ------------------------------------------------------------------------------------------------
void SetHour(Int32 hour)
void SetHour(int32_t hour)
{
_Func->SetHour(hour);
}
// ------------------------------------------------------------------------------------------------
Int32 GetMinute()
int32_t GetMinute()
{
return _Func->GetMinute();
}
// ------------------------------------------------------------------------------------------------
void SetMinute(Int32 minute)
void SetMinute(int32_t minute)
{
_Func->SetMinute(minute);
}
// ------------------------------------------------------------------------------------------------
Int32 GetWeather()
int32_t GetWeather()
{
return _Func->GetWeather();
}
// ------------------------------------------------------------------------------------------------
void SetWeather(Int32 weather)
void SetWeather(int32_t weather)
{
_Func->SetWeather(weather);
}
// ------------------------------------------------------------------------------------------------
Float32 GetGravity()
float GetGravity()
{
return _Func->GetGravity();
}
// ------------------------------------------------------------------------------------------------
void SetGravity(Float32 gravity)
void SetGravity(float gravity)
{
_Func->SetGravity(gravity);
}
// ------------------------------------------------------------------------------------------------
Float32 GetGameSpeed()
float GetGameSpeed()
{
return _Func->GetGameSpeed();
}
// ------------------------------------------------------------------------------------------------
void SetGameSpeed(Float32 speed)
void SetGameSpeed(float speed)
{
_Func->SetGameSpeed(speed);
}
// ------------------------------------------------------------------------------------------------
Float32 GetWaterLevel()
float GetWaterLevel()
{
return _Func->GetWaterLevel();
}
// ------------------------------------------------------------------------------------------------
void SetWaterLevel(Float32 level)
void SetWaterLevel(float level)
{
_Func->SetWaterLevel(level);
}
// ------------------------------------------------------------------------------------------------
Float32 GetMaximumFlightAltitude()
float GetMaximumFlightAltitude()
{
return _Func->GetMaximumFlightAltitude();
}
// ------------------------------------------------------------------------------------------------
void SetMaximumFlightAltitude(Float32 height)
void SetMaximumFlightAltitude(float height)
{
_Func->SetMaximumFlightAltitude(height);
}
// ------------------------------------------------------------------------------------------------
Int32 GetKillCommandDelay()
int32_t GetKillCommandDelay()
{
return _Func->GetKillCommandDelay();
}
// ------------------------------------------------------------------------------------------------
void SetKillCommandDelay(Int32 delay)
void SetKillCommandDelay(int32_t delay)
{
_Func->SetKillCommandDelay(delay);
}
// ------------------------------------------------------------------------------------------------
Float32 GetVehiclesForcedRespawnHeight()
float GetVehiclesForcedRespawnHeight()
{
return _Func->GetVehiclesForcedRespawnHeight();
}
// ------------------------------------------------------------------------------------------------
void SetVehiclesForcedRespawnHeight(Float32 height)
void SetVehiclesForcedRespawnHeight(float height)
{
_Func->SetVehiclesForcedRespawnHeight(height);
}
// ------------------------------------------------------------------------------------------------
void CreateExplosion(Int32 world, Int32 type, const Vector3 & pos, CPlayer & source, bool grounded)
void CreateExplosion(int32_t world, int32_t type, const Vector3 & pos, CPlayer & source, bool grounded)
{
if (_Func->CreateExplosion(world, type, pos.x, pos.y, pos.z,
source.GetID(), static_cast< uint8_t >(grounded)) == vcmpErrorArgumentOutOfBounds)
@ -594,7 +592,7 @@ void CreateExplosion(Int32 world, Int32 type, const Vector3 & pos, CPlayer & sou
}
// ------------------------------------------------------------------------------------------------
void CreateExplosionEx(Int32 world, Int32 type, Float32 x, Float32 y, Float32 z, CPlayer & source, bool grounded)
void CreateExplosionEx(int32_t world, int32_t type, float x, float y, float z, CPlayer & source, bool grounded)
{
if (_Func->CreateExplosion(world, type, x, y, z,
source.GetID(), static_cast< uint8_t >(grounded)) == vcmpErrorArgumentOutOfBounds)
@ -604,7 +602,7 @@ void CreateExplosionEx(Int32 world, Int32 type, Float32 x, Float32 y, Float32 z,
}
// ------------------------------------------------------------------------------------------------
void PlaySound(Int32 world, Int32 sound, const Vector3 & pos)
void PlaySound(int32_t world, int32_t sound, const Vector3 & pos)
{
if (_Func->PlaySound(world, sound, pos.x, pos.y, pos.z) == vcmpErrorArgumentOutOfBounds)
{
@ -613,7 +611,7 @@ void PlaySound(Int32 world, Int32 sound, const Vector3 & pos)
}
// ------------------------------------------------------------------------------------------------
void PlaySoundEx(Int32 world, Int32 sound, Float32 x, Float32 y, Float32 z)
void PlaySoundEx(int32_t world, int32_t sound, float x, float y, float z)
{
if (_Func->PlaySound(world, sound, x, y, z) == vcmpErrorArgumentOutOfBounds)
{
@ -622,7 +620,7 @@ void PlaySoundEx(Int32 world, Int32 sound, Float32 x, Float32 y, Float32 z)
}
// ------------------------------------------------------------------------------------------------
void PlaySoundForWorld(Int32 world, Int32 sound)
void PlaySoundForWorld(int32_t world, int32_t sound)
{
if (_Func->PlaySound(world, sound, NAN, NAN, NAN) == vcmpErrorArgumentOutOfBounds)
{
@ -631,89 +629,89 @@ void PlaySoundForWorld(Int32 world, Int32 sound)
}
// ------------------------------------------------------------------------------------------------
void HideMapObject(Int32 model, const Vector3 & pos)
void HideMapObject(int32_t model, const Vector3 & pos)
{
_Func->HideMapObject(model,
static_cast< Int16 >(std::lround(std::floor(pos.x * 10.0f) + 0.5f)),
static_cast< Int16 >(std::lround(std::floor(pos.y * 10.0f) + 0.5f)),
static_cast< Int16 >(std::lround(std::floor(pos.z * 10.0f) + 0.5f))
static_cast< int16_t >(std::lround(std::floor(pos.x * 10.0f) + 0.5f)),
static_cast< int16_t >(std::lround(std::floor(pos.y * 10.0f) + 0.5f)),
static_cast< int16_t >(std::lround(std::floor(pos.z * 10.0f) + 0.5f))
);
}
// ------------------------------------------------------------------------------------------------
void HideMapObjectEx(Int32 model, Float32 x, Float32 y, Float32 z)
void HideMapObjectEx(int32_t model, float x, float y, float z)
{
_Func->HideMapObject(model,
static_cast< Int16 >(std::lround(std::floor(x * 10.0f) + 0.5f)),
static_cast< Int16 >(std::lround(std::floor(y * 10.0f) + 0.5f)),
static_cast< Int16 >(std::lround(std::floor(z * 10.0f) + 0.5f))
static_cast< int16_t >(std::lround(std::floor(x * 10.0f) + 0.5f)),
static_cast< int16_t >(std::lround(std::floor(y * 10.0f) + 0.5f)),
static_cast< int16_t >(std::lround(std::floor(z * 10.0f) + 0.5f))
);
}
// ------------------------------------------------------------------------------------------------
void HideMapObjectRaw(Int32 model, Int16 x, Int16 y, Int16 z)
void HideMapObjectRaw(int32_t model, int16_t x, int16_t y, int16_t z)
{
_Func->HideMapObject(model, x, y, z);
}
// ------------------------------------------------------------------------------------------------
void ShowMapObject(Int32 model, const Vector3 & pos)
void ShowMapObject(int32_t model, const Vector3 & pos)
{
_Func->ShowMapObject(model,
static_cast< Int16 >(std::lround(std::floor(pos.x * 10.0f) + 0.5f)),
static_cast< Int16 >(std::lround(std::floor(pos.y * 10.0f) + 0.5f)),
static_cast< Int16 >(std::lround(std::floor(pos.z * 10.0f) + 0.5f))
static_cast< int16_t >(std::lround(std::floor(pos.x * 10.0f) + 0.5f)),
static_cast< int16_t >(std::lround(std::floor(pos.y * 10.0f) + 0.5f)),
static_cast< int16_t >(std::lround(std::floor(pos.z * 10.0f) + 0.5f))
);
}
// ------------------------------------------------------------------------------------------------
void ShowMapObjectEx(Int32 model, Float32 x, Float32 y, Float32 z)
void ShowMapObjectEx(int32_t model, float x, float y, float z)
{
_Func->ShowMapObject(model,
static_cast< Int16 >(std::lround(std::floor(x * 10.0f) + 0.5f)),
static_cast< Int16 >(std::lround(std::floor(y * 10.0f) + 0.5f)),
static_cast< Int16 >(std::lround(std::floor(z * 10.0f) + 0.5f))
static_cast< int16_t >(std::lround(std::floor(x * 10.0f) + 0.5f)),
static_cast< int16_t >(std::lround(std::floor(y * 10.0f) + 0.5f)),
static_cast< int16_t >(std::lround(std::floor(z * 10.0f) + 0.5f))
);
}
// ------------------------------------------------------------------------------------------------
void ShowMapObjectRaw(Int32 model, Int16 x, Int16 y, Int16 z)
void ShowMapObjectRaw(int32_t model, int16_t x, int16_t y, int16_t z)
{
_Func->ShowMapObject(model, x, y, z);
}
// ------------------------------------------------------------------------------------------------
void ShowAllMapObjects(void)
void ShowAllMapObjects()
{
_Func->ShowAllMapObjects();
}
// ------------------------------------------------------------------------------------------------
SQFloat GetWeaponDataValue(Int32 weapon, Int32 field)
SQFloat GetWeaponDataValue(int32_t weapon, int32_t field)
{
return ConvTo< SQFloat >::From(_Func->GetWeaponDataValue(weapon, field));
}
// ------------------------------------------------------------------------------------------------
bool SetWeaponDataValue(Int32 weapon, Int32 field, SQFloat value)
bool SetWeaponDataValue(int32_t weapon, int32_t field, SQFloat value)
{
return (_Func->SetWeaponDataValue(weapon, field, value) != vcmpErrorArgumentOutOfBounds);
}
// ------------------------------------------------------------------------------------------------
bool ResetWeaponDataValue(Int32 weapon, Int32 field)
bool ResetWeaponDataValue(int32_t weapon, int32_t field)
{
return (_Func->ResetWeaponDataValue(weapon, field) != vcmpErrorArgumentOutOfBounds);
}
// ------------------------------------------------------------------------------------------------
bool IsWeaponDataValueModified(Int32 weapon, Int32 field)
bool IsWeaponDataValueModified(int32_t weapon, int32_t field)
{
return _Func->IsWeaponDataValueModified(weapon, field);
}
// ------------------------------------------------------------------------------------------------
bool ResetWeaponData(Int32 weapon)
bool ResetWeaponData(int32_t weapon)
{
return (_Func->ResetWeaponData(weapon) != vcmpErrorArgumentOutOfBounds);
}
@ -725,8 +723,8 @@ void ResetAllWeaponData()
}
// ------------------------------------------------------------------------------------------------
Int32 AddPlayerClass(Int32 team, const Color3 & color, Int32 skin, const Vector3 & pos, Float32 angle,
Int32 wep1, Int32 ammo1, Int32 wep2, Int32 ammo2, Int32 wep3, Int32 ammo3)
int32_t AddPlayerClass(int32_t team, const Color3 & color, int32_t skin, const Vector3 & pos, float angle,
int32_t wep1, int32_t ammo1, int32_t wep2, int32_t ammo2, int32_t wep3, int32_t ammo3)
{
return _Func->AddPlayerClass(team, color.GetRGB(), skin, pos.x, pos.y, pos.z, angle,
wep1, ammo1, wep2, ammo2, wep3, ammo3);
@ -751,19 +749,19 @@ void SetSpawnCameraLookAt(const Vector3 & pos)
}
// ------------------------------------------------------------------------------------------------
void SetSpawnPlayerPositionEx(Float32 x, Float32 y, Float32 z)
void SetSpawnPlayerPositionEx(float x, float y, float z)
{
_Func->SetSpawnPlayerPosition(x, y, z);
}
// ------------------------------------------------------------------------------------------------
void SetSpawnCameraPositionEx(Float32 x, Float32 y, Float32 z)
void SetSpawnCameraPositionEx(float x, float y, float z)
{
_Func->SetSpawnCameraPosition(x, y, z);
}
// ------------------------------------------------------------------------------------------------
void SetSpawnCameraLookAtEx(Float32 x, Float32 y, Float32 z)
void SetSpawnCameraLookAtEx(float x, float y, float z)
{
_Func->SetSpawnPlayerPosition(x, y, z);
}
@ -771,29 +769,29 @@ void SetSpawnCameraLookAtEx(Float32 x, Float32 y, Float32 z)
// ------------------------------------------------------------------------------------------------
void BanIP(StackStrF & addr)
{
_Func->BanIP(const_cast< SStr >(addr.mPtr));
_Func->BanIP(const_cast< SQChar * >(addr.mPtr));
}
// ------------------------------------------------------------------------------------------------
bool UnbanIP(StackStrF & addr)
{
return _Func->UnbanIP(const_cast< SStr >(addr.mPtr));
return _Func->UnbanIP(const_cast< SQChar * >(addr.mPtr));
}
// ------------------------------------------------------------------------------------------------
bool IsIPBanned(StackStrF & addr)
{
return _Func->IsIPBanned(const_cast< SStr >(addr.mPtr));
return _Func->IsIPBanned(const_cast< SQChar * >(addr.mPtr));
}
// ------------------------------------------------------------------------------------------------
Int32 GetPlayerIdFromName(StackStrF & name)
int32_t GetPlayerIdFromName(StackStrF & name)
{
return _Func->GetPlayerIdFromName(name.mPtr);
}
// ------------------------------------------------------------------------------------------------
bool IsPlayerConnected(Int32 player_id)
bool IsPlayerConnected(int32_t player_id)
{
return _Func->IsPlayerConnected(player_id);
}
@ -805,22 +803,22 @@ void ForceAllSelect()
}
// ------------------------------------------------------------------------------------------------
bool CheckEntityExists(Int32 type, Int32 index)
bool CheckEntityExists(int32_t type, int32_t index)
{
return _Func->CheckEntityExists(static_cast< vcmpEntityPool >(type), index);
}
// ------------------------------------------------------------------------------------------------
CSStr GetDistrictName(const Vector2 & point)
const SQChar * GetDistrictName(const Vector2 & point)
{
return GetDistrictNameEx(point.x, point.y);
}
// ------------------------------------------------------------------------------------------------
CSStr GetDistrictNameEx(SQFloat x, SQFloat y)
const SQChar * GetDistrictNameEx(SQFloat x, SQFloat y)
{
// Attempt to see if the specified point is within one of the known districts
for (Uint32 n = 0; n < (sizeof(g_Districts) / sizeof(District)); ++n)
for (uint32_t n = 0; n < (sizeof(g_Districts) / sizeof(District)); ++n) // NOLINT(modernize-loop-convert)
{
// Grab the district
const District & d = g_Districts[n];
@ -835,19 +833,19 @@ CSStr GetDistrictNameEx(SQFloat x, SQFloat y)
}
// ------------------------------------------------------------------------------------------------
Uint16 GetFallTimer()
uint16_t GetFallTimer()
{
return _Func->GetFallTimer();
}
// ------------------------------------------------------------------------------------------------
void SetFallTimer(Uint16 rate)
void SetFallTimer(uint16_t rate)
{
_Func->SetFallTimer(rate);
}
#if SQMOD_SDK_LEAST(2, 1)
// ------------------------------------------------------------------------------------------------
SQFloat GetNetworkStatisticsF(Int32 option_id)
SQFloat GetNetworkStatisticsF(int32_t option_id)
{
// Retrieve the requested information
double value = _Func->GetNetworkStatistics(-1, static_cast< vcmpNetworkStatisticsOption >(option_id));
@ -856,7 +854,7 @@ SQFloat GetNetworkStatisticsF(Int32 option_id)
}
// ------------------------------------------------------------------------------------------------
SQInteger GetNetworkStatisticsI(Int32 option_id)
SQInteger GetNetworkStatisticsI(int32_t option_id)
{
// Retrieve the requested information
double value = _Func->GetNetworkStatistics(-1, static_cast< vcmpNetworkStatisticsOption >(option_id));

View File

@ -9,42 +9,42 @@ namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Retrieve the name of a certain key-code.
*/
CSStr GetKeyCodeName(Uint8 keycode);
const SQChar * GetKeyCodeName(uint8_t keycode);
/* ------------------------------------------------------------------------------------------------
* Modify the name of a certain key-code.
*/
void SetKeyCodeName(Uint8 keycode, StackStrF & name);
void SetKeyCodeName(uint8_t keycode, StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* Retrieve the server version.
*/
Uint32 GetServerVersion();
SQMOD_NODISCARD uint32_t GetServerVersion();
/* ------------------------------------------------------------------------------------------------
* Retrieve the server settings.
*/
Table GetServerSettings();
SQMOD_NODISCARD Table GetServerSettings();
/* ------------------------------------------------------------------------------------------------
* Retrieve the number of loaded plug-ins.
*/
Uint32 GetNumberOfPlugins();
SQMOD_NODISCARD uint32_t GetNumberOfPlugins();
/* ------------------------------------------------------------------------------------------------
* Retrieve information about a certain plug-in.
*/
Table GetPluginInfo(Int32 plugin_id);
SQMOD_NODISCARD Table GetPluginInfo(int32_t plugin_id);
/* ------------------------------------------------------------------------------------------------
* Attempt to find a plug-in identifier by it's name.
*/
Int32 FindPlugin(StackStrF & name);
SQMOD_NODISCARD int32_t FindPlugin(StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* Send a custom command to the loaded plug-ins.
*/
void SendPluginCommand(Uint32 identifier, StackStrF & payload);
void SendPluginCommand(uint32_t identifier, StackStrF & payload);
/* ------------------------------------------------------------------------------------------------
* Retrieve the server time.
@ -59,57 +59,57 @@ void SendLogMessage(StackStrF & msg);
/* ------------------------------------------------------------------------------------------------
* Retrieve the last error that occurred on the server.
*/
Int32 GetLastError();
SQMOD_NODISCARD int32_t GetLastError();
/* ------------------------------------------------------------------------------------------------
* Retrieve the version of the host Squirrel plug-in as an integer.
*/
Uint32 GetPluginVersion();
SQMOD_NODISCARD uint32_t GetPluginVersion();
/* ------------------------------------------------------------------------------------------------
* Retrieve the version of the host Squirrel plug-in as a string.
*/
CSStr GetPluginVersionStr();
SQMOD_NODISCARD const SQChar * GetPluginVersionStr();
/* ------------------------------------------------------------------------------------------------
* Retrieve the name of the host Squirrel plug-in.
*/
CSStr GetPluginName();
SQMOD_NODISCARD const SQChar * GetPluginName();
/* ------------------------------------------------------------------------------------------------
* Retrieve the author of the host Squirrel plug-in.
*/
CSStr GetPluginAuthor();
SQMOD_NODISCARD const SQChar * GetPluginAuthor();
/* ------------------------------------------------------------------------------------------------
* Retrieve the id of the host Squirrel plug-in.
*/
Int32 GetPluginID();
SQMOD_NODISCARD int32_t GetPluginID();
/* ------------------------------------------------------------------------------------------------
* Retrieve the port onto which the server was binded.
*/
Uint32 GetServerPort();
SQMOD_NODISCARD uint32_t GetServerPort();
/* ------------------------------------------------------------------------------------------------
* Retrieve the server flags.
*/
Uint32 GetServerFlags();
SQMOD_NODISCARD uint32_t GetServerFlags();
/* ------------------------------------------------------------------------------------------------
* Retrieve the maximum number of clients allowed on the server.
*/
Int32 GetMaxPlayers();
SQMOD_NODISCARD int32_t GetMaxPlayers();
/* ------------------------------------------------------------------------------------------------
* Modify the maximum number of clients allowed on the server.
*/
void SetMaxPlayers(Int32 max);
void SetMaxPlayers(int32_t max);
/* ------------------------------------------------------------------------------------------------
* Retrieve the server name.
*/
CSStr GetServerName();
SQMOD_NODISCARD const SQChar * GetServerName();
/* ------------------------------------------------------------------------------------------------
* Modify the server name.
@ -119,7 +119,7 @@ void SetServerName(StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* Retrieve the server password.
*/
CSStr GetServerPassword();
SQMOD_NODISCARD const SQChar * GetServerPassword();
/* ------------------------------------------------------------------------------------------------
* Modify the server password.
@ -129,7 +129,7 @@ void SetServerPassword(StackStrF & passwd);
/* ------------------------------------------------------------------------------------------------
* Retrieve the game-mode text.
*/
CSStr GetGameModeText();
SQMOD_NODISCARD const SQChar * GetGameModeText();
/* ------------------------------------------------------------------------------------------------
* Modify the game-mode text.
@ -139,17 +139,17 @@ void SetGameModeText(StackStrF & text);
/* ------------------------------------------------------------------------------------------------
* Create a radio stream.
*/
SQInteger CreateRadioStream(bool listed, StackStrF & name, StackStrF & url);
SQMOD_NODISCARD SQInteger CreateRadioStream(bool listed, StackStrF & name, StackStrF & url);
/* ------------------------------------------------------------------------------------------------
* Create a radio stream.
*/
SQInteger CreateRadioStreamEx(Int32 id, bool listed, StackStrF & name, StackStrF & url);
SQMOD_NODISCARD SQInteger CreateRadioStreamEx(int32_t id, bool listed, StackStrF & name, StackStrF & url);
/* ------------------------------------------------------------------------------------------------
* Remove a radio stream.
*/
void RemoveRadioStream(Int32 id);
void RemoveRadioStream(int32_t id);
/* ------------------------------------------------------------------------------------------------
* Shutdown the server.
@ -159,22 +159,22 @@ void ShutdownServer();
/* ------------------------------------------------------------------------------------------------
* Retrieve a server option.
*/
bool GetServerOption(Int32 option_id);
bool GetServerOption(int32_t option_id);
/* ------------------------------------------------------------------------------------------------
* Modify a server option.
*/
void SetServerOption(Int32 option_id, bool toggle);
void SetServerOption(int32_t option_id, bool toggle);
/* ------------------------------------------------------------------------------------------------
* Modify a server option.
*/
void SetServerOptionEx(Int32 option_id, bool toggle, Int32 header, LightObj & payload);
void SetServerOptionEx(int32_t option_id, bool toggle, int32_t header, LightObj & payload);
/* ------------------------------------------------------------------------------------------------
* Retrieve the world bounds.
*/
Table GetWorldBounds();
SQMOD_NODISCARD Table GetWorldBounds();
/* ------------------------------------------------------------------------------------------------
* Modify the world bounds.
@ -184,173 +184,173 @@ void SetWorldBounds(const Vector2 & max, const Vector2 & min);
/* ------------------------------------------------------------------------------------------------
* Modify the world bounds.
*/
void SetWorldBoundsEx(Float32 max_x, Float32 max_y, Float32 min_x, Float32 min_y);
void SetWorldBoundsEx(float max_x, float max_y, float min_x, float min_y);
/* ------------------------------------------------------------------------------------------------
* Retrieve the wasted settings.
*/
Table GetWastedSettings();
SQMOD_NODISCARD Table GetWastedSettings();
/* ------------------------------------------------------------------------------------------------
* Modify the wasted settings.
*/
void SetWastedSettings(Uint32 dt, Uint32 ft, Float32 fis, Float32 fos,
const Color3 & fc, Uint32 cfs, Uint32 cft);
void SetWastedSettings(uint32_t dt, uint32_t ft, float fis, float fos,
const Color3 & fc, uint32_t cfs, uint32_t cft);
/* ------------------------------------------------------------------------------------------------
* Retrieve the current time-rate.
*/
Int32 GetTimeRate();
SQMOD_NODISCARD int32_t GetTimeRate();
/* ------------------------------------------------------------------------------------------------
* Modify the current time-rate.
*/
void SetTimeRate(Uint32 rate);
void SetTimeRate(uint32_t rate);
/* ------------------------------------------------------------------------------------------------
* Retrieve the game hour.
*/
Int32 GetHour();
SQMOD_NODISCARD int32_t GetHour();
/* ------------------------------------------------------------------------------------------------
* Modify the game hour.
*/
void SetHour(Int32 hour);
void SetHour(int32_t hour);
/* ------------------------------------------------------------------------------------------------
* Retrieve the game minute.
*/
Int32 GetMinute();
SQMOD_NODISCARD int32_t GetMinute();
/* ------------------------------------------------------------------------------------------------
* Modify the game minute.
*/
void SetMinute(Int32 minute);
void SetMinute(int32_t minute);
/* ------------------------------------------------------------------------------------------------
* Retrieve the weather effects.
*/
Int32 GetWeather();
SQMOD_NODISCARD int32_t GetWeather();
/* ------------------------------------------------------------------------------------------------
* Modify the weather effects.
*/
void SetWeather(Int32 weather);
void SetWeather(int32_t weather);
/* ------------------------------------------------------------------------------------------------
* Retrieve the game gravity.
*/
Float32 GetGravity();
SQMOD_NODISCARD float GetGravity();
/* ------------------------------------------------------------------------------------------------
* Modify the game gravity.
*/
void SetGravity(Float32 gravity);
void SetGravity(float gravity);
/* ------------------------------------------------------------------------------------------------
* Retrieve the game speed.
*/
Float32 GetGameSpeed();
SQMOD_NODISCARD float GetGameSpeed();
/* ------------------------------------------------------------------------------------------------
* Modify the game speed.
*/
void SetGameSpeed(Float32 speed);
void SetGameSpeed(float speed);
/* ------------------------------------------------------------------------------------------------
* Retrieve the water level.
*/
Float32 GetWaterLevel();
SQMOD_NODISCARD float GetWaterLevel();
/* ------------------------------------------------------------------------------------------------
* Modify the water level.
*/
void SetWaterLevel(Float32 level);
void SetWaterLevel(float level);
/* ------------------------------------------------------------------------------------------------
* Retrieve the maximum flight altitude.
*/
Float32 GetMaximumFlightAltitude();
SQMOD_NODISCARD float GetMaximumFlightAltitude();
/* ------------------------------------------------------------------------------------------------
* Modify the maximum flight altitude.
*/
void SetMaximumFlightAltitude(Float32 height);
void SetMaximumFlightAltitude(float height);
/* ------------------------------------------------------------------------------------------------
* Retrieve the kill command delay.
*/
Int32 GetKillCommandDelay();
SQMOD_NODISCARD int32_t GetKillCommandDelay();
/* ------------------------------------------------------------------------------------------------
* Modify the kill command delay.
*/
void SetKillCommandDelay(Int32 delay);
void SetKillCommandDelay(int32_t delay);
/* ------------------------------------------------------------------------------------------------
* Retrieve the vehicles forced respawn height.
*/
Float32 GetVehiclesForcedRespawnHeight();
SQMOD_NODISCARD float GetVehiclesForcedRespawnHeight();
/* ------------------------------------------------------------------------------------------------
* Modify the vehicles forced respawn height.
*/
void SetVehiclesForcedRespawnHeight(Float32 height);
void SetVehiclesForcedRespawnHeight(float height);
/* ------------------------------------------------------------------------------------------------
* Create a game explosion.
*/
void CreateExplosion(Int32 world, Int32 type, const Vector3 & pos, CPlayer & source, bool grounded);
void CreateExplosion(int32_t world, int32_t type, const Vector3 & pos, CPlayer & source, bool grounded);
/* ------------------------------------------------------------------------------------------------
* Create a game explosion.
*/
void CreateExplosionEx(Int32 world, Int32 type, Float32 x, Float32 y, Float32 z, CPlayer & source, bool grounded);
void CreateExplosionEx(int32_t world, int32_t type, float x, float y, float z, CPlayer & source, bool grounded);
/* ------------------------------------------------------------------------------------------------
* Play a game sound.
*/
void PlaySound(Int32 world, Int32 sound, const Vector3 & pos);
void PlaySound(int32_t world, int32_t sound, const Vector3 & pos);
/* ------------------------------------------------------------------------------------------------
* Play a game sound.
*/
void PlaySoundEx(Int32 world, Int32 sound, Float32 x, Float32 y, Float32 z);
void PlaySoundEx(int32_t world, int32_t sound, float x, float y, float z);
/* ------------------------------------------------------------------------------------------------
* Play a game sound to a specific world.
*/
void PlaySoundForWorld(Int32 world, Int32 sound);
void PlaySoundForWorld(int32_t world, int32_t sound);
/* ------------------------------------------------------------------------------------------------
* Make a map object invisible.
*/
void HideMapObject(Int32 model, const Vector3 & pos);
void HideMapObject(int32_t model, const Vector3 & pos);
/* ------------------------------------------------------------------------------------------------
* Make a map object invisible.
*/
void HideMapObjectEx(Int32 model, Float32 x, Float32 y, Float32 z);
void HideMapObjectEx(int32_t model, float x, float y, float z);
/* ------------------------------------------------------------------------------------------------
* Make a map object invisible.
*/
void HideMapObjectRaw(Int32 model, Int16 x, Int16 y, Int16 z);
void HideMapObjectRaw(int32_t model, int16_t x, int16_t y, int16_t z);
/* ------------------------------------------------------------------------------------------------
* Make a map object visible again.
*/
void ShowMapObject(Int32 model, const Vector3 & pos);
void ShowMapObject(int32_t model, const Vector3 & pos);
/* ------------------------------------------------------------------------------------------------
* Make a map object visible again.
*/
void ShowMapObjectEx(Int32 model, Float32 x, Float32 y, Float32 z);
void ShowMapObjectEx(int32_t model, float x, float y, float z);
/* ------------------------------------------------------------------------------------------------
* Make a map object visible again.
*/
void ShowMapObjectRaw(Int32 model, Int16 x, Int16 y, Int16 z);
void ShowMapObjectRaw(int32_t model, int16_t x, int16_t y, int16_t z);
/* ------------------------------------------------------------------------------------------------
* Make all map objects visible again.
@ -360,27 +360,27 @@ void ShowAllMapObjects();
/* ------------------------------------------------------------------------------------------------
* Retrieve field data of a certain weapon.
*/
SQFloat GetWeaponDataValue(Int32 weapon, Int32 field);
SQMOD_NODISCARD SQFloat GetWeaponDataValue(int32_t weapon, int32_t field);
/* ------------------------------------------------------------------------------------------------
* Modify field data of a certain weapon.
*/
bool SetWeaponDataValue(Int32 weapon, Int32 field, SQFloat value);
bool SetWeaponDataValue(int32_t weapon, int32_t field, SQFloat value);
/* ------------------------------------------------------------------------------------------------
* Reset field data of a certain weapon.
*/
bool ResetWeaponDataValue(Int32 weapon, Int32 field);
bool ResetWeaponDataValue(int32_t weapon, int32_t field);
/* ------------------------------------------------------------------------------------------------
* See whether field data of a certain weapon was modified.
*/
bool IsWeaponDataValueModified(Int32 weapon, Int32 field);
bool IsWeaponDataValueModified(int32_t weapon, int32_t field);
/* ------------------------------------------------------------------------------------------------
* Reset all fields data of a certain weapon.
*/
bool ResetWeaponData(Int32 weapon);
bool ResetWeaponData(int32_t weapon);
/* ------------------------------------------------------------------------------------------------
* Reset all fields data of a all weapons.
@ -390,8 +390,8 @@ void ResetAllWeaponData();
/* ------------------------------------------------------------------------------------------------
* Create a new player class.
*/
Int32 AddPlayerClass(Int32 team, const Color3 & color, Int32 skin, const Vector3 & pos, Float32 angle,
Int32 wep1, Int32 ammo1, Int32 wep2, Int32 ammo2, Int32 wep3, Int32 ammo3);
SQMOD_NODISCARD int32_t AddPlayerClass(int32_t team, const Color3 & color, int32_t skin, const Vector3 & pos, float angle,
int32_t wep1, int32_t ammo1, int32_t wep2, int32_t ammo2, int32_t wep3, int32_t ammo3);
/* ------------------------------------------------------------------------------------------------
* Set the player position when spawning.
@ -411,17 +411,17 @@ void SetSpawnCameraLookAt(const Vector3 & pos);
/* ------------------------------------------------------------------------------------------------
* Set the player position when spawning.
*/
void SetSpawnPlayerPositionEx(Float32 x, Float32 y, Float32 z);
void SetSpawnPlayerPositionEx(float x, float y, float z);
/* ------------------------------------------------------------------------------------------------
* Set the camera position when spawning.
*/
void SetSpawnCameraPositionEx(Float32 x, Float32 y, Float32 z);
void SetSpawnCameraPositionEx(float x, float y, float z);
/* ------------------------------------------------------------------------------------------------
* Set the camera focus when spawning.
*/
void SetSpawnCameraLookAtEx(Float32 x, Float32 y, Float32 z);
void SetSpawnCameraLookAtEx(float x, float y, float z);
/* ------------------------------------------------------------------------------------------------
* Ban an IP address from the server.
@ -441,12 +441,12 @@ bool IsIPBanned(StackStrF & addr);
/* ------------------------------------------------------------------------------------------------
* Retrieve the identifier of the player with the specified name.
*/
Int32 GetPlayerIdFromName(StackStrF & name);
SQMOD_NODISCARD int32_t GetPlayerIdFromName(StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* See if a player with the specified identifier is connected.
*/
bool IsPlayerConnected(Int32 player_id);
bool IsPlayerConnected(int32_t player_id);
/* ------------------------------------------------------------------------------------------------
* Force all players on the server to select a class.
@ -456,37 +456,37 @@ void ForceAllSelect();
/* ------------------------------------------------------------------------------------------------
* See if an entity exists on the server.
*/
bool CheckEntityExists(Int32 type, Int32 index);
bool CheckEntityExists(int32_t type, int32_t index);
/* ------------------------------------------------------------------------------------------------
* See if a certain point is within a known district on the bas game map.
*/
CSStr GetDistrictName(const Vector2 & point);
SQMOD_NODISCARD const SQChar * GetDistrictName(const Vector2 & point);
/* ------------------------------------------------------------------------------------------------
* See if a certain point is within a known district on the bas game map.
*/
CSStr GetDistrictNameEx(SQFloat x, SQFloat y);
SQMOD_NODISCARD const SQChar * GetDistrictNameEx(SQFloat x, SQFloat y);
/* ------------------------------------------------------------------------------------------------
* Retrieve the fall timer rate.
*/
Uint16 GetFallTimer();
SQMOD_NODISCARD uint16_t GetFallTimer();
/* ------------------------------------------------------------------------------------------------
* Modify the fall timer rate.
*/
void SetFallTimer(Uint16 rate);
void SetFallTimer(uint16_t rate);
#if SQMOD_SDK_LEAST(2, 1)
/* ------------------------------------------------------------------------------------------------
* Retrieve network statistics related to the server.
*/
SQFloat GetNetworkStatisticsF(Int32 option_id);
SQMOD_NODISCARD SQFloat GetNetworkStatisticsF(int32_t option_id);
/* ------------------------------------------------------------------------------------------------
* Retrieve network statistics related to the server.
*/
SQInteger GetNetworkStatisticsI(Int32 option_id);
SQMOD_NODISCARD SQInteger GetNetworkStatisticsI(int32_t option_id);
#endif
} // Namespace:: SqMod

View File

@ -5,20 +5,20 @@
namespace SqMod {
// ------------------------------------------------------------------------------------------------
CSStr GetModelName(Int32 /*id*/)
const SQChar * GetModelName(int32_t /*id*/)
{
// @TODO Implement...
return _SC("");
}
// ------------------------------------------------------------------------------------------------
void SetModelName(Int32 /*id*/, StackStrF & /*name*/)
void SetModelName(int32_t /*id*/, StackStrF & /*name*/)
{
// @TODO Implement...
}
// ------------------------------------------------------------------------------------------------
bool IsModelWeapon(Int32 id)
bool IsModelWeapon(int32_t id)
{
switch (id)
{
@ -64,7 +64,7 @@ bool IsModelWeapon(Int32 id)
}
// ------------------------------------------------------------------------------------------------
bool IsModelActuallyWeapon(Int32 id)
bool IsModelActuallyWeapon(int32_t id)
{
switch (id)
{

View File

@ -9,21 +9,21 @@ namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Retrieve the name associated with a model identifier.
*/
CSStr GetModelName(Int32 id);
SQMOD_NODISCARD const SQChar * GetModelName(int32_t id);
/* ------------------------------------------------------------------------------------------------
* Modify the name associated with a model identifier.
*/
void SetModelName(Int32 id, StackStrF & name);
void SetModelName(int32_t id, StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* See whether the given model identifier is used a weapon model.
*/
bool IsModelWeapon(Int32 id);
SQMOD_NODISCARD bool IsModelWeapon(int32_t id);
/* ------------------------------------------------------------------------------------------------
* See whether the given model identifier is an actual weapon model.
*/
bool IsModelActuallyWeapon(Int32 id);
SQMOD_NODISCARD bool IsModelActuallyWeapon(int32_t id);
} // Namespace:: SqMod

View File

@ -1,12 +1,7 @@
// ------------------------------------------------------------------------------------------------
#include "Misc/Player.hpp"
#include "Base/Color3.hpp"
#include "Core.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstring>
#include <algorithm>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -96,13 +91,13 @@ static String CS_Skin_Names[] = { // NOLINT(cert-err58-cpp)
};
// ------------------------------------------------------------------------------------------------
CCStr GetSkinName(Uint32 id)
const char * GetSkinName(uint32_t id)
{
return (id > 159) ? _SC("") : CS_Skin_Names[id].c_str();
}
// ------------------------------------------------------------------------------------------------
void SetSkinName(Uint32 id, StackStrF & name)
void SetSkinName(uint32_t id, StackStrF & name)
{
if (id <= 159)
{
@ -111,7 +106,7 @@ void SetSkinName(Uint32 id, StackStrF & name)
}
// ------------------------------------------------------------------------------------------------
Int32 GetSkinID(StackStrF & name)
int32_t GetSkinID(StackStrF & name)
{
// Clone the string into an editable version
String str(name.mPtr, static_cast< size_t >(name.mLen));
@ -125,7 +120,7 @@ Int32 GetSkinID(StackStrF & name)
return SQMOD_UNKNOWN;
}
// Grab the actual length of the string
const Uint32 len = ConvTo< Uint32 >::From(str.length());
const uint32_t len = ConvTo< uint32_t >::From(str.length());
// Get the most significant characters used to identify a skin
CharT a = str[0], b = 0, c = 0, d = str[len-1];
// Look for deeper specifiers
@ -781,9 +776,9 @@ Int32 GetSkinID(StackStrF & name)
}
// ------------------------------------------------------------------------------------------------
bool IsSkinValid(Int32 id)
bool IsSkinValid(int32_t id)
{
CSStr name = GetSkinName(static_cast<Uint32>(id));
const SQChar * name = GetSkinName(static_cast<uint32_t>(id));
return (name && *name != '\0');
}

View File

@ -9,21 +9,21 @@ namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Retrieve the name associated with a skin model identifier.
*/
CCStr GetSkinName(Uint32 id);
SQMOD_NODISCARD const char * GetSkinName(uint32_t id);
/* ------------------------------------------------------------------------------------------------
* Modify the name associated with a skin model identifier.
*/
void SetSkinName(Uint32 id, StackStrF & name);
void SetSkinName(uint32_t id, StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* Convert a vehicle model name to a skin model identifier.
*/
Int32 GetSkinID(StackStrF & name);
SQMOD_NODISCARD int32_t GetSkinID(StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* See whether the specified skin model identifier is valid.
*/
bool IsSkinValid(Int32 id);
SQMOD_NODISCARD bool IsSkinValid(int32_t id);
} // Namespace:: SqMod

View File

@ -1,314 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Misc/Privilege.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(UnitTn, _SC("SqPrivilegeUnit"))
SQMODE_DECL_TYPENAME(ClassTn, _SC("SqPrivilegeClass"))
SQMODE_DECL_TYPENAME(EntryTn, _SC("SqPrivilegeEntry"))
SQMODE_DECL_TYPENAME(ManagerTn, _SC("SqPrivilegeManager"))
// ------------------------------------------------------------------------------------------------
// Helper value used to identify an index that doesn't exist.
static constexpr size_t BAD_POS = ~static_cast< size_t >(0);
// ------------------------------------------------------------------------------------------------
PvManagers PvManager::s_Managers;
/* ------------------------------------------------------------------------------------------------
* Privilege unit wrapper.
*/
class PvUnitWrap
{
private:
/* --------------------------------------------------------------------------------------------
*
*/
PvUnit::Ref mInst;
public:
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvUnitWrap(SQInteger id, PvClass * cls)
{
}
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvUnitWrap(SQInteger id, StackStrF && tag, PvClass * cls)
{
}
/* -------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
PvUnitWrap(const PvUnitWrap & o) = delete;
/* -------------------------------------------------------------------------------------------
* Destructor.
*/
~PvUnitWrap();
/* -------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
PvUnitWrap & operator = (const PvUnitWrap & o) = delete;
/* --------------------------------------------------------------------------------------------
* Release all script resources. Recursively forward request.
*/
void Release()
{
}
};
/* ------------------------------------------------------------------------------------------------
* Privilege class wrapper.
*/
class PvClassWrap
{
friend class PvManager;
private:
/* --------------------------------------------------------------------------------------------
*
*/
PvClass::Ref mInst;
public:
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvClassWrap(SQInteger id, PvManager * mgr)
{
}
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvClassWrap(SQInteger id, StackStrF && tag, PvManager * mgr)
{
}
/* -------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
PvClassWrap(const PvClassWrap & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
PvClassWrap(PvClassWrap && o) = delete;
/* -------------------------------------------------------------------------------------------
* Destructor.
*/
~PvClassWrap();
/* -------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
PvClassWrap & operator = (const PvClassWrap & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
PvClassWrap & operator = (PvClassWrap && o) = delete;
/* --------------------------------------------------------------------------------------------
* Release all script resources. Recursively forward request.
*/
void Release()
{
}
};
/* ------------------------------------------------------------------------------------------------
* Privilege entry wrapper.
*/
class PvEntryWrap
{
friend class PvManager;
private:
/* --------------------------------------------------------------------------------------------
*
*/
PvEntry::Ref mInst;
public:
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvEntryWrap(SQInteger id, PvManager * mgr)
{
}
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvEntryWrap(SQInteger id, StackStrF && tag, PvManager * mgr)
{
}
/* -------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
PvEntryWrap(const PvEntryWrap & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
PvEntryWrap(PvEntryWrap && o) = delete;
/* -------------------------------------------------------------------------------------------
* Destructor.
*/
~PvEntryWrap();
/* -------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
PvEntryWrap & operator = (const PvEntryWrap & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
PvEntryWrap & operator = (PvEntryWrap && o) = delete;
/* --------------------------------------------------------------------------------------------
* Release all script resources. Recursively forward request.
*/
void Release()
{
}
};
// ------------------------------------------------------------------------------------------------
void TerminatePrivileges()
{
PvManager::Terminate();
}
// ================================================================================================
void Register_Privilege(HSQUIRRELVM vm)
{
Table pns(vm);
/*
pns.Bind(_SC("Unit"),
Class< PvUnit, NoConstructor< PvUnit > >(vm, UnitTn::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &UnitTn::Fn)
.Func(_SC("_tostring"), &PvUnit::ToString)
// Core Properties
.Prop(_SC("ID"), &PvUnit::GetID)
.Prop(_SC("Tag"), &PvUnit::GetTag, &PvUnit::SetTag)
.Prop(_SC("Data"), &PvUnit::GetData, &PvUnit::SetData)
.Prop(_SC("Manager"), &PvUnit::GetManager)
.Prop(_SC("Class"), &PvUnit::GetClass, &PvUnit::SetClass)
.Prop(_SC("Authority"), &PvUnit::GetAuthority, &PvUnit::SetAuthority)
// Core Methods
.FmtFunc(_SC("SetTag"), &PvUnit::ApplyTag)
// Member Methods
.CbFunc(_SC("OnQuery"), &PvUnit::SetOnQuery)
.CbFunc(_SC("OnLost"), &PvUnit::SetOnLost)
.CbFunc(_SC("OnGained"), &PvUnit::SetOnGained)
// Member Overloads
.Overload< bool (PvUnit::*)(const PvEntry &) const >
(_SC("Can"), &PvUnit::Can)
.Overload< bool (PvUnit::*)(const PvEntry &, const PvUnit &) const >
(_SC("Can"), &PvUnit::Can)
);
pns.Bind(_SC("Class"),
Class< PvClass, NoConstructor< PvClass > >(vm, ClassTn::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &ClassTn::Fn)
.Func(_SC("_tostring"), &PvClass::ToString)
// Core Properties
.Prop(_SC("ID"), &PvClass::GetID)
.Prop(_SC("Tag"), &PvClass::GetTag, &PvClass::SetTag)
.Prop(_SC("Data"), &PvClass::GetData, &PvClass::SetData)
.Prop(_SC("Parent"), &PvClass::GetParent, &PvClass::SetParent)
.Prop(_SC("Manager"), &PvClass::GetManager)
// Core Methods
.FmtFunc(_SC("SetTag"), &PvClass::ApplyTag)
// Member Methods
.Func(_SC("AddUnit"), &PvClass::AddUnit)
.Func(_SC("GetUnit"), &PvClass::GetUnitByID)
.Func(_SC("GetUnitByID"), &PvClass::GetUnitByID)
.Func(_SC("HaveUnitWithID"), &PvClass::HaveUnitWithID)
.FmtFunc(_SC("GetUnitByTag"), &PvClass::GetUnitByTag)
.FmtFunc(_SC("HaveUnitWithTag"), &PvClass::HaveUnitWithTag)
.FmtFunc(_SC("CreateUnit"), &PvClass::CreateUnit)
.CbFunc(_SC("OnQuery"), &PvClass::SetOnQuery)
.CbFunc(_SC("OnLost"), &PvClass::SetOnLost)
.CbFunc(_SC("OnGained"), &PvClass::SetOnGained)
// Raw functions
);
pns.Bind(_SC("Entry"),
Class< PvEntry, NoConstructor< PvEntry > >(vm, EntryTn::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &EntryTn::Fn)
.Func(_SC("_tostring"), &PvEntry::ToString)
// Core Properties
.Prop(_SC("ID"), &PvEntry::GetID)
.Prop(_SC("Tag"), &PvEntry::GetTag, &PvEntry::SetTag)
.Prop(_SC("Data"), &PvEntry::GetData, &PvEntry::SetData)
.Prop(_SC("Manager"), &PvEntry::GetManager)
.Prop(_SC("Brief"), &PvEntry::GetBrief, &PvEntry::SetBrief)
.Prop(_SC("Info"), &PvEntry::GetInfo, &PvEntry::SetInfo)
.Prop(_SC("Default"), &PvEntry::GetDefault, &PvEntry::SetDefault)
// Core Methods
.FmtFunc(_SC("SetTag"), &PvEntry::ApplyTag)
// Member Methods
.FmtFunc(_SC("SetBrief"), &PvEntry::ApplyBrief)
.FmtFunc(_SC("SetInfo"), &PvEntry::ApplyInfo)
.CbFunc(_SC("OnQuery"), &PvEntry::SetOnQuery)
.CbFunc(_SC("OnLost"), &PvEntry::SetOnLost)
.CbFunc(_SC("OnGained"), &PvEntry::SetOnGained)
// Raw functions
);
*/
/* pns.Bind(_SC("Manager"),
Class< PvManager, NoCopy< PvManager > >(vm, ManagerTn::Str)
// Constructors
.Ctor()
.Ctor< StackStrF & >()
// Meta-methods
.SquirrelFunc(_SC("_typename"), &ManagerTn::Fn)
.Func(_SC("_tostring"), &PvManager::ToString)
// Core Properties
.Prop(_SC("Tag"), &PvManager::GetTag, &PvManager::SetTag)
.Prop(_SC("Data"), &PvManager::GetData, &PvManager::SetData)
// Core Methods
.FmtFunc(_SC("SetTag"), &PvManager::ApplyTag)
// Member Methods
.CbFunc(_SC("OnQuery"), &PvManager::SetOnQuery)
.CbFunc(_SC("OnLost"), &PvManager::SetOnLost)
.CbFunc(_SC("OnGained"), &PvManager::SetOnGained)
// Raw functions
);
*/
RootTable(vm).Bind(_SC("SqPrivilege"), pns);
}
} // Namespace:: SqMod

View File

@ -1,704 +0,0 @@
#pragma once
/* ------------------------------------------------------------------------------------------------
* This could have been much more flexible and advanced than this (as initially planned).
* However, several factors played an important role in its current simplicity:
* 1) Time constraints:
* This had to be done over the course of a weekend (at worst). It might be extended
* over time but right now this will do.
* 2) Performance cost:
* Privilege micro-management will become costly if scripting is involved. Therefore, several
* sacrifices had to be made. Such as type-agnostic status value, script controlled query etc.
*/
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
#include <vector>
#include <utility>
#include <algorithm>
#include <unordered_map>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
struct PvUnit;
struct PvClass;
struct PvEntry;
// ------------------------------------------------------------------------------------------------
class PvUnit;
class PvClass;
class PvEntry;
class PvManager;
// ------------------------------------------------------------------------------------------------
typedef std::vector< PvManager * > PvManagers;
// ------------------------------------------------------------------------------------------------
typedef std::vector< std::pair< SQInteger, SQInteger > > PvStatusList;
/* ------------------------------------------------------------------------------------------------
* An individual unit/entity that inherits the privileges of a class/group and can
* change their status without affecting other units and/or their associated class.
* A unit cannot extend it's privileges to other entities.
* Units cost more to query if they differ from their class but save memory in large numbers.
* Each unit must have a unique numerical identifier within their associated manager.
*/
struct PvUnit
{
/* --------------------------------------------------------------------------------------------
* Strong and weak reference types.
*/
typedef SharedPtr< PvUnit > Ref;
typedef WeakPtr< PvUnit > Ptr;
/* --------------------------------------------------------------------------------------------
* Type of container used to store privilege units.
*/
typedef std::vector< std::pair< SQInteger, Ref > > List;
/* --------------------------------------------------------------------------------------------
* User identifier associated with this unit instance.
*/
SQInteger mID;
/* --------------------------------------------------------------------------------------------
* Authority level associated with a particular unit.
*/
SQInteger mAuthority;
/* --------------------------------------------------------------------------------------------
* A container with unique privilege status values associated with this unit.
*/
PvStatusList mPrivileges;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege query event.
*/
Function mOnQuery;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege modify event.
*/
Function mOnModify;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege gained event.
*/
Function mOnGained;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege lost event.
*/
Function mOnLost;
/* --------------------------------------------------------------------------------------------
* User tag associated with this instance.
*/
StackStrF mTag;
/* --------------------------------------------------------------------------------------------
* User data associated with this instance.
*/
LightObj mData;
/* --------------------------------------------------------------------------------------------
* Pointer to the associated class.
*/
WeakPtr< PvClass > mClass;
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvUnit(SQInteger id, WeakPtr< PvClass > cls)
: mID(id)
, mAuthority(0)
, mPrivileges()
, mOnQuery(), mOnGained(), mOnLost()
, mTag(), mData()
, mClass(std::move(cls))
{
}
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvUnit(SQInteger id, StackStrF && tag, WeakPtr< PvClass > cls)
: mID(id)
, mAuthority(0)
, mPrivileges()
, mOnQuery(), mOnGained(), mOnLost()
, mTag(std::forward< StackStrF >(tag)), mData()
, mClass(std::move(cls))
{
}
/* -------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
PvUnit(const PvUnit & o) = delete;
/* -------------------------------------------------------------------------------------------
* Destructor.
*/
~PvUnit();
/* -------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
PvUnit & operator = (const PvUnit & o) = delete;
/* -------------------------------------------------------------------------------------------
* Comparison operators. Uses the identifier internally as that is guaranteed to be unique.
*/
bool operator == (const PvUnit & o) const { return mID == o.mID; }
bool operator != (const PvUnit & o) const { return mID != o.mID; }
bool operator < (const PvUnit & o) const { return mID < o.mID; }
bool operator > (const PvUnit & o) const { return mID > o.mID; }
bool operator <= (const PvUnit & o) const { return mID <= o.mID; }
bool operator >= (const PvUnit & o) const { return mID >= o.mID; }
/* --------------------------------------------------------------------------------------------
* Release all script resources. Recursively forward request.
*/
void Release()
{
mOnQuery.Release();
mOnGained.Release();
mOnLost.Release();
mTag.Release();
mData.Release();
}
};
/* ------------------------------------------------------------------------------------------------
* An individual class/group that can optionally inherit the privileges of another and can
* change their status to affect their children but not their parent class.
* A class can extend it's privileges to units and/or other classes.
* These cost less to query but use more memory because they're fewer and they preallocate it.
* Each class must have a unique numerical identifier within their associated manager.
*/
struct PvClass
{
/* --------------------------------------------------------------------------------------------
* Strong and weak reference types.
*/
typedef SharedPtr< PvClass > Ref;
typedef WeakPtr< PvClass > Ptr;
/* --------------------------------------------------------------------------------------------
* Type of container used to store privilege classes.
*/
typedef std::vector< std::pair< SQInteger, Ref > > List;
/* --------------------------------------------------------------------------------------------
* User identifier associated with this class instance.
*/
SQInteger mID;
/* --------------------------------------------------------------------------------------------
* The parent class from which we are inheriting privileges, if any.
*/
PvClass * mParent;
/* --------------------------------------------------------------------------------------------
* A container with unique privilege status values associated with this class.
*/
PvStatusList mPrivileges;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege query event.
*/
Function mOnQuery;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege modify event.
*/
Function mOnModify;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege gained event.
*/
Function mOnGained;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege lost event.
*/
Function mOnLost;
/* --------------------------------------------------------------------------------------------
* Container that stores all the associated units.
*/
PvUnit::List mUnits;
/* --------------------------------------------------------------------------------------------
* User tag associated with this instance.
*/
StackStrF mTag;
/* --------------------------------------------------------------------------------------------
* User data associated with this instance.
*/
LightObj mData;
/* --------------------------------------------------------------------------------------------
* Pointer to the associated manager.
*/
PvManager * mManager;
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvClass(SQInteger id, PvManager * mgr)
: mID(id)
, mParent(nullptr)
, mPrivileges()
, mOnQuery(), mOnGained(), mOnLost()
, mUnits()
, mTag(), mData()
, mManager(mgr)
{
}
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvClass(SQInteger id, StackStrF && tag, PvManager * mgr)
: mID(id)
, mParent(nullptr)
, mPrivileges()
, mOnQuery(), mOnGained(), mOnLost()
, mUnits()
, mTag(std::forward< StackStrF >(tag)), mData()
, mManager(mgr)
{
}
/* -------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
PvClass(const PvClass & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
PvClass(PvClass && o) = delete;
/* -------------------------------------------------------------------------------------------
* Destructor.
*/
~PvClass();
/* -------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
PvClass & operator = (const PvClass & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
PvClass & operator = (PvClass && o) = delete;
/* -------------------------------------------------------------------------------------------
* Comparison operators. Uses the identifier internally as that is guaranteed to be unique.
*/
bool operator == (const PvClass & o) const { return mID == o.mID; }
bool operator != (const PvClass & o) const { return mID != o.mID; }
bool operator < (const PvClass & o) const { return mID < o.mID; }
bool operator > (const PvClass & o) const { return mID > o.mID; }
bool operator <= (const PvClass & o) const { return mID <= o.mID; }
bool operator >= (const PvClass & o) const { return mID >= o.mID; }
/* --------------------------------------------------------------------------------------------
* Release all script resources. Recursively forward request.
*/
void Release()
{
mOnQuery.Release();
mOnGained.Release();
mOnLost.Release();
mTag.Release();
mData.Release();
}
};
/* ------------------------------------------------------------------------------------------------
* An entry represents a privilege that a class or unit can can have.
* Each entry must have a unique numerical identifier within their associated manager.
*/
struct PvEntry
{
/* --------------------------------------------------------------------------------------------
* Strong and weak reference types.
*/
typedef SharedPtr< PvEntry > Ref;
typedef WeakPtr< PvEntry > Ptr;
/* --------------------------------------------------------------------------------------------
* Type of container used to store privilege entries.
*/
typedef std::vector< std::pair< SQInteger, Ref > > List;
/* --------------------------------------------------------------------------------------------
* User identifier associated with this instance.
*/
SQInteger mID;
/* --------------------------------------------------------------------------------------------
* User tag associated with this instance.
*/
StackStrF mTag;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege query event.
*/
Function mOnQuery;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege gained event.
*/
Function mOnGained;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege lost event.
*/
Function mOnLost;
/* --------------------------------------------------------------------------------------------
* User data associated with this instance.
*/
LightObj mData;
/* --------------------------------------------------------------------------------------------
* Brief information about the privilege.
*/
StackStrF mBrief;
/* --------------------------------------------------------------------------------------------
* Detailed information about the privilege.
*/
StackStrF mInfo;
/* --------------------------------------------------------------------------------------------
* Implicit privilege status value.
*/
SQInteger mDefault;
/* --------------------------------------------------------------------------------------------
* Pointer to the associated manager.
*/
PvManager * mManager;
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvEntry(SQInteger id, PvManager * mgr)
: mID(id), mTag()
, mOnQuery(), mOnGained(), mOnLost()
, mData(), mBrief(), mInfo(), mDefault()
, mManager(mgr)
{
}
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvEntry(SQInteger id, StackStrF && tag, PvManager * mgr)
: mID(id), mTag(std::forward< StackStrF >(tag))
, mOnQuery(), mOnGained(), mOnLost()
, mData(), mBrief(), mInfo(), mDefault()
, mManager(mgr)
{
}
/* -------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
PvEntry(const PvEntry & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
PvEntry(PvEntry && o) = delete;
/* -------------------------------------------------------------------------------------------
* Destructor.
*/
~PvEntry();
/* -------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
PvEntry & operator = (const PvEntry & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
PvEntry & operator = (PvEntry && o) = delete;
/* -------------------------------------------------------------------------------------------
* Comparison operators. Uses the identifier internally as that is guaranteed to be unique.
*/
bool operator == (const PvEntry & o) const { return mID == o.mID; }
bool operator != (const PvEntry & o) const { return mID != o.mID; }
bool operator < (const PvEntry & o) const { return mID < o.mID; }
bool operator > (const PvEntry & o) const { return mID > o.mID; }
bool operator <= (const PvEntry & o) const { return mID <= o.mID; }
bool operator >= (const PvEntry & o) const { return mID >= o.mID; }
/* --------------------------------------------------------------------------------------------
* Release all script resources. Recursively forward request.
*/
void Release()
{
mTag.Release();
mOnQuery.Release();
mOnGained.Release();
mOnLost.Release();
mData.Release();
mBrief.Release();
mInfo.Release();
}
};
/* ------------------------------------------------------------------------------------------------
*
*/
class PvManager
{
private:
/* --------------------------------------------------------------------------------------------
* Container that stores privilege entries.
*/
PvEntry::List m_Entries;
/* --------------------------------------------------------------------------------------------
* Container that stores the managed classes.
*/
PvClass::List m_Classes;
/* --------------------------------------------------------------------------------------------
* Container that stores all the managed units.
*/
PvUnit::List m_Units;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege query event.
*/
Function m_OnQuery;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege gained event.
*/
Function m_OnGained;
/* --------------------------------------------------------------------------------------------
* Dedicated callback for privilege lost event.
*/
Function m_OnLost;
/* --------------------------------------------------------------------------------------------
* User tag associated with this instance.
*/
StackStrF m_Tag;
/* --------------------------------------------------------------------------------------------
* User data associated with this instance.
*/
LightObj m_Data;
/* --------------------------------------------------------------------------------------------
* List of active privilege managers.
*/
static PvManagers s_Managers;
public:
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvManager()
: m_Entries(), m_Classes(), m_Units()
, m_OnQuery(), m_OnGained(), m_OnLost()
, m_Tag(), m_Data()
{
s_Managers.push_back(this);
}
/* -------------------------------------------------------------------------------------------
* Default constructor.
*/
PvManager(StackStrF & tag)
: m_Entries(), m_Classes(), m_Units()
, m_OnQuery(), m_OnGained(), m_OnLost()
, m_Tag(std::move(tag)), m_Data()
{
s_Managers.push_back(this);
}
/* -------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
PvManager(const PvManager & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
PvManager(PvManager && o) = delete;
/* -------------------------------------------------------------------------------------------
* Destructor.
*/
~PvManager()
{
s_Managers.erase(std::remove(s_Managers.begin(), s_Managers.end(), this), s_Managers.end());
}
/* -------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
PvManager & operator = (const PvManager & o) = delete;
/* -------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
PvManager & operator = (PvManager && o) = delete;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
auto ToString() const
{
return m_Tag.mObj;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the associated user tag wrapper.
*/
const StackStrF & GetTagW() const
{
return m_Tag;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the associated user tag.
*/
auto GetTag() const
{
return m_Tag.mObj;
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user tag.
*/
void SetTag(StackStrF & tag)
{
m_Tag = std::move(tag);
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user tag.
*/
PvManager & ApplyTag(StackStrF & tag)
{
SetTag(tag);
return *this;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the associated user data.
*/
LightObj & GetData()
{
return m_Data;
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user data.
*/
void SetData(LightObj & data)
{
m_Data = data;
}
/* --------------------------------------------------------------------------------------------
* Bind a script function to the status query callback.
*/
void SetOnQuery(Function & func)
{
m_OnQuery = std::move(func);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the function bound to the status query callback.
*/
Function & GetOnQuery()
{
return m_OnQuery;
}
/* --------------------------------------------------------------------------------------------
* Bind a script function to the status lost callback.
*/
void SetOnLost(Function & func)
{
m_OnLost = std::move(func);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the function bound to the status lost callback.
*/
Function & GetOnLost()
{
return m_OnLost;
}
/* --------------------------------------------------------------------------------------------
* Bind a script function to the status gained callback.
*/
void SetOnGained(Function & func)
{
m_OnGained = std::move(func);
}
/* --------------------------------------------------------------------------------------------
* Retrieve the function bound to the status gained callback.
*/
Function & GetOnGained()
{
return m_OnGained;
}
/* --------------------------------------------------------------------------------------------
* Release all script resources. Recursively forward request to all classes, units and entries.
*/
void Release()
{
// Release objects from this instance
m_OnQuery.Release();
m_OnGained.Release();
m_OnLost.Release();
m_Tag.Release();
m_Data.Release();
}
/* --------------------------------------------------------------------------------------------
* Terminate the all managers by releasing their classes and units and callbacks.
*/
static void Terminate()
{
for (auto & pvm : s_Managers)
{
pvm->Release();
}
}
};
} // Namespace:: SqMod

View File

@ -3,7 +3,7 @@
#include "Base/Color3.hpp"
#include "Base/Vector2.hpp"
#include "Entity/Player.hpp"
#include "Library/Numeric/LongInt.hpp"
#include "Library/Numeric/Long.hpp"
// ------------------------------------------------------------------------------------------------
#include "Misc/Functions.hpp"

View File

@ -1,366 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Misc/Routine.hpp"
#include "Library/Chrono.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstring>
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqRoutineInstance"))
// ------------------------------------------------------------------------------------------------
Routine::Time Routine::s_Last = 0;
Routine::Time Routine::s_Prev = 0;
Routine::Interval Routine::s_Intervals[SQMOD_MAX_ROUTINES];
Routine::Instance Routine::s_Instances[SQMOD_MAX_ROUTINES];
bool Routine::s_Silenced = false;
// ------------------------------------------------------------------------------------------------
void Routine::Process()
{
// Is this the first call?
if (s_Last == 0)
{
s_Last = Chrono::GetCurrentSysTime();
// We'll do it text time
return;
}
// Backup the last known time-stamp
s_Prev = s_Last;
// Get the current time-stamp
s_Last = Chrono::GetCurrentSysTime();
// Calculate the elapsed time
const auto delta = Int32((s_Last - s_Prev) / 1000L);
// Process all active routines
for (Interval * itr = s_Intervals; itr != (s_Intervals + SQMOD_MAX_ROUTINES); ++itr)
{
// Is this routine valid?
if (*itr)
{
// Decrease the elapsed time
(*itr) -= delta;
// Have we completed the routine interval?
if ((*itr) <= 0)
{
// Execute and reset the elapsed time
(*itr) = s_Instances[itr - s_Intervals].Execute();
}
}
}
}
// ------------------------------------------------------------------------------------------------
void Routine::Initialize()
{
std::memset(s_Intervals, 0, sizeof(s_Intervals));
SetSilenced(!ErrorHandling::IsEnabled());
}
// ------------------------------------------------------------------------------------------------
void Routine::Deinitialize()
{
// Release any script resources that the routines might store
for (auto & r : s_Instances)
{
r.Terminate();
}
}
// ------------------------------------------------------------------------------------------------
SQInteger Routine::Create(HSQUIRRELVM vm)
{
// Locate the identifier of a free slot
const SQInteger slot = FindUnused();
// See if we have where to store this routine
if (slot < 0)
{
return sq_throwerror(vm, "Reached the maximum number of active routines");
}
// Grab the top of the stack
const SQInteger top = sq_gettop(vm);
// See if too many arguments were specified
if (top >= 20) /* 5 base + 14 parameters = 19 */
{
return sq_throwerror(vm, "Too many parameters specified");
}
// Was there was an environment specified?
else if (top <= 1)
{
return sq_throwerror(vm, "Missing routine environment");
}
// Was there was a callback specified?
else if (top <= 2)
{
return sq_throwerror(vm, "Missing routine callback");
}
// Validate the callback type
else if (sq_gettype(vm, 3) != OT_CLOSURE && sq_gettype(vm, 3) != OT_NATIVECLOSURE)
{
return sq_throwerror(vm, "Invalid callback type");
}
SQRESULT res = SQ_OK;
// Prepare an object for the environment
HSQOBJECT env;
// Get the type of the environment object
const SQObjectType etype = sq_gettype(vm, 2);
// Whether to default to the root table
bool use_root = etype == OT_NULL;
// Is the specified environment a boolean (true) value?
if (etype == OT_STRING)
{
// Attempt to generate the string value
StackStrF val(vm, 2);
// Have we failed to retrieve the string?
if (SQ_FAILED(val.Proc()))
{
return val.mRes; // Propagate the error!
}
// If the string is empty or "root" then we use the root table
else if (!val.mLen || sqmod_stricmp(val.mPtr, "root") == 0)
{
use_root = true;
}
// If the string is "self" then we leave it null and default to self
else if (sqmod_stricmp(val.mPtr, "self") == 0)
{
sq_resetobject(&env); // Make sure environment is null
use_root = false; // Just in case
}
}
// Is the specified environment a null value?
if (use_root)
{
// Push the root table on the stack
sq_pushroottable(vm);
// Attempt to retrieve the table object
res = sq_getstackobj(vm, -1, &env);
// Preserve the stack state
sq_poptop(vm);
}
// Should we treat it as a valid environment object?
else if (etype != OT_STRING)
{
sq_getstackobj(vm, 2, &env); // Just retrieve the specified environment
}
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// Prepare an object for the function
HSQOBJECT func;
// Fetch the specified callback object
res = sq_getstackobj(vm, 3, &func);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// The number of iterations and interval to execute the routine
SQInteger intrv = 0, itr = 0;
// Was there an interval specified?
if (top > 3)
{
// Grab the interval from the stack
res = sq_getinteger(vm, 4, &intrv);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
}
// Was there a number of iterations specified?
if (top > 4)
{
// Grab the iterations from the stack
res = sq_getinteger(vm, 5, &itr);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
}
// Attempt to create a routine instance
try
{
DeleteGuard< Routine > dg(new Routine());
ClassType< Routine >::PushInstance(vm, dg.Get());
dg.Release();
}
catch (const Sqrat::Exception & e)
{
return sq_throwerror(vm, "Unable to create the routine instance");
}
// Prepare an object for the routine
HSQOBJECT obj;
// Fetch the created routine object
res = sq_getstackobj(vm, -1, &obj);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// At this point we can grab a reference to our slot
Instance & inst = s_Instances[slot];
// Were there any arguments specified?
if (top > 5)
{
// Grab a pointer to the arguments array
Argument * args = inst.mArgv;
// Reset the argument counter
inst.mArgc = 0;
// Grab the specified arguments from the stack
for (SQInteger i = 6; i <= top; ++i)
{
res = sq_getstackobj(vm, i, &(args[inst.mArgc].mObj));
// Validate the result
if (SQ_FAILED(res))
{
// Clear previous arguments
inst.Clear();
// Propagate the error
return res;
}
// Keep a strong reference to the argument
sq_addref(vm, &(args[inst.mArgc].mObj));
// Increase the argument counter
++inst.mArgc;
}
}
// Attempt to retrieve the routine from the stack and associate it with the slot
try
{
Var< Routine * >(vm, -1).value->m_Slot = ConvTo< Uint32 >::From(slot);
}
catch (const Sqrat::Exception & e)
{
// Clear extracted arguments
inst.Clear();
// Now it's safe to throw the error
return sq_throwerror(vm, "Unable to create the routine instance");
}
// Alright, at this point we can initialize the slot
inst.Init(env, func, obj, intrv, static_cast< Iterator >(itr));
// Now initialize the timer
s_Intervals[slot] = intrv;
// We have the created routine on the stack, so let's return it
return 1;
}
// ------------------------------------------------------------------------------------------------
bool Routine::IsWithTag(StackStrF & tag)
{
// Is the specified tag valid?
if (tag.mPtr != nullptr)
{
// Iterate routine list
for (const auto & r : s_Instances)
{
if (!r.mInst.IsNull() && r.mTag == tag.mPtr)
{
return true; // Yup, we're doing this
}
}
}
// Unable to find such routine
return false;
}
// ------------------------------------------------------------------------------------------------
bool Routine::TerminateWithTag(StackStrF & tag)
{
// Is the specified tag valid?
if (tag.mPtr != nullptr)
{
// Iterate routine list
for (auto & r : s_Instances)
{
if (!r.mInst.IsNull() && r.mTag == tag.mPtr)
{
r.Terminate(); // Yup, we're doing this
return true; // A routine was terminated
}
}
}
// Unable to find such routine
return false;
}
/* ------------------------------------------------------------------------------------------------
* Forward the call to process routines.
*/
void ProcessRoutines()
{
Routine::Process();
}
/* ------------------------------------------------------------------------------------------------
* Forward the call to initialize routines.
*/
void InitializeRoutines()
{
Routine::Initialize();
}
/* ------------------------------------------------------------------------------------------------
* Forward the call to terminate routines.
*/
void TerminateRoutines()
{
Routine::Deinitialize();
}
// ================================================================================================
void Register_Routine(HSQUIRRELVM vm)
{
RootTable(vm).Bind(Typename::Str,
Class< Routine, NoConstructor< Routine > >(vm, Typename::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &Typename::Fn)
.Func(_SC("_tostring"), &Routine::ToString)
// Properties
.Prop(_SC("Tag"), &Routine::GetTag, &Routine::SetTag)
.Prop(_SC("Env"), &Routine::GetEnv, &Routine::SetEnv)
.Prop(_SC("Func"), &Routine::GetFunc, &Routine::SetFunc)
.Prop(_SC("Data"), &Routine::GetData, &Routine::SetData)
.Prop(_SC("Interval"), &Routine::GetInterval, &Routine::SetInterval)
.Prop(_SC("Iterations"), &Routine::GetIterations, &Routine::SetIterations)
.Prop(_SC("Suspended"), &Routine::GetSuspended, &Routine::SetSuspended)
.Prop(_SC("Quiet"), &Routine::GetQuiet, &Routine::SetQuiet)
.Prop(_SC("Endure"), &Routine::GetEndure, &Routine::SetEndure)
.Prop(_SC("Arguments"), &Routine::GetArguments)
// Member Methods
.FmtFunc(_SC("SetTag"), &Routine::ApplyTag)
.Func(_SC("SetData"), &Routine::ApplyData)
.Func(_SC("SetInterval"), &Routine::ApplyInterval)
.Func(_SC("SetIterations"), &Routine::ApplyIterations)
.Func(_SC("SetSuspended"), &Routine::ApplySuspended)
.Func(_SC("SetQuiet"), &Routine::AppplyQuiet)
.Func(_SC("SetEndure"), &Routine::ApplyEndure)
.Func(_SC("Terminate"), &Routine::Terminate)
.Func(_SC("GetArgument"), &Routine::GetArgument)
.Func(_SC("DropEnv"), &Routine::DropEnv)
.StaticFunc(_SC("UsedCount"), &Routine::GetUsed)
.StaticFunc(_SC("AreSilenced"), &Routine::GetSilenced)
.StaticFunc(_SC("SetSilenced"), &Routine::SetSilenced)
);
// Global functions
RootTable(vm).SquirrelFunc(_SC("SqRoutine"), &Routine::Create);
RootTable(vm).FmtFunc(_SC("SqFindRoutineByTag"), &Routine::FindByTag);
RootTable(vm).FmtFunc(_SC("SqIsRoutineWithTag"), &Routine::IsWithTag);
RootTable(vm).FmtFunc(_SC("SqTerminateRoutineWithTag"), &Routine::TerminateWithTag);
}
} // Namespace:: SqMod

View File

@ -1,678 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Execute callbacks after specific intervals of time.
*/
class Routine
{
public:
/* --------------------------------------------------------------------------------------------
* Simplify future changes to a single point of change.
*/
typedef Int64 Time;
typedef SQInteger Interval;
typedef Uint32 Iterator;
typedef LightObj Argument;
private:
/* --------------------------------------------------------------------------------------------
* Structure that represents an active routine and keeps track of the routine information.
*/
struct Instance
{
// ----------------------------------------------------------------------------------------
LightObj mEnv; // A reference to the managed environment object.
LightObj mFunc; // A reference to the managed function object.
LightObj mInst; // Reference to the routine associated with this instance.
LightObj mData; // A reference to the arbitrary data associated with this instance.
String mTag; // An arbitrary string which represents the tag.
Iterator mIterations; // Number of iterations before self destruct.
Interval mInterval; // Interval between routine invocations.
bool mSuspended; // Whether this instance is allowed to receive calls.
bool mQuiet; // Whether this instance is allowed to handle errors.
bool mEndure; // Whether this instance is allowed to terminate itself on errors.
bool mExecuting; // Whether this instance is currently being executed.
Uint8 mArgc; // The number of arguments that the routine must forward.
Argument mArgv[14]; // The arguments that the routine must forward.
/* ----------------------------------------------------------------------------------------
* Default constructor.
*/
Instance() noexcept
: mEnv()
, mFunc()
, mInst()
, mData()
, mTag()
, mIterations(0)
, mInterval(0)
, mSuspended(false)
, mQuiet(GetSilenced())
, mEndure(false)
, mExecuting(false)
, mArgc(0)
, mArgv()
{
/* ... */
}
/* ----------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
Instance(const Instance & o) = delete;
/* ----------------------------------------------------------------------------------------
* Move constructor. (disabled)
*/
Instance(Instance && o) = delete;
/* ----------------------------------------------------------------------------------------
* Destructor.
*/
~Instance()
{
Terminate();
}
/* ----------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
Instance & operator = (const Instance & o) = delete;
/* ----------------------------------------------------------------------------------------
* Move assignment operator. (disabled)
*/
Instance & operator = (Instance && o) = delete;
/* ----------------------------------------------------------------------------------------
* Initializes the routine parameters. (assumes previous values are already released)
*/
void Init(HSQOBJECT & env, HSQOBJECT & func, HSQOBJECT & inst, Interval intrv, Iterator itr)
{
// Initialize the callback objects
mEnv = LightObj{env};
mFunc = LightObj{func};
// Associate with the routine instance
mInst = LightObj{inst};
// Initialize the routine options
mIterations = itr;
mInterval = intrv;
// This can't be true now
mExecuting = false;
}
/* ----------------------------------------------------------------------------------------
* Release managed script resources.
*/
void Release()
{
mEnv.Release();
mFunc.Release();
mInst.Release();
mData.Release();
mIterations = 0;
mInterval = 0;
mTag.clear();
}
/* ----------------------------------------------------------------------------------------
* Execute the managed routine.
*/
Interval Execute()
{
// Is this even a valid routine?
if (mInst.IsNull())
{
return 0; // Dunno how we got here but it ends now
}
// Are we allowed to forward calls?
else if (!mSuspended)
{
// Grab the virtual machine once
HSQUIRRELVM vm = SqVM();
// Push the function on the stack
sq_pushobject(vm, mFunc);
// Push the environment on the stack
if (!mEnv.IsNull())
{
sq_pushobject(vm, mEnv); // Push object
}
else
{
sq_pushobject(vm, mInst); // Push self
}
// Push function parameters, if any
for (Uint32 n = 0; n < mArgc; ++n)
{
sq_pushobject(vm, mArgv[n].mObj);
}
// This routine is currently executing
mExecuting = true;
// Make the function call and store the result
const SQRESULT res = sq_call(vm, mArgc + 1, static_cast< SQBool >(false), static_cast< SQBool >(!mQuiet));
// This routine has finished executing
mExecuting = false;
// Pop the callback object from the stack
sq_pop(vm, 1);
// Validate the result
if (SQ_FAILED(res))
{
// Should we endure the errors?
if (!mEndure)
{
Terminate(); // Destroy our self on error
}
}
}
// Decrease the number of iterations if necessary
if (mIterations && (--mIterations) == 0)
{
Terminate(); // This routine reached the end of it's life
}
// Return the current interval
return mInterval;
}
/* ----------------------------------------------------------------------------------------
* Clear the arguments.
*/
void Clear()
{
// Now release the arguments
for (auto & a : mArgv)
{
a.Release();
}
// Reset the counter
mArgc = 0;
}
/* ----------------------------------------------------------------------------------------
* Terminate the routine.
*/
void Terminate()
{
Release();
Clear();
}
};
private:
// --------------------------------------------------------------------------------------------
static Time s_Last; // Last time point.
static Time s_Prev; // Previous time point.
static Interval s_Intervals[SQMOD_MAX_ROUTINES]; // List of intervals to be processed.
static Instance s_Instances[SQMOD_MAX_ROUTINES]; // List of routines to be executed.
static bool s_Silenced; // Error reporting independent from global setting.
private:
/* --------------------------------------------------------------------------------------------
* The index of the slot in the pool of active routines.
*/
Uint32 m_Slot;
protected:
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
Routine()
: m_Slot(SQMOD_MAX_ROUTINES)
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
explicit Routine(Uint32 slot)
: m_Slot(slot)
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Find an unoccupied routine slot.
*/
static SQInteger FindUnused()
{
for (const auto & r : s_Instances)
{
// Either not used or not currently being executing
if (r.mInst.IsNull() && !(r.mExecuting))
{
return (&r - s_Instances); // Return the index of this element
}
}
// No available slot
return -1;
}
public:
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
~Routine()
{
if (m_Slot < SQMOD_MAX_ROUTINES)
{
Terminate();
}
}
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
Routine(const Routine & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor. (disabled)
*/
Routine(Routine && o) = delete;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
Routine & operator = (const Routine & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator. (disabled)
*/
Routine & operator = (Routine && o) = delete;
/* --------------------------------------------------------------------------------------------
* Retrieve the number of used routine slots.
*/
static SQInteger GetUsed()
{
SQInteger n = 0;
// Iterate routine list
for (const auto & r : s_Instances)
{
if (!r.mInst.IsNull())
{
++n;
}
}
// Return the final count
return n;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the number of used routine slots.
*/
static const LightObj & FindByTag(StackStrF & tag)
{
// Is the specified tag valid?
if (!tag.mPtr)
{
STHROWF("Invalid routine tag");
}
// Iterate routine list
for (const auto & r : s_Instances)
{
if (!r.mInst.IsNull() && r.mTag == tag.mPtr)
{
return r.mInst; // Return this routine instance
}
}
// Unable to find such routine
STHROWF("Unable to find a routine with tag (%s)", tag.mPtr);
// Should not reach this point but if it did, we have to return something
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warray-bounds"
#endif
return s_Instances[SQMOD_MAX_ROUTINES].mInst; // Intentional Buffer overflow!
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}
/* --------------------------------------------------------------------------------------------
* Check if a routine with a certain tag exists.
*/
static bool IsWithTag(StackStrF & tag);
/* --------------------------------------------------------------------------------------------
* Check if a routine with a certain tag exists.
*/
static bool TerminateWithTag(StackStrF & tag);
/* --------------------------------------------------------------------------------------------
* Process all active routines and update elapsed time.
*/
static void Process();
/* --------------------------------------------------------------------------------------------
* Initialize all resources and prepare for startup.
*/
static void Initialize();
/* --------------------------------------------------------------------------------------------
* Release all resources and prepare for shutdown.
*/
static void Deinitialize();
/* --------------------------------------------------------------------------------------------
* Create a routine with the specified parameters.
*/
static SQInteger Create(HSQUIRRELVM vm);
protected:
/* --------------------------------------------------------------------------------------------
* See whether this routine is valid otherwise throw an exception.
*/
void Validate() const
{
if (m_Slot >= SQMOD_MAX_ROUTINES)
{
STHROWF("This instance does not reference a valid routine");
}
}
/* --------------------------------------------------------------------------------------------
* See whether this routine is valid otherwise throw an exception.
*/
Instance & GetValid() const
{
if (m_Slot >= SQMOD_MAX_ROUTINES)
{
STHROWF("This instance does not reference a valid routine");
}
// We know it's valid so let's return it
return s_Instances[m_Slot];
}
public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
const String & ToString() const
{
return (m_Slot >= SQMOD_MAX_ROUTINES) ? NullString() : s_Instances[m_Slot].mTag;
}
/* --------------------------------------------------------------------------------------------
* Terminate the routine.
*/
void Terminate()
{
GetValid().Terminate();
s_Intervals[m_Slot] = 0;
m_Slot = SQMOD_MAX_ROUTINES;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the associated user tag.
*/
const String & GetTag() const
{
return GetValid().mTag;
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user tag.
*/
void SetTag(StackStrF & tag)
{
GetValid().mTag.assign(tag.mPtr, static_cast< size_t >(ClampMin(tag.mLen, 0)));
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user tag.
*/
Routine & ApplyTag(StackStrF & tag)
{
SetTag(tag);
return *this;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the environment object.
*/
const LightObj & GetEnv() const
{
return GetValid().mEnv;
}
/* --------------------------------------------------------------------------------------------
* Modify the environment object.
*/
void SetEnv(const LightObj & env)
{
GetValid().mEnv = env.IsNull() ? LightObj(RootTable().GetObj()) : env;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the function object.
*/
const LightObj & GetFunc() const
{
return GetValid().mFunc;
}
/* --------------------------------------------------------------------------------------------
* Modify the function object.
*/
void SetFunc(const Function & func)
{
// Validate the specified
if (!sq_isclosure(func.GetFunc()) && !sq_isnativeclosure(func.GetFunc()))
{
STHROWF("Invalid callback type %s", SqTypeName(GetValid().mFunc.GetType()));
}
// Store the function without the environment
GetValid().mFunc = LightObj(func.GetFunc());
}
/* --------------------------------------------------------------------------------------------
* Retrieve the arbitrary user data object.
*/
const LightObj & GetData() const
{
return GetValid().mData;
}
/* --------------------------------------------------------------------------------------------
* Modify the arbitrary user data object.
*/
void SetData(const LightObj & data)
{
GetValid().mData = data;
}
/* --------------------------------------------------------------------------------------------
* Modify the arbitrary user data object.
*/
Routine & ApplyData(const LightObj & data)
{
SetData(data);
return *this;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the execution interval.
*/
SQInteger GetInterval() const
{
return ConvTo< SQInteger >::From(GetValid().mInterval);
}
/* --------------------------------------------------------------------------------------------
* Modify the execution interval.
*/
void SetInterval(SQInteger itr)
{
GetValid().mInterval = ClampMin(ConvTo< Interval >::From(itr), static_cast< Interval >(0));
}
/* --------------------------------------------------------------------------------------------
* Modify the execution interval.
*/
Routine & ApplyInterval(SQInteger itr)
{
SetInterval(itr);
return *this;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the number of iterations.
*/
SQInteger GetIterations() const
{
return ConvTo< SQInteger >::From(GetValid().mIterations);
}
/* --------------------------------------------------------------------------------------------
* Modify the number of iterations.
*/
void SetIterations(SQInteger itr)
{
GetValid().mIterations = ConvTo< Iterator >::From(itr);
}
/* --------------------------------------------------------------------------------------------
* Modify the number of iterations.
*/
Routine & ApplyIterations(SQInteger itr)
{
SetIterations(itr);
return *this;
}
/* --------------------------------------------------------------------------------------------
* See whether the routine is suspended.
*/
bool GetSuspended() const
{
return GetValid().mSuspended;
}
/* --------------------------------------------------------------------------------------------
* Set whether the routine should be suspended.
*/
void SetSuspended(bool toggle)
{
GetValid().mSuspended = toggle;
}
/* --------------------------------------------------------------------------------------------
* Set whether the routine should be suspended.
*/
Routine & ApplySuspended(bool toggle)
{
SetSuspended(toggle);
return *this;
}
/* --------------------------------------------------------------------------------------------
* See whether the routine is quite.
*/
bool GetQuiet() const
{
return GetValid().mQuiet;
}
/* --------------------------------------------------------------------------------------------
* Set whether the routine should be quiet.
*/
void SetQuiet(bool toggle)
{
GetValid().mQuiet = toggle;
}
/* --------------------------------------------------------------------------------------------
* Set whether the routine should be quiet.
*/
Routine & AppplyQuiet(bool toggle)
{
SetQuiet(toggle);
return *this;
}
/* --------------------------------------------------------------------------------------------
* See whether the routine endures.
*/
bool GetEndure() const
{
return GetValid().mEndure;
}
/* --------------------------------------------------------------------------------------------
* Set whether the routine should endure.
*/
void SetEndure(bool toggle)
{
GetValid().mEndure = toggle;
}
/* --------------------------------------------------------------------------------------------
* Set whether the routine should endure.
*/
Routine & ApplyEndure(bool toggle)
{
SetEndure(toggle);
return *this;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the number of arguments to be forwarded.
*/
SQInteger GetArguments() const
{
return ConvTo< SQInteger >::From(GetValid().mArgc);
}
/* --------------------------------------------------------------------------------------------
* Retrieve a certain argument.
*/
const Argument & GetArgument(SQInteger arg) const
{
// Cast the index to the proper value
Uint8 idx = ConvTo< Uint8 >::From(arg);
// Validate the specified index
if (idx >= 14)
{
STHROWF("The specified index is out of range: %u >= %u", idx, 14);
}
// Return the requested argument
return GetValid().mArgv[idx];
}
/* --------------------------------------------------------------------------------------------
* Release the environment object and default to self.
*/
void DropEnv()
{
GetValid().mEnv.Release();
}
/* --------------------------------------------------------------------------------------------
* See if error reporting is enabled for all newlly created routines.
*/
static bool GetSilenced()
{
return s_Silenced;
}
/* --------------------------------------------------------------------------------------------
* Set if error reporting should be enabled for all newlly created routines.
*/
static void SetSilenced(bool toggle)
{
s_Silenced = toggle;
}
};
} // Namespace:: SqMod

File diff suppressed because it is too large Load Diff

View File

@ -1,763 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
#include <vector>
#include <utility>
#include <algorithm>
#include <functional>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
struct Signal;
struct SignalWrapper;
/* ------------------------------------------------------------------------------------------------
* Class used to deliver events to one or more listeners.
*/
struct Signal
{
friend class SignalWrapper;
// --------------------------------------------------------------------------------------------
typedef unsigned int SizeType; // Type of value used to represent sizes and/or indexes.
// --------------------------------------------------------------------------------------------
enum { SMB_SIZE = 8 };
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
Signal();
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
explicit Signal(const char * name)
: Signal(String(name))
{
//...
}
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
explicit Signal(const String & name)
: Signal(String(name))
{
//...
}
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
explicit Signal(String && name);
/* --------------------------------------------------------------------------------------------
* Copy constructor (disabled).
*/
Signal(const Signal & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor (disabled).
*/
Signal(Signal && o) = delete;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~Signal();
/* --------------------------------------------------------------------------------------------
* Copy assignment operator (disabled).
*/
Signal & operator = (const Signal & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator (disabled).
*/
Signal & operator = (Signal && o) = delete;
protected:
/* --------------------------------------------------------------------------------------------
* Adjust the internal buffer size if necessary.
*/
bool AdjustSlots(SizeType capacity);
/* --------------------------------------------------------------------------------------------
* Structure responsible for storing information about a slot.
*/
struct Slot {
SQHash mThisHash; // The hash of the specified environment.
SQHash mFuncHash; // The hash of the specified callback.
HSQOBJECT mThisRef; // The specified script environment.
HSQOBJECT mFuncRef; // The specified script callback.
/* ----------------------------------------------------------------------------------------
* Default constructor.
*/
Slot()
: mThisHash(0)
, mFuncHash(0)
, mThisRef()
, mFuncRef()
{
sq_resetobject(&mThisRef);
sq_resetobject(&mFuncRef);
}
/* ----------------------------------------------------------------------------------------
* Forwarding constructor.
*/
Slot(Object & env, ::Sqrat::Function & func)
: Slot(env.GetObj(), func.GetFunc())
{
/* ... */
}
/* ----------------------------------------------------------------------------------------
* Base constructor.
*/
Slot(HSQOBJECT & env, HSQOBJECT & func)
: mThisHash(0)
, mFuncHash(0)
, mThisRef(env)
, mFuncRef(func)
{
HSQUIRRELVM vm = SqVM();
// Remember the current stack size
const StackGuard sg(vm);
// Is there an explicit environment?
if (!sq_isnull(mThisRef))
{
// Keep a reference to this environment
sq_addref(vm, &mThisRef);
// Push the environment on the stack
sq_pushobject(vm, mThisRef);
// Grab the hash of the environment object
mThisHash = sq_gethash(vm, -1);
}
// Is there an explicit function?
if (!sq_isnull(mFuncRef))
{
// Keep a reference to this function
sq_addref(vm, &mFuncRef);
// Push the callback on the stack
sq_pushobject(vm, mFuncRef);
// Grab the hash of the callback object
mFuncHash = sq_gethash(vm, -1);
}
}
/* ----------------------------------------------------------------------------------------
* Base constructor.
*/
Slot(HSQOBJECT & env, HSQOBJECT & func, SQHash envh, SQHash funch)
: mThisHash(envh)
, mFuncHash(funch)
, mThisRef(env)
, mFuncRef(func)
{
}
/* ----------------------------------------------------------------------------------------
* Copy constructor.
*/
Slot(const Slot & o)
: mThisHash(o.mThisHash)
, mFuncHash(o.mFuncHash)
, mThisRef(o.mThisRef)
, mFuncRef(o.mFuncRef)
{
// Track reference
if (mFuncHash != 0)
{
sq_addref(SqVM(), &mThisRef);
sq_addref(SqVM(), &mFuncRef);
}
}
/* ----------------------------------------------------------------------------------------
* Move constructor.
*/
Slot(Slot && o) noexcept
: mThisHash(o.mThisHash)
, mFuncHash(o.mFuncHash)
, mThisRef(o.mThisRef)
, mFuncRef(o.mFuncRef)
{
// Take ownership
sq_resetobject(&o.mThisRef);
sq_resetobject(&o.mFuncRef);
}
/* ----------------------------------------------------------------------------------------
* Destructor.
*/
~Slot()
{
Release();
}
/* ----------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
Slot & operator = (const Slot & o)
{
if (this != &o)
{
// Release current resources, if any
Release();
// Replicate data
mThisHash = o.mThisHash;
mFuncHash = o.mFuncHash;
mThisRef = o.mThisRef;
mFuncRef = o.mFuncRef;
// Track reference
sq_addref(SqVM(), &const_cast< HSQOBJECT & >(o.mThisRef));
sq_addref(SqVM(), &const_cast< HSQOBJECT & >(o.mFuncRef));
}
return *this;
}
/* ----------------------------------------------------------------------------------------
* Move assignment operator.
*/
Slot & operator = (Slot && o) noexcept
{
if (this != &o)
{
// Release current resources, if any
Release();
// Replicate data
mThisHash = o.mThisHash;
mFuncHash = o.mFuncHash;
mThisRef = o.mThisRef;
mFuncRef = o.mFuncRef;
// Take ownership
sq_resetobject(&o.mThisRef);
sq_resetobject(&o.mFuncRef);
}
return *this;
}
/* ----------------------------------------------------------------------------------------
* Equality comparison operator.
*/
bool operator == (const Slot & o) const
{
return (mThisHash == o.mThisHash) && (mFuncHash == o.mFuncHash);
}
/* ----------------------------------------------------------------------------------------
* Inequality comparison operator.
*/
bool operator != (const Slot & o) const
{
return (mThisHash != o.mThisHash) || (mFuncHash != o.mFuncHash);
}
/* ----------------------------------------------------------------------------------------
* Release managed script resources.
*/
bool Available() const
{
return (mFuncHash == 0);
}
/* ----------------------------------------------------------------------------------------
* Release managed script resources.
*/
void Release()
{
// Should we release any environment object?
if (mThisHash != 0)
{
sq_release(SqVM(), &mThisRef);
sq_resetobject(&mThisRef);
// Also reset the hash
mThisHash = 0;
}
// Should we release any callback object?
if (mFuncHash != 0)
{
sq_release(SqVM(), &mFuncRef);
sq_resetobject(&mFuncRef);
// Also reset the hash
mFuncHash = 0;
}
}
/* ----------------------------------------------------------------------------------------
* Swap the values of two slots.
*/
void Swap(Slot & s)
{
// Swap the environment hash
SQHash h = mThisHash;
mThisHash = s.mThisHash;
s.mThisHash = h;
// Swap the callback hash
h = mFuncHash;
mFuncHash = s.mFuncHash;
s.mFuncHash = h;
// Swap the environment object
HSQOBJECT o = mThisRef;
mThisRef = s.mThisRef;
s.mThisRef = o;
// Swap the callback object
o = mFuncRef;
mFuncRef = s.mFuncRef;
s.mFuncRef = o;
}
};
// --------------------------------------------------------------------------------------------
typedef Slot ValueType; // Value type used to represent a slot.
typedef ValueType & Reference; // Reference to the stored value type
typedef const ValueType & ConstReference; // Constant reference to the stored value type.
typedef ValueType * Pointer; // Pointer to the stored value type
typedef const ValueType * ConstPointer; // Constant pointer to the stored value type.
// --------------------------------------------------------------------------------------------
/// Execution scope used to adjust iterators when removing slots or adjusting the buffer.
struct Scope {
// ----------------------------------------------------------------------------------------
Pointer mItr; ///< Currently executed slot.
Pointer mEnd; ///< Where the execution ends.
Scope * mParent; ///< Previous execution scope.
Scope * mChild; ///< Next execution scope.
// ----------------------------------------------------------------------------------------
/// Default constructor.
Scope(Scope * parent, Pointer begin, Pointer end)
: mItr(begin), mEnd(end), mParent(parent), mChild(nullptr)
{
if (mParent != nullptr) mParent->mChild = this;
}
// ----------------------------------------------------------------------------------------
/// Destructor.
~Scope() {
if (mParent != nullptr) mParent->mChild = nullptr;
}
// ----------------------------------------------------------------------------------------
/// Adjust the iterators to account for the fact that the specified slot was removed.
void Descend(Pointer ptr);
/// Adjust the iterators to account for the fact that the specified slot is now leading.
void Lead(Pointer ptr);
/// Adjust the iterators to account for the fact that the specified slot is now tailing.
void Tail(Pointer ptr);
/// Adjust the iterators to finish the execution abruptly.
void Finish();
};
private:
// --------------------------------------------------------------------------------------------
SizeType m_Used; // The number of stored slots that are valid.
SizeType m_Size; // The size of the memory allocated for slots.
Pointer m_Slots; // Pointer to the memory containing the slots.
// --------------------------------------------------------------------------------------------
Scope * m_Scope; // Current execution state.
// --------------------------------------------------------------------------------------------
String m_Name; // The name that identifies this signal.
LightObj m_Data; // User data associated with this instance.
// --------------------------------------------------------------------------------------------
ValueType m_SMB[SMB_SIZE]{}; // Small buffer optimization.
public:
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
const String & ToString() const
{
return m_Name;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the associated user data.
*/
LightObj & GetData()
{
return m_Data;
}
/* --------------------------------------------------------------------------------------------
* Modify the associated user data.
*/
void SetData(LightObj & data)
{
m_Data = data;
}
/* --------------------------------------------------------------------------------------------
* The number of slots connected to the signal.
*/
SQInteger GetUsed() const
{
return static_cast< SQInteger >(m_Used);
}
/* --------------------------------------------------------------------------------------------
* Clear all slots connected to the signal.
*/
void ClearSlots();
/* --------------------------------------------------------------------------------------------
* See if there are any slots connected.
*/
bool IsEmpty() const
{
return (m_Used == 0);
}
protected:
/* --------------------------------------------------------------------------------------------
* Connect the specified slot to the signal.
*/
SQInteger Connect(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Connect the specified slot but not before disconnecting all other occurrences.
*/
SQInteger ConnectOnce(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Disconnect all occurrences of the specified slot from the signal.
*/
SQInteger Disconnect(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* See if the specified slot is connected to the signal.
*/
SQInteger Exists(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* See if the specified slot environment is connected to the signal.
*/
SQInteger ExistsThis(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* See if the specified slot callback is connected to the signal.
*/
SQInteger ExistsFunc(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Count all occurrences of the specified slot.
*/
SQInteger Count(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Count all occurrences of the specified slot environment.
*/
SQInteger CountThis(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Count all occurrences of the specified slot callback.
*/
SQInteger CountFunc(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Move all occurrences of the specified slot to the front.
*/
SQInteger Lead(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Move all occurrences of the specified slot environment to the front.
*/
SQInteger LeadThis(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Move all occurrences of the specified slot callback to the front.
*/
SQInteger LeadFunc(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Move all occurrences of the specified slot to the back.
*/
SQInteger Tail(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Move all occurrences of the specified slot environment to the back.
*/
SQInteger TailThis(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Move all occurrences of the specified slot callback to the back.
*/
SQInteger TailFunc(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Remove all occurrences of the specified slot.
*/
SQInteger Eliminate(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Remove all occurrences of the specified slot environment.
*/
SQInteger EliminateThis(SignalWrapper & w);
/* --------------------------------------------------------------------------------------------
* Remove all occurrences of the specified slot callback.
*/
SQInteger EliminateFunc(SignalWrapper & w);
public:
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Connect` method of this class.
*/
static SQInteger SqConnect(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `ConnectOnce` method of this class.
*/
static SQInteger SqConnectOnce(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Exists` method of this class.
*/
static SQInteger SqExists(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Disconnect` method of this class.
*/
static SQInteger SqDisconnect(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `ExistsThis` method of this class.
*/
static SQInteger SqExistsThis(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `ExistsFunc` method of this class.
*/
static SQInteger SqExistsFunc(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Count` method of this class.
*/
static SQInteger SqCount(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `CountThis` method of this class.
*/
static SQInteger SqCountThis(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `CountFunc` method of this class.
*/
static SQInteger SqCountFunc(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Lead` method of this class.
*/
static SQInteger SqLead(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `LeadThis` method of this class.
*/
static SQInteger SqLeadThis(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `LeadFunc` method of this class.
*/
static SQInteger SqLeadFunc(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Tail` method of this class.
*/
static SQInteger SqTail(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `TailThis` method of this class.
*/
static SQInteger SqTailThis(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `TailFunc` method of this class.
*/
static SQInteger SqTailFunc(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Eliminate` method of this class.
*/
static SQInteger SqEliminate(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `EliminateThis` method of this class.
*/
static SQInteger SqEliminateThis(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `EliminateFunc` method of this class.
*/
static SQInteger SqEliminateFunc(HSQUIRRELVM vm);
protected:
/* --------------------------------------------------------------------------------------------
* Emit the event to the connected slots.
*/
SQInteger Emit(HSQUIRRELVM vm, SQInteger top);
/* --------------------------------------------------------------------------------------------
* Emit the event to the connected slots and collect returned values.
*/
SQInteger Query(HSQUIRRELVM vm, SQInteger top);
/* --------------------------------------------------------------------------------------------
* Emit the event to the connected slots and see if they consume it.
*/
SQInteger Consume(HSQUIRRELVM vm, SQInteger top);
/* --------------------------------------------------------------------------------------------
* Emit the event to the connected slots and see if they approve it.
*/
SQInteger Approve(HSQUIRRELVM vm, SQInteger top);
/* --------------------------------------------------------------------------------------------
* Emit the event to the connected slots and see if they return something.
*/
SQInteger Request(HSQUIRRELVM vm, SQInteger top);
public:
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Emit` method of this class.
*/
static SQInteger SqEmit(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Query` method of this class.
*/
static SQInteger SqQuery(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Consume` method of this class.
*/
static SQInteger SqConsume(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Approve` method of this class.
*/
static SQInteger SqApprove(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Squirrel wrapper for the `Request` method of this class.
*/
static SQInteger SqRequest(HSQUIRRELVM vm);
protected:
// --------------------------------------------------------------------------------------------
typedef std::pair< std::size_t, SignalPair > SignalElement;
typedef std::vector< SignalElement > SignalPool;
typedef std::vector< Signal * > FreeSignals;
// --------------------------------------------------------------------------------------------
static SignalPool s_Signals; // List of all created signals.
static FreeSignals s_FreeSignals; // List of signals without a name.
/* --------------------------------------------------------------------------------------------
* Specialization for when there are no arguments given.
*/
void PushParameters()
{
//...
}
/* --------------------------------------------------------------------------------------------
* Specialization for when there's only one argument given/remaining.
*/
template < typename T > void PushParameters(T v)
{
Var< T >::push(SqVM(), v);
}
/* --------------------------------------------------------------------------------------------
* Specialization for when there's more than one argument given.
*/
template < typename T, typename... Args > void PushParameters(T v, Args... args)
{
Var< T >::push(SqVM(), v);
PushParameters(args...);
}
public:
/* --------------------------------------------------------------------------------------------
* Terminate all signal instances and release any script resources.
*/
static void Terminate();
/* --------------------------------------------------------------------------------------------
* Create a free signal without a specific name.
*/
static LightObj CreateFree();
/* --------------------------------------------------------------------------------------------
* Create a new signal with the specified name.
*/
static LightObj Create(StackStrF & name);
/* --------------------------------------------------------------------------------------------
* Remove the signal with the specified name.
*/
static void Remove(StackStrF & name);
/* --------------------------------------------------------------------------------------------
* Retrieve the signal with the specified name.
*/
static const LightObj & Fetch(StackStrF & name);
/* --------------------------------------------------------------------------------------------
* Emit a signal from the module.
*/
template < typename... Args > void operator () (Args&&... args)
{
// Are there any slots connected?
if (!m_Used) return;
// Enter a new execution scope
Scope scope(m_Scope, m_Slots, m_Slots + m_Used);
// Activate the current scope and create a guard to restore it
const AutoAssign< Scope * > aa(m_Scope, scope.mParent, &scope);
// Grab the default virtual machine
HSQUIRRELVM vm = SqVM();
// Process the slots from this scope
while (scope.mItr != scope.mEnd)
{
// Grab a reference to the current slot
const Slot & slot = *(scope.mItr++);
// Push the callback object
sq_pushobject(vm, slot.mFuncRef);
// Is there an explicit environment?
if (slot.mThisHash == 0)
{
sq_pushroottable(vm);
}
else
{
sq_pushobject(vm, slot.mThisRef);
}
// Push the given parameters on the stack
PushParameters(args...);
// Make the function call and store the result
const SQRESULT res = sq_call(vm, 1 + sizeof...(Args), static_cast< SQBool >(false), static_cast< SQBool >(ErrorHandling::IsEnabled()));
// Pop the callback object from the stack
sq_pop(vm, 1);
// Validate the result
if (SQ_FAILED(res))
{
SQTHROW(vm, LastErrorString(vm)); // Stop emitting signals NOLINT(hicpp-exception-baseclass,cert-err60-cpp)
}
}
}
};
} // Namespace:: SqMod

View File

@ -1,521 +0,0 @@
// ------------------------------------------------------------------------------------------------
#include "Tasks.hpp"
#include "Core.hpp"
#include "Library/Chrono.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstring>
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
SQMODE_DECL_TYPENAME(Typename, _SC("SqTask"))
// ------------------------------------------------------------------------------------------------
Tasks::Time Tasks::s_Last = 0;
Tasks::Time Tasks::s_Prev = 0;
Tasks::Interval Tasks::s_Intervals[SQMOD_MAX_TASKS];
Tasks::Task Tasks::s_Tasks[SQMOD_MAX_TASKS];
// ------------------------------------------------------------------------------------------------
void Tasks::Task::Init(HSQOBJECT & func, HSQOBJECT & inst, Interval intrv, Iterator itr, Int32 id, Int32 type)
{
// Initialize the callback hash
mHash = 0;
// Initialize the callback objects
mFunc = LightObj(func);
mInst = LightObj(inst);
// Initialize the task options
mIterations = itr;
mInterval = intrv;
// Initialize the entity information
mEntity = ConvTo< Int16 >::From(id);
mType = ConvTo< Uint8 >::From(type);
// Grab the virtual machine once
HSQUIRRELVM vm = SqVM();
// Remember the current stack size
const StackGuard sg(vm);
// Is there a valid function?
if (!mFunc.IsNull())
{
// Push the callback on the stack
sq_pushobject(vm, mFunc);
// Grab the hash of the callback object
mHash = sq_gethash(vm, -1);
}
}
// ------------------------------------------------------------------------------------------------
void Tasks::Task::Release()
{
mHash = 0;
mTag.clear();
mFunc.Release();
mInst.Release();
mData.Release();
mIterations = 0;
mInterval = 0;
mEntity = -1;
mType = 0;
}
// ------------------------------------------------------------------------------------------------
Tasks::Interval Tasks::Task::Execute()
{
// Are we even a valid task?
if (INVALID_ENTITY(mEntity))
{
return 0; // Dunno how we got here but it ends now
}
// Grab the virtual machine once
HSQUIRRELVM vm = SqVM();
// Push the function on the stack
sq_pushobject(vm, mFunc);
// Push the environment on the stack
sq_pushobject(vm, mSelf);
// Push function parameters, if any
for (Uint32 n = 0; n < mArgc; ++n)
{
sq_pushobject(vm, mArgv[n].mObj);
}
// Make the function call and store the result
const SQRESULT res = sq_call(vm, mArgc + 1, static_cast< SQBool >(false), static_cast< SQBool >(ErrorHandling::IsEnabled()));
// Pop the callback object from the stack
sq_pop(vm, 1);
// Validate the result
if (SQ_FAILED(res))
{
Terminate(); // Destroy ourself on error
}
// Decrease the number of iterations if necessary
if (mIterations && (--mIterations) == 0)
{
Terminate(); // This routine reached the end of it's life
}
// Return the current interval
return mInterval;
}
// ------------------------------------------------------------------------------------------------
void Tasks::Process()
{
// Is this the first call?
if (s_Last == 0)
{
s_Last = Chrono::GetCurrentSysTime();
// We'll do it text time
return;
}
// Backup the last known time-stamp
s_Prev = s_Last;
// Get the current time-stamp
s_Last = Chrono::GetCurrentSysTime();
// Calculate the elapsed time
const auto delta = Int32((s_Last - s_Prev) / 1000L);
// Process all active tasks
for (Interval * itr = s_Intervals; itr != (s_Intervals + SQMOD_MAX_TASKS); ++itr)
{
// Is this task valid?
if (*itr)
{
// Decrease the elapsed time
(*itr) -= delta;
// Have we completed the routine interval?
if ((*itr) <= 0)
{
// Execute and reset the elapsed time
(*itr) = s_Tasks[itr - s_Intervals].Execute();
}
}
}
}
// ------------------------------------------------------------------------------------------------
void Tasks::Initialize()
{
std::memset(s_Intervals, 0, sizeof(s_Intervals));
// Transform all task instances to script objects
for (auto & t : s_Tasks)
{
// This is fine because they'll always outlive the virtual machine
t.mSelf = LightObj(&t);
}
}
// ------------------------------------------------------------------------------------------------
void Tasks::Register(HSQUIRRELVM vm)
{
RootTable(vm).Bind(Typename::Str,
Class< Task, NoDestructor< Task > >(vm, Typename::Str)
// Meta-methods
.SquirrelFunc(_SC("_typename"), &Typename::Fn)
.Func(_SC("_tostring"), &Task::ToString)
// Properties
.Prop(_SC("Tag"), &Task::GetTag, &Task::SetTag)
.Prop(_SC("Entity"), &Task::GetInst)
.Prop(_SC("Func"), &Task::GetFunc, &Task::SetFunc)
.Prop(_SC("Data"), &Task::GetData, &Task::SetData)
.Prop(_SC("Interval"), &Task::GetInterval, &Task::SetInterval)
.Prop(_SC("Iterations"), &Task::GetIterations, &Task::SetIterations)
.Prop(_SC("Arguments"), &Task::GetArguments)
.Prop(_SC("Inst"), &Task::GetInst)
// Member Methods
.FmtFunc(_SC("SetTag"), &Task::SetTag)
.Func(_SC("Terminate"), &Task::Terminate)
.Func(_SC("GetArgument"), &Task::GetArgument)
// Static functions
.StaticFunc(_SC("Used"), &Tasks::GetUsed)
);
}
// ------------------------------------------------------------------------------------------------
void Tasks::Deinitialize()
{
// Release any script resources that the tasks might store
for (auto & t : s_Tasks)
{
t.Terminate();
t.mSelf.Release();
}
}
// ------------------------------------------------------------------------------------------------
LightObj & Tasks::FindEntity(Int32 id, Int32 type)
{
switch (type)
{
case ENT_BLIP: return Core::Get().GetBlip(id).mObj;
case ENT_CHECKPOINT: return Core::Get().GetCheckpoint(id).mObj;
case ENT_KEYBIND: return Core::Get().GetKeybind(id).mObj;
case ENT_OBJECT: return Core::Get().GetObj(id).mObj;
case ENT_PICKUP: return Core::Get().GetPickup(id).mObj;
case ENT_PLAYER: return Core::Get().GetPlayer(id).mObj;
case ENT_VEHICLE: return Core::Get().GetVehicle(id).mObj;
default: return NullLightObj();
}
}
// ------------------------------------------------------------------------------------------------
SQInteger Tasks::FindUnused()
{
for (const auto & t : s_Tasks)
{
if (INVALID_ENTITY(t.mEntity))
{
return (&t - s_Tasks); // Return the index of this element
}
}
// No available slot
return -1;
}
// ------------------------------------------------------------------------------------------------
SQInteger Tasks::Create(Int32 id, Int32 type, HSQUIRRELVM vm)
{
// Locate the identifier of a free slot
const SQInteger slot = FindUnused();
// See if we have where to store this task
if (slot < 0)
{
return sq_throwerror(vm, "Reached the maximum number of tasks");
}
// Grab the top of the stack
const SQInteger top = sq_gettop(vm);
// See if too many arguments were specified
if (top > 12) /* 4 base + 8 parameters = 12 */
{
return sq_throwerror(vm, "Too many parameters specified");
}
// Was there was a callback specified?
else if (top <= 1)
{
return sq_throwerror(vm, "Missing task callback");
}
// Validate the callback type
else if (sq_gettype(vm, 2) != OT_CLOSURE && sq_gettype(vm, 2) != OT_NATIVECLOSURE)
{
return sq_throwerror(vm, "Invalid callback type");
}
// Prepare an entity instance object
HSQOBJECT inst;
// Attempt to retrieve the entity instance
try
{
inst = FindEntity(id, type).GetObj();
}
catch (const std::exception & e)
{
return sq_throwerror(vm, e.what());
}
// Prepare the function object
HSQOBJECT func;
// Fetch the specified callback
SQRESULT res = sq_getstackobj(vm, 2, &func);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// The number of iterations and interval to execute the task
SQInteger intrv = 0, itr = 0;
// Was there an interval specified?
if (top > 2)
{
// Grab the interval from the stack
res = sq_getinteger(vm, 3, &intrv);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
}
// Was there a number of iterations specified?
if (top > 3)
{
// Grab the iterations from the stack
res = sq_getinteger(vm, 4, &itr);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
}
// At this point we can grab a reference to our slot
Task & task = s_Tasks[slot];
// Were there any arguments specified?
if (top > 4)
{
// Grab a pointer to the arguments array
Argument * args = task.mArgv;
// Reset the argument counter
task.mArgc = 0;
// Grab the specified arguments from the stack
for (SQInteger i = 5; i <= top; ++i)
{
res = sq_getstackobj(vm, i, &(args[task.mArgc].mObj));
// Validate the result
if (SQ_FAILED(res))
{
// Clear previous arguments
task.Clear();
// Propagate the error
return res;
}
// Keep a strong reference to the argument
sq_addref(vm, &(args[task.mArgc].mObj));
// Increase the argument counter
++task.mArgc;
}
}
// Alright, at this point we can initialize the slot
task.Init(func, inst, intrv, static_cast< Iterator >(itr), id, type);
// Now initialize the timer
s_Intervals[slot] = intrv;
// Push the tag instance on the stack
sq_pushobject(vm, task.mSelf);
// Specify that this function returns a value
return 1;
}
// ------------------------------------------------------------------------------------------------
SQInteger Tasks::Find(Int32 id, Int32 type, SQInteger & pos, HSQUIRRELVM vm)
{
// Grab the top of the stack
const SQInteger top = sq_gettop(vm);
// Was there a callback specified?
if (top <= 1)
{
return sq_throwerror(vm, "Missing task callback");
}
SQRESULT res = SQ_OK;
// Grab the hash of the callback object
const SQHash chash = sq_gethash(vm, 2);
// Should we include the iterations in the criteria?
if (top > 3)
{
SQInteger intrv = 0;
// Grab the interval from the stack
res = sq_getinteger(vm, 3, &intrv);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// Attempt to find the requested task
for (const auto & t : s_Tasks)
{
if (t.mHash == chash && t.mEntity == id && t.mType == type && t.mInterval == intrv)
{
pos = static_cast< SQInteger >(&t - s_Tasks); // Store the index of this element
}
}
}
// Should we include the interval in the criteria?
else if (top > 2)
{
SQInteger intrv = 0, sqitr = 0;
// Grab the interval from the stack
res = sq_getinteger(vm, 3, &intrv);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// Grab the iterations from the stack
res = sq_getinteger(vm, 4, &sqitr);
// Validate the result
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// Cast iterations to the right type
const Iterator itr = ConvTo< Iterator >::From(sqitr);
// Attempt to find the requested task
for (const auto & t : s_Tasks)
{
if (t.mHash == chash && t.mEntity == id && t.mType == type && t.mInterval == intrv && t.mIterations == itr)
{
pos = static_cast< SQInteger >(&t - s_Tasks); // Store the index of this element
}
}
}
else
{
// Attempt to find the requested task
for (const auto & t : s_Tasks)
{
if (t.mHash == chash && t.mEntity == id && t.mType == type)
{
pos = static_cast< SQInteger >(&t - s_Tasks); // Store the index of this element
}
}
}
// We could not find such task
return res;
}
// ------------------------------------------------------------------------------------------------
SQInteger Tasks::Remove(Int32 id, Int32 type, HSQUIRRELVM vm)
{
// Default to not found
SQInteger pos = -1;
// Perform a search
SQRESULT res = Find(id, type, pos, vm);
// Did the search failed?
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// Did we find anything?
else if (pos < 0)
{
return sq_throwerror(vm, "Unable to locate such task");
}
else
{
// Release task resources
s_Tasks[pos].Terminate();
// Reset the timer
s_Intervals[pos] = 0;
}
// Specify that we don't return anything
return 0;
}
// ------------------------------------------------------------------------------------------------
SQInteger Tasks::Exists(Int32 id, Int32 type, HSQUIRRELVM vm)
{
// Default to not found
SQInteger pos = -1;
// Perform a search
SQRESULT res = Find(id, type, pos, vm);
// Did the search failed?
if (SQ_FAILED(res))
{
return res; // Propagate the error
}
// Push a boolean on whether this task was found
sq_pushbool(vm, static_cast< SQBool >(pos >= 0));
// Specify that we're returning a value
return 1;
}
// ------------------------------------------------------------------------------------------------
const Tasks::Task & Tasks::FindByTag(Int32 id, Int32 type, StackStrF & tag)
{
// Attempt to find the requested task
for (const auto & t : s_Tasks)
{
if (t.mEntity == id && t.mType == type && t.mTag == tag.mPtr)
{
return t; // Return this task instance
}
}
// Unable to find such task
STHROWF("Unable to find a task with tag (%s)", tag.mPtr);
// Should not reach this point but if it did, we have to return something
return s_Tasks[SQMOD_MAX_TASKS]; // Intentional Buffer overflow!
}
// ------------------------------------------------------------------------------------------------
void Tasks::Cleanup(Int32 id, Int32 type)
{
for (auto & t : s_Tasks)
{
if (t.mEntity == id && t.mType == type)
{
t.Terminate();
// Also disable the timer
s_Intervals[&t - s_Tasks] = 0;
}
}
}
/* ------------------------------------------------------------------------------------------------
* Forward the call to process tasks.
*/
void ProcessTasks()
{
Tasks::Process();
}
/* ------------------------------------------------------------------------------------------------
* Forward the call to initialize tasks.
*/
void InitializeTasks()
{
Tasks::Initialize();
}
/* ------------------------------------------------------------------------------------------------
* Forward the call to register tasks.
*/
void RegisterTask(HSQUIRRELVM vm)
{
Tasks::Register(vm);
}
/* ------------------------------------------------------------------------------------------------
* Forward the call to terminate tasks.
*/
void TerminateTasks()
{
Tasks::Deinitialize();
}
/* ------------------------------------------------------------------------------------------------
* Forward the call to cleanup certain tasks.
*/
void CleanupTasks(Int32 id, Int32 type)
{
Tasks::Cleanup(id, type);
}
} // Namespace:: SqMod

View File

@ -1,524 +0,0 @@
#pragma once
// ------------------------------------------------------------------------------------------------
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Execute callbacks for specific entities after specific intervals of time.
*/
class Tasks
{
public:
/* --------------------------------------------------------------------------------------------
* Simplify future changes to a single point of change.
*/
typedef Int64 Time;
typedef SQInteger Interval;
typedef Uint32 Iterator;
typedef LightObj Argument;
private:
/* --------------------------------------------------------------------------------------------
* Structure that represents a task and keeps track of the task information.
*/
struct Task
{
// ----------------------------------------------------------------------------------------
SQHash mHash; // The hash of the referenced function object.
String mTag; // An arbitrary string which represents the tag.
LightObj mSelf; // A reference to `this`as a script object.
LightObj mFunc; // A reference to the managed function object.
LightObj mInst; // A reference to the associated entity object.
LightObj mData; // A reference to the arbitrary data associated with this instance.
Iterator mIterations; // Number of iterations before self destruct.
Interval mInterval; // Interval between task invocations.
Int16 mEntity; // The identifier of the entity to which is belongs.
Uint8 mType; // The type of the entity to which is belongs.
Uint8 mArgc; // The number of arguments that the task must forward.
Argument mArgv[8]; // The arguments that the task must forward.
/* ----------------------------------------------------------------------------------------
* Default constructor.
*/
Task() noexcept
: mHash(0)
, mTag()
, mSelf()
, mFunc()
, mInst()
, mData()
, mIterations(0)
, mInterval(0)
, mEntity(-1)
, mType(0)
, mArgc(0)
, mArgv()
{
/* ... */
}
/* ----------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
Task(const Task & o) = delete;
/* ----------------------------------------------------------------------------------------
* Move constructor. (disabled)
*/
Task(Task && o) = delete;
/* ----------------------------------------------------------------------------------------
* Release managed script resources.
*/
~Task()
{
Terminate();
}
/* ----------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
Task & operator = (const Task & o) = delete;
/* ----------------------------------------------------------------------------------------
* Move assignment operator. (disabled)
*/
Task & operator = (Task && o) = delete;
/* ----------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
const String & ToString() const
{
return mTag;
}
/* ----------------------------------------------------------------------------------------
* Initializes the task parameters. (assumes previous values are already released)
*/
void Init(HSQOBJECT & inst, HSQOBJECT & func, Interval intrv, Iterator itr, Int32 id, Int32 type);
/* ----------------------------------------------------------------------------------------
* Release managed script resources.
*/
void Release();
/* ----------------------------------------------------------------------------------------
* Execute the managed task.
*/
Interval Execute();
/* ----------------------------------------------------------------------------------------
* Clear the arguments.
*/
void Clear()
{
// Now release the arguments
for (auto & a : mArgv)
{
a.Release();
}
// Reset the counter
mArgc = 0;
}
/* ----------------------------------------------------------------------------------------
* Terminate the task.
*/
void Terminate()
{
Release();
Clear();
}
/* ----------------------------------------------------------------------------------------
* Retrieve the associated user tag.
*/
const String & GetTag() const
{
return mTag;
}
/* ----------------------------------------------------------------------------------------
* Modify the associated user tag.
*/
void SetTag(StackStrF & tag)
{
mTag.assign(tag.mPtr, static_cast< size_t >(ClampMin(tag.mLen, 0)));
}
/* ----------------------------------------------------------------------------------------
* Retrieve the instance to entity instance.
*/
const LightObj & GetInst() const
{
return mInst;
}
/* ----------------------------------------------------------------------------------------
* Retrieve the function object.
*/
const LightObj & GetFunc() const
{
return mFunc;
}
/* ----------------------------------------------------------------------------------------
* Modify the function object.
*/
void SetFunc(const Function & func)
{
// Validate the specified
if (!sq_isclosure(func.GetFunc()) && !sq_isnativeclosure(func.GetFunc()))
{
STHROWF("Invalid callback type %s", SqTypeName(mFunc.GetType()));
}
// Grab the virtual machine once
HSQUIRRELVM vm = SqVM();
// Remember the current stack size
const StackGuard sg(vm);
// Push the callback on the stack
sq_pushobject(vm, func.GetFunc());
// Grab the hash of the callback object
mHash = sq_gethash(vm, -1);
// Now store the function without the environment
mFunc = LightObj(func.GetFunc());
}
/* ----------------------------------------------------------------------------------------
* Retrieve the arbitrary user data object.
*/
const LightObj & GetData() const
{
return mData;
}
/* ----------------------------------------------------------------------------------------
* Modify the arbitrary user data object.
*/
void SetData(const LightObj & data)
{
mData = data;
}
/* ----------------------------------------------------------------------------------------
* Retrieve the execution interval.
*/
SQInteger GetInterval() const
{
return ConvTo< SQInteger >::From(mInterval);
}
/* ----------------------------------------------------------------------------------------
* Modify the execution interval.
*/
void SetInterval(SQInteger itr)
{
mInterval = ClampMin(ConvTo< Interval >::From(itr), static_cast< Interval >(0));
}
/* ----------------------------------------------------------------------------------------
* Retrieve the number of iterations.
*/
SQInteger GetIterations() const
{
return ConvTo< SQInteger >::From(mIterations);
}
/* ----------------------------------------------------------------------------------------
* Modify the number of iterations.
*/
void SetIterations(SQInteger itr)
{
mIterations = ConvTo< Iterator >::From(itr);
}
/* ----------------------------------------------------------------------------------------
* Retrieve the number of arguments to be forwarded.
*/
SQInteger GetArguments() const
{
return ConvTo< SQInteger >::From(mArgc);
}
/* ----------------------------------------------------------------------------------------
* Retrieve a certain argument.
*/
const Argument & GetArgument(SQInteger arg) const
{
constexpr Uint32 argvn = (sizeof(mArgv) / sizeof(mArgv[0]));
// Cast the index to the proper value
Uint8 idx = ConvTo< Uint8 >::From(arg);
// Validate the specified index
if (idx >= argvn)
{
STHROWF("The specified index is out of range: %u >= %u", idx, argvn);
}
// Return the requested argument
return mArgv[idx];
}
};
// --------------------------------------------------------------------------------------------
static Time s_Last; // Last time point.
static Time s_Prev; // Previous time point.
static Interval s_Intervals[SQMOD_MAX_TASKS]; // List of intervals to be processed.
static Task s_Tasks[SQMOD_MAX_TASKS]; // List of tasks to be executed.
public:
/* --------------------------------------------------------------------------------------------
* Copy assignment operator. (disabled)
*/
Tasks & operator = (const Tasks & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move assignment operator. (disabled)
*/
Tasks & operator = (Tasks && o) = delete;
/* --------------------------------------------------------------------------------------------
* Default constructor. (disabled)
*/
Tasks() = delete;
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
Tasks(const Tasks & o) = delete;
/* --------------------------------------------------------------------------------------------
* Move constructor. (disabled)
*/
Tasks(Tasks && o) = delete;
/* --------------------------------------------------------------------------------------------
* Destructor. (disabled)
*/
~Tasks() = delete;
/* --------------------------------------------------------------------------------------------
* Process all active tasks and update elapsed time.
*/
static void Process();
/* --------------------------------------------------------------------------------------------
* Initialize all resources and prepare for startup.
*/
static void Initialize();
/* --------------------------------------------------------------------------------------------
* Register the task class.
*/
static void Register(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Release all resources and prepare for shutdown.
*/
static void Deinitialize();
protected:
/* --------------------------------------------------------------------------------------------
* Retrieve the instance of the specified entity.
*/
static LightObj & FindEntity(Int32 id, Int32 type);
/* --------------------------------------------------------------------------------------------
* Find an unoccupied task slot.
*/
static SQInteger FindUnused();
/* --------------------------------------------------------------------------------------------
* Locate the first task with the specified parameters.
*/
static SQInteger Find(Int32 id, Int32 type, SQInteger & pos, HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Attempt to create a task with the specified parameters.
*/
static SQInteger Create(Int32 id, Int32 type, HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Attempt to remove the task with the specified parameters.
*/
static SQInteger Remove(Int32 id, Int32 type, HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* See if a task with the specified parameters exists.
*/
static SQInteger Exists(Int32 id, Int32 type, HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Cleanup all tasks associated with the specified entity.
*/
static const Task & FindByTag(Int32 id, Int32 type, StackStrF & tag);
public:
/* --------------------------------------------------------------------------------------------
* Retrieve the number of used tasks slots.
*/
static SQInteger GetUsed()
{
SQInteger n = 0;
// Iterate task list
for (const auto & t : s_Tasks)
{
if (VALID_ENTITY(t.mEntity))
{
++n;
}
}
// Return the final count
return n;
}
/* --------------------------------------------------------------------------------------------
* Cleanup all tasks associated with the specified entity.
*/
static void Cleanup(Int32 id, Int32 type);
/* --------------------------------------------------------------------------------------------
* Forwards calls to create tasks.
*/
template < typename Entity, Int32 Type > static SQInteger MakeTask(HSQUIRRELVM vm)
{
// The entity instance
const Entity * inst = nullptr;
// Attempt to extract the instance
try
{
// Fetch the instance from the stack
inst = Var< const Entity * >(vm, 1).value;
// Do we have a valid instance?
if (!inst)
{
STHROWF("Invalid entity instance");
}
// Validate the actual entity instance
inst->Validate();
}
catch (const Sqrat::Exception & e)
{
return sq_throwerror(vm, e.what());
}
// Forward the call and return the result
return Create(inst->GetID(), Type, vm);
}
/* --------------------------------------------------------------------------------------------
* Forwards calls to remove tasks.
*/
template < typename Entity, Int32 Type > static SQInteger DropTask(HSQUIRRELVM vm)
{
// The entity instance
const Entity * inst = nullptr;
// Attempt to extract the instance
try
{
// Fetch the instance from the stack
inst = Var< const Entity * >(vm, 1).value;
// Do we have a valid instance?
if (!inst)
{
STHROWF("Invalid entity instance");
}
// Validate the actual entity instance
inst->Validate();
}
catch (const Sqrat::Exception & e)
{
return sq_throwerror(vm, e.what());
}
// Forward the call and return the result
return Remove(inst->GetID(), Type, vm);
}
/* --------------------------------------------------------------------------------------------
* Forwards calls to check tasks.
*/
template < typename Entity, Int32 Type > static SQInteger DoesTask(HSQUIRRELVM vm)
{
// The entity instance
const Entity * inst = nullptr;
// Attempt to extract the instance
try
{
// Fetch the instance from the stack
inst = Var< const Entity * >(vm, 1).value;
// Do we have a valid instance?
if (!inst)
{
STHROWF("Invalid entity instance");
}
// Validate the actual entity instance
inst->Validate();
}
catch (const Sqrat::Exception & e)
{
return sq_throwerror(vm, e.what());
}
// Forward the call and return the result
return Exists(inst->GetID(), Type, vm);
}
/* --------------------------------------------------------------------------------------------
* Forwards calls to find tasks.
*/
template < typename Entity, Int32 Type > static SQInteger FindTask(HSQUIRRELVM vm)
{
// Was the tag string specified?
if (sq_gettop(vm) <= 1)
{
return sq_throwerror(vm, "Missing tag string");
}
// The entity instance
const Entity * inst = nullptr;
// Attempt to extract the instance
try
{
// Fetch the instance from the stack
inst = Var< const Entity * >(vm, 1).value;
// Do we have a valid instance?
if (!inst)
{
STHROWF("Invalid entity instance");
}
// Validate the actual entity instance
inst->Validate();
}
catch (const Sqrat::Exception & e)
{
return sq_throwerror(vm, e.what());
}
// Attempt to generate the string value
StackStrF tag(vm, 2);
// Have we failed to retrieve the string?
if (SQ_FAILED(tag.Proc(true)))
{
return tag.mRes; // Propagate the error!
}
// Attempt to find the specified task
try
{
// Perform the search
const Task & task = FindByTag(inst->GetID(), Type, tag);
// Now push the instance on the stack
sq_pushobject(vm, task.mSelf.mObj);
}
catch (const Sqrat::Exception & e)
{
return sq_throwerror(vm, e.what());
}
// Specify that this function returns a value
return 1;
}
};
} // Namespace:: SqMod

View File

@ -1,10 +1,6 @@
// ------------------------------------------------------------------------------------------------
#include "Misc/Vehicle.hpp"
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstring>
#include <algorithm>
#include "Core/Utility.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -83,7 +79,7 @@ struct InitCustomVehicleNames
} g_InitCustomVehicleNames{};
// ------------------------------------------------------------------------------------------------
String GetAutomobileName(Uint32 id)
String GetAutomobileName(uint32_t id)
{
if (id > 129 && id < 237)
{
@ -102,7 +98,7 @@ String GetAutomobileName(Uint32 id)
}
// ------------------------------------------------------------------------------------------------
void SetAutomobileName(Uint32 id, StackStrF & name)
void SetAutomobileName(uint32_t id, StackStrF & name)
{
if (id > 129 && id < 237)
{
@ -119,7 +115,7 @@ void SetAutomobileName(Uint32 id, StackStrF & name)
}
// ------------------------------------------------------------------------------------------------
Int32 GetAutomobileID(StackStrF & name)
int32_t GetAutomobileID(StackStrF & name)
{
// Clone the string into an editable version
String str(name.mPtr, static_cast< size_t >(name.mLen));
@ -133,7 +129,7 @@ Int32 GetAutomobileID(StackStrF & name)
return SQMOD_UNKNOWN;
}
// Grab the actual length of the string
const Uint32 len = ConvTo< Uint32 >::From(str.length());
const uint32_t len = ConvTo< uint32_t >::From(str.length());
// Get the most significant characters used to identify a vehicle
CharT a = str[0], b = 0, c = 0, d = str[len-1];
// Look for deeper specifiers
@ -691,11 +687,11 @@ Int32 GetAutomobileID(StackStrF & name)
}
// ------------------------------------------------------------------------------------------------
bool IsAutomobileValid(Int32 id)
bool IsAutomobileValid(int32_t id)
{
try
{
return !GetAutomobileName(static_cast< Uint32 >(id)).empty();
return !GetAutomobileName(static_cast< uint32_t >(id)).empty();
}
catch (...)
{

View File

@ -9,21 +9,21 @@ namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Retrieve the name associated with a vehicle model identifier.
*/
String GetAutomobileName(Uint32 id);
SQMOD_NODISCARD String GetAutomobileName(uint32_t id);
/* ------------------------------------------------------------------------------------------------
* Modify the name associated with a vehicle model identifier.
*/
void SetAutomobileName(Uint32 id, StackStrF & name);
void SetAutomobileName(uint32_t id, StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* Convert a vehicle model name to a vehicle model identifier.
*/
Int32 GetAutomobileID(StackStrF & name);
SQMOD_NODISCARD int32_t GetAutomobileID(StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* See whether the specified vehicle model identifier is valid.
*/
bool IsAutomobileValid(Int32 id);
SQMOD_NODISCARD bool IsAutomobileValid(int32_t id);
} // Namespace:: SqMod

View File

@ -1,11 +1,6 @@
// ------------------------------------------------------------------------------------------------
#include "Misc/Weapon.hpp"
#include "Base/Shared.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include "Core/Utility.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
@ -50,16 +45,16 @@ static String CS_Weapon_Names[] = { // NOLINT(cert-err58-cpp)
/* 70 */ "Suicide", /* 71 */ ""
};
/// Fall back for custom weapon names.
static std::unordered_map<Uint32, String> CS_Custom_Weapon_Names{};
static std::unordered_map<uint32_t, String> CS_Custom_Weapon_Names{};
// ------------------------------------------------------------------------------------------------
static inline bool IsCustomWeapon(Uint32 id)
static inline bool IsCustomWeapon(uint32_t id)
{
return (id > 70);
}
// ------------------------------------------------------------------------------------------------
Uint32 GetWeaponSlot(Uint32 id)
uint32_t GetWeaponSlot(uint32_t id)
{
switch(id) {
case 0:
@ -110,7 +105,7 @@ Uint32 GetWeaponSlot(Uint32 id)
}
// ------------------------------------------------------------------------------------------------
CCStr GetWeaponName(Uint32 id)
const char * GetWeaponName(uint32_t id)
{
// Can we consider this a custom weapon ID?
if (IsCustomWeapon(id))
@ -132,7 +127,7 @@ CCStr GetWeaponName(Uint32 id)
}
// ------------------------------------------------------------------------------------------------
void SetWeaponName(Uint32 id, StackStrF & name)
void SetWeaponName(uint32_t id, StackStrF & name)
{
// Can we consider this a custom weapon ID?
if (IsCustomWeapon(id))
@ -148,9 +143,9 @@ void SetWeaponName(Uint32 id, StackStrF & name)
}
// ------------------------------------------------------------------------------------------------
Uint32 GetCustomWeaponNamePoolSize()
uint32_t GetCustomWeaponNamePoolSize()
{
return static_cast< Uint32 >(CS_Custom_Weapon_Names.size());
return static_cast< uint32_t >(CS_Custom_Weapon_Names.size());
}
// ------------------------------------------------------------------------------------------------
@ -160,7 +155,7 @@ void ClearCustomWeaponNamePool()
}
// ------------------------------------------------------------------------------------------------
Int32 GetWeaponID(StackStrF & name)
int32_t GetWeaponID(StackStrF & name)
{
// Clone the string into an editable version
String str(name.mPtr, static_cast< size_t >(name.mLen));
@ -174,7 +169,7 @@ Int32 GetWeaponID(StackStrF & name)
return SQMOD_UNKNOWN;
}
// Grab the actual length of the string
const Uint32 len = ConvTo< Uint32 >::From(str.length());
const uint32_t len = ConvTo< uint32_t >::From(str.length());
// Get the most significant characters used to identify a weapon
CharT a = str[0], b = 0, c = 0, d = str[len-1];
// Look for deeper specifiers
@ -369,14 +364,14 @@ Int32 GetWeaponID(StackStrF & name)
}
// ------------------------------------------------------------------------------------------------
bool IsWeaponValid(Int32 id)
bool IsWeaponValid(int32_t id)
{
CSStr name = GetWeaponName(static_cast< Uint32 >(id));
const SQChar * name = GetWeaponName(static_cast< uint32_t >(id));
return (name && *name != '\0');
}
// ------------------------------------------------------------------------------------------------
Int32 WeaponToModel(Int32 id)
int32_t WeaponToModel(int32_t id)
{
switch (id)
{
@ -421,7 +416,7 @@ Int32 WeaponToModel(Int32 id)
}
// ------------------------------------------------------------------------------------------------
bool IsWeaponNatural(Int32 id)
bool IsWeaponNatural(int32_t id)
{
switch (id)
{

View File

@ -9,22 +9,22 @@ namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Retrieve the slot associated with a weapon identifier.
*/
Uint32 GetWeaponSlot(Uint32 id);
SQMOD_NODISCARD uint32_t GetWeaponSlot(uint32_t id);
/* ------------------------------------------------------------------------------------------------
* Retrieve the name associated with a weapon identifier.
*/
CSStr GetWeaponName(Uint32 id);
SQMOD_NODISCARD const SQChar * GetWeaponName(uint32_t id);
/* ------------------------------------------------------------------------------------------------
* Modify the name associated with a weapon identifier.
*/
void SetWeaponName(Uint32 id, StackStrF & name);
void SetWeaponName(uint32_t id, StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* Retrieve the total number of identifiers in the pool of custom weapon names.
*/
Uint32 GetCustomWeaponNamePoolSize();
SQMOD_NODISCARD uint32_t GetCustomWeaponNamePoolSize();
/* ------------------------------------------------------------------------------------------------
* Clear all identifiersand associated names from the pool of custom weapon names.
@ -34,21 +34,21 @@ void ClearCustomWeaponNamePool();
/* ------------------------------------------------------------------------------------------------
* Convert a weapon name to a weapon identifier.
*/
Int32 GetWeaponID(StackStrF & name);
SQMOD_NODISCARD int32_t GetWeaponID(StackStrF & name);
/* ------------------------------------------------------------------------------------------------
* See whether the specified weapon identifier is valid.
*/
bool IsWeaponValid(Int32 id);
bool IsWeaponValid(int32_t id);
/* ------------------------------------------------------------------------------------------------
* Convert the given weapon identifier to it's associated model identifier.
*/
Int32 WeaponToModel(Int32 id);
SQMOD_NODISCARD int32_t WeaponToModel(int32_t id);
/* ------------------------------------------------------------------------------------------------
* See whether the given weapon identifier cannot be used by another player to inflict damage.
*/
bool IsWeaponNatural(Int32 id);
SQMOD_NODISCARD bool IsWeaponNatural(int32_t id);
} // Namespace:: SqMod