1
0
mirror of https://github.com/VCMP-SqMod/SqMod.git synced 2025-01-19 03:57:14 +01:00

Update the Mongoose module to work with the modified API.

Separate Mongoose handles into their own source files.
This commit is contained in:
Sandu Liviu Catalin 2016-06-03 21:30:05 +03:00
parent 26d12d601d
commit e1a1ccf979
17 changed files with 415 additions and 886 deletions

View File

@ -441,13 +441,16 @@
<Unit filename="../modules/mg/Message.cpp" /> <Unit filename="../modules/mg/Message.cpp" />
<Unit filename="../modules/mg/Message.hpp" /> <Unit filename="../modules/mg/Message.hpp" />
<Unit filename="../modules/mg/Module.cpp" /> <Unit filename="../modules/mg/Module.cpp" />
<Unit filename="../modules/mg/Module.hpp" />
<Unit filename="../modules/mg/Options.cpp" /> <Unit filename="../modules/mg/Options.cpp" />
<Unit filename="../modules/mg/Options.hpp" /> <Unit filename="../modules/mg/Options.hpp" />
<Unit filename="../modules/mg/String.cpp" /> <Unit filename="../modules/mg/String.cpp" />
<Unit filename="../modules/mg/String.hpp" /> <Unit filename="../modules/mg/String.hpp" />
<Unit filename="../modules/mg/WebSocket.cpp" /> <Unit filename="../modules/mg/WebSocket.cpp" />
<Unit filename="../modules/mg/WebSocket.hpp" /> <Unit filename="../modules/mg/WebSocket.hpp" />
<Unit filename="../shared/Base/Buffer.cpp" />
<Unit filename="../shared/Base/Buffer.hpp" />
<Unit filename="../shared/Base/Utility.cpp" />
<Unit filename="../shared/Base/Utility.hpp" />
<Unit filename="../shared/SqMod.cpp" /> <Unit filename="../shared/SqMod.cpp" />
<Extensions> <Extensions>
<code_completion /> <code_completion />

View File

@ -1,198 +1,10 @@
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include "Common.hpp" #include "Common.hpp"
#include "Module.hpp"
// ------------------------------------------------------------------------------------------------
#include <cstdio>
#include <cstring>
#include <cstdlib>
// ------------------------------------------------------------------------------------------------
#include <sqrat.h>
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
static SQChar g_Buffer[4096]; // Common buffer to reduce memory allocations.
// ------------------------------------------------------------------------------------------------
SStr GetTempBuff()
{
return g_Buffer;
}
// ------------------------------------------------------------------------------------------------
Uint32 GetTempBuffSize()
{
return sizeof(g_Buffer);
}
// ------------------------------------------------------------------------------------------------
void SqThrowF(CSStr str, ...)
{
// Initialize the argument list
va_list args;
va_start (args, str);
// Write the requested contents
if (std::vsnprintf(g_Buffer, sizeof(g_Buffer), str, args) < 0)
{
std::strcpy(g_Buffer, "Unknown error has occurred");
}
// Release the argument list
va_end(args);
// Throw the exception with the resulted message
throw Sqrat::Exception(g_Buffer);
}
// ------------------------------------------------------------------------------------------------
CSStr FmtStr(CSStr str, ...)
{
// Initialize the argument list
va_list args;
va_start (args, str);
// Write the requested contents
if (std::vsnprintf(g_Buffer, sizeof(g_Buffer), str, args) < 0)
{
g_Buffer[0] = '\0'; // Make sure the string is terminated
}
// Release the argument list
va_end(args);
// Return the data from the buffer
return g_Buffer;
}
// ------------------------------------------------------------------------------------------------
StackGuard::StackGuard()
: m_VM(_SqVM), m_Top(sq_gettop(m_VM))
{
/* ... */
}
// ------------------------------------------------------------------------------------------------
StackGuard::StackGuard(HSQUIRRELVM vm)
: m_VM(vm), m_Top(sq_gettop(vm))
{
/* ... */
}
// ------------------------------------------------------------------------------------------------
StackGuard::~StackGuard()
{
sq_pop(m_VM, sq_gettop(m_VM) - m_Top);
}
// --------------------------------------------------------------------------------------------
StackStrF::StackStrF(HSQUIRRELVM vm, SQInteger idx, bool fmt)
: mPtr(nullptr)
, mLen(-1)
, mRes(SQ_OK)
, mObj()
, mVM(vm)
{
const Int32 top = sq_gettop(vm);
// Reset the converted value object
sq_resetobject(&mObj);
// Was the string or value specified?
if (top <= (idx - 1))
{
mRes = sq_throwerror(vm, "Missing string or value");
}
// Do we have enough values to call the format function and are we allowed to?
else if (top > idx && fmt)
{
// Pointer to the generated string
SStr str = nullptr;
// Attempt to generate the specified string format
mRes = sqstd_format(vm, idx, &mLen, &str);
// Did the format succeeded but ended up with a null string pointer?
if (SQ_SUCCEEDED(mRes) && !str)
{
mRes = sq_throwerror(vm, "Unable to generate the string");
}
else
{
mPtr = const_cast< CSStr >(str);
}
}
// Is the value on the stack an actual string?
else if (sq_gettype(vm, idx) == OT_STRING)
{
// Obtain a reference to the string object
mRes = sq_getstackobj(vm, idx, &mObj);
// Could we retrieve the object from the stack?
if (SQ_SUCCEEDED(mRes))
{
// Keep a strong reference to the object
sq_addref(vm, &mObj);
// Attempt to retrieve the string value from the stack
mRes = sq_getstring(vm, idx, &mPtr);
}
// Did the retrieval succeeded but ended up with a null string pointer?
if (SQ_SUCCEEDED(mRes) && !mPtr)
{
mRes = sq_throwerror(vm, "Unable to retrieve the string");
}
}
// We have to try and convert it to string
else
{
// Attempt to convert the value from the stack to a string
mRes = sq_tostring(vm, idx);
// Could we convert the specified value to string?
if (SQ_SUCCEEDED(mRes))
{
// Obtain a reference to the resulted object
mRes = sq_getstackobj(vm, -1, &mObj);
// Could we retrieve the object from the stack?
if (SQ_SUCCEEDED(mRes))
{
// Keep a strong reference to the object
sq_addref(vm, &mObj);
// Attempt to obtain the string pointer
mRes = sq_getstring(vm, -1, &mPtr);
}
}
// Pop a value from the stack regardless of the result
sq_pop(vm, 1);
// Did the retrieval succeeded but ended up with a null string pointer?
if (SQ_SUCCEEDED(mRes) && !mPtr)
{
mRes = sq_throwerror(vm, "Unable to retrieve the value");
}
}
}
// ------------------------------------------------------------------------------------------------
Object & NullObject()
{
static Object o;
o.Release();
return o;
}
// ------------------------------------------------------------------------------------------------
Table & NullTable()
{
static Table t;
t.Release();
return t;
}
// ------------------------------------------------------------------------------------------------
Array & NullArray()
{
static Array a;
a.Release();
return a;
}
// ------------------------------------------------------------------------------------------------
Function & NullFunction()
{
static Function f;
f.Release();
return f;
}
} // Namespace:: SqMod } // Namespace:: SqMod

View File

@ -2,16 +2,9 @@
#define _SQMG_COMMON_HPP_ #define _SQMG_COMMON_HPP_
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include "ModBase.hpp" #include "Base/Utility.hpp"
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdarg>
// ------------------------------------------------------------------------------------------------
#include <squirrel.h>
#include <mongoose.h> #include <mongoose.h>
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -30,138 +23,6 @@ namespace SqMod {
#define SQMG_VERSION_MINOR 0 #define SQMG_VERSION_MINOR 0
#define SQMG_VERSION_PATCH 1 #define SQMG_VERSION_PATCH 1
/* ------------------------------------------------------------------------------------------------
* Retrieve the temporary buffer.
*/
SStr GetTempBuff();
/* ------------------------------------------------------------------------------------------------
* Retrieve the size of the temporary buffer.
*/
Uint32 GetTempBuffSize();
/* ------------------------------------------------------------------------------------------------
* Throw a formatted exception.
*/
void SqThrowF(CSStr str, ...);
/* ------------------------------------------------------------------------------------------------
* Generate a formatted string.
*/
CSStr FmtStr(CSStr str, ...);
/* ------------------------------------------------------------------------------------------------
* Implements RAII to restore the VM stack to it's initial size on function exit.
*/
struct StackGuard
{
/* --------------------------------------------------------------------------------------------
* Default constructor.
*/
StackGuard();
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
StackGuard(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~StackGuard();
private:
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
StackGuard(const StackGuard &);
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
StackGuard(StackGuard &&);
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
StackGuard & operator = (const StackGuard &);
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
StackGuard & operator = (StackGuard &&);
private:
// --------------------------------------------------------------------------------------------
HSQUIRRELVM m_VM; // The VM where the stack should be restored.
Int32 m_Top; // The top of the stack when this instance was created.
};
/* ------------------------------------------------------------------------------------------------
* Helper structure for retrieving a value from the stack as a string or a formatted string.
*/
struct StackStrF
{
// --------------------------------------------------------------------------------------------
CSStr mPtr; // Pointer to the C string that was retrieved.
SQInteger mLen; // The string length if it could be retrieved.
SQRESULT mRes; // The result of the retrieval attempts.
HSQOBJECT mObj; // Strong reference to the string object.
HSQUIRRELVM mVM; // The associated virtual machine.
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
StackStrF(HSQUIRRELVM vm, SQInteger idx, bool fmt = true);
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackStrF(const StackStrF & o) = delete;
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackStrF(StackStrF && o) = delete;
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~StackStrF();
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackStrF & operator = (const StackStrF & o) = delete;
/* --------------------------------------------------------------------------------------------
* Copy constructor. (disabled)
*/
StackStrF & operator = (StackStrF && o) = delete;
};
/* ------------------------------------------------------------------------------------------------
* Retrieve a reference to a null script object.
*/
Object & NullObject();
/* ------------------------------------------------------------------------------------------------
* Retrieve a reference to a null/empty script table.
*/
Table & NullTable();
/* ------------------------------------------------------------------------------------------------
* Retrieve a reference to a null/empty script array.
*/
Array & NullArray();
/* ------------------------------------------------------------------------------------------------
* Retrieve a reference to a null script function.
*/
Function & NullFunction();
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
enum struct HndInit enum struct HndInit
{ {

View File

@ -2,9 +2,6 @@
#include "Connection.hpp" #include "Connection.hpp"
#include "Manager.hpp" #include "Manager.hpp"
// ------------------------------------------------------------------------------------------------
#include <sqrat.h>
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {

View File

@ -2,7 +2,7 @@
#define _SQMG_CONNECTION_HPP_ #define _SQMG_CONNECTION_HPP_
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include "Handles.hpp" #include "Handle/Connection.hpp"
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {

View File

@ -2,9 +2,6 @@
#include "HTTP.hpp" #include "HTTP.hpp"
#include "Manager.hpp" #include "Manager.hpp"
// ------------------------------------------------------------------------------------------------
#include <sqrat.h>
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {

View File

@ -2,7 +2,7 @@
#define _SQMG_HTTP_HPP_ #define _SQMG_HTTP_HPP_
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include "Handles.hpp" #include "Handle/Connection.hpp"
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {

View File

@ -1,77 +1,9 @@
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include "Handles.hpp" #include "Handle/Connection.hpp"
#include "Module.hpp"
// ------------------------------------------------------------------------------------------------
#include <ctime>
#include <algorithm>
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {
// ------------------------------------------------------------------------------------------------
ManagerHnd::Managers ManagerHnd::s_Managers;
// ------------------------------------------------------------------------------------------------
void ManagerHnd::Validate() const
{
// Is the handle valid?
if ((m_Hnd == nullptr))
{
STHROWF("Invalid Mongoose manager reference");
}
}
// ------------------------------------------------------------------------------------------------
void ManagerHnd::Validate(CSStr act) const
{
// Is the handle valid?
if ((m_Hnd == nullptr))
{
STHROWF("Invalid Mongoose manager reference while: %s", act);
}
}
// ------------------------------------------------------------------------------------------------
ManagerHnd::Handle::Handle()
: mMgr()
, mRef(1)
{
// Initialize event manager object
mg_mgr_init(&mMgr, this);
// Add this instance to the pool
s_Managers.push_back(this);
}
// ------------------------------------------------------------------------------------------------
ManagerHnd::Handle::~Handle()
{
// Attempt to release manager resources
mg_mgr_free(&mMgr);
// Remove this from the pool
s_Managers.erase(std::remove(s_Managers.begin(), s_Managers.end(), this), s_Managers.end());
}
// ------------------------------------------------------------------------------------------------
Int64 ManagerHnd::Handle::Pool(Int32 milli)
{
// Pool the manager for events and store the returned timestamp
std::time_t timestamp = mg_mgr_poll(&mMgr, milli);
// Create a tm structure pointing to the unix epoch time
std::tm epoch_strt;
epoch_strt.tm_sec = 0;
epoch_strt.tm_min = 0;
epoch_strt.tm_hour = 0;
epoch_strt.tm_mday = 1;
epoch_strt.tm_mon = 0;
epoch_strt.tm_year = 70;
epoch_strt.tm_isdst = -1;
// Convert it to a time structure
std::time_t basetime = std::mktime(&epoch_strt);
// Return obtained timestamp
return static_cast< Int64 >(std::difftime(timestamp, basetime));
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void ConnectionHnd::Validate() const void ConnectionHnd::Validate() const
{ {

View File

@ -1,297 +1,12 @@
#ifndef _SQMG_HANDLES_HPP_ #ifndef _SQMG_HANDLE_CONNECTION_HPP_
#define _SQMG_HANDLES_HPP_ #define _SQMG_HANDLE_CONNECTION_HPP_
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include "Common.hpp" #include "Common.hpp"
// ------------------------------------------------------------------------------------------------
#include <vector>
// ------------------------------------------------------------------------------------------------
#include <sqrat.h>
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Manages a reference counted manager and its associated resources.
*/
class ManagerHnd
{
// --------------------------------------------------------------------------------------------
friend class Manager;
friend class Connection;
public:
// --------------------------------------------------------------------------------------------
typedef mg_mgr Type; // The managed type.
// --------------------------------------------------------------------------------------------
typedef Type* Pointer; // Pointer to the managed type.
typedef const Type* ConstPtr; // Constant pointer to the managed type.
// --------------------------------------------------------------------------------------------
typedef Type& Reference; // Reference to the managed type.
typedef const Type& ConstRef; // Constant reference to the managed type.
// --------------------------------------------------------------------------------------------
typedef unsigned int Counter; // Reference counter type.
/* --------------------------------------------------------------------------------------------
* Validate the manager handle and throw an error if invalid.
*/
void Validate() const;
/* --------------------------------------------------------------------------------------------
* Validate the manager handle and throw an error if invalid.
*/
void Validate(CSStr act) const;
protected:
/* --------------------------------------------------------------------------------------------
* The structure that holds the data associated with a physically simulated world.
*/
struct Handle
{
// ----------------------------------------------------------------------------------------
Type mMgr; // The managed manager structure.
Counter mRef; // Reference count to the managed handles.
/* ----------------------------------------------------------------------------------------
* Base constructor.
*/
Handle();
/* ----------------------------------------------------------------------------------------
* Destructor.
*/
~Handle();
/* ----------------------------------------------------------------------------------------
* Pool the managed connections for events.
*/
Int64 Pool(Int32 milli);
};
// --------------------------------------------------------------------------------------------
typedef std::vector< Handle * > Managers; // List of created managers.
// --------------------------------------------------------------------------------------------
static Managers s_Managers;
private:
// --------------------------------------------------------------------------------------------
Handle* m_Hnd;
/* --------------------------------------------------------------------------------------------
* Grab a strong reference to a connection handle.
*/
void Grab()
{
if (m_Hnd)
{
++(m_Hnd->mRef);
}
}
/* --------------------------------------------------------------------------------------------
* Drop a strong reference to a connection handle.
*/
void Drop()
{
if (m_Hnd && --(m_Hnd->mRef) == 0)
{
delete m_Hnd; // Let the destructor take care of cleaning up (if necessary)
}
}
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
ManagerHnd(HndInit init)
: m_Hnd(init == HndInit::InitHnd ? new Handle() : nullptr)
{
/* ... */
}
public:
/* --------------------------------------------------------------------------------------------
* Default constructor (null).
*/
ManagerHnd()
: m_Hnd(nullptr)
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Handle constructor.
*/
ManagerHnd(Handle * hnd)
: m_Hnd(hnd)
{
Grab();
}
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
ManagerHnd(const ManagerHnd & o)
: m_Hnd(o.m_Hnd)
{
Grab();
}
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
ManagerHnd(ManagerHnd && o)
: m_Hnd(o.m_Hnd)
{
o.m_Hnd = nullptr;
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~ManagerHnd()
{
Drop();
}
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
ManagerHnd & operator = (const ManagerHnd & o)
{
if (m_Hnd != o.m_Hnd)
{
Drop();
m_Hnd = o.m_Hnd;
Grab();
}
return *this;
}
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
ManagerHnd & operator = (ManagerHnd && o)
{
if (m_Hnd != o.m_Hnd)
{
m_Hnd = o.m_Hnd;
o.m_Hnd = nullptr;
}
return *this;
}
/* --------------------------------------------------------------------------------------------
* Perform an equality comparison between two connection handles.
*/
bool operator == (const ManagerHnd & o) const
{
return (m_Hnd == o.m_Hnd);
}
/* --------------------------------------------------------------------------------------------
* Perform an inequality comparison between two connection handles.
*/
bool operator != (const ManagerHnd & o) const
{
return (m_Hnd != o.m_Hnd);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to boolean for use in boolean operations.
*/
operator bool () const
{
return (m_Hnd != nullptr);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance.
*/
operator Pointer ()
{
return (m_Hnd != nullptr) ? &(m_Hnd->mMgr) : nullptr;
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance.
*/
operator Pointer () const
{
return (m_Hnd != nullptr) ? &(m_Hnd->mMgr) : nullptr;
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance.
*/
operator Reference ()
{
assert((m_Hnd != nullptr));
return (m_Hnd->mMgr);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance.
*/
operator ConstRef () const
{
assert((m_Hnd != nullptr));
return (m_Hnd->mMgr);
}
/* --------------------------------------------------------------------------------------------
* Member operator for dereferencing the managed pointer.
*/
Handle * operator -> () const
{
assert(m_Hnd != nullptr);
return m_Hnd;
}
/* --------------------------------------------------------------------------------------------
* Indirection operator for obtaining a reference of the managed pointer.
*/
Handle & operator * () const
{
assert(m_Hnd != nullptr);
return *m_Hnd;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the raw handle structure pointer.
*/
Handle * HndPtr()
{
return m_Hnd;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the raw handle structure pointer.
*/
Handle * HndPtr() const
{
return m_Hnd;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the number of active references to the managed instance.
*/
Counter Count() const
{
return (m_Hnd != nullptr) ? m_Hnd->mRef : 0;
}
};
/* ------------------------------------------------------------------------------------------------ /* ------------------------------------------------------------------------------------------------
* Manages a reference counted connection and its associated resources. * Manages a reference counted connection and its associated resources.
*/ */
@ -413,7 +128,7 @@ protected:
private: private:
// -------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------
Handle* m_Hnd; Handle * m_Hnd; // The managed handle instance.
/* -------------------------------------------------------------------------------------------- /* --------------------------------------------------------------------------------------------
* Grab a strong reference to a connection handle. * Grab a strong reference to a connection handle.
@ -623,4 +338,4 @@ public:
} // Namespace:: SqMod } // Namespace:: SqMod
#endif // _SQMG_HANDLES_HPP_ #endif // _SQMG_HANDLE_CONNECTION_HPP_

View File

@ -0,0 +1,74 @@
// ------------------------------------------------------------------------------------------------
#include "Handle/Manager.hpp"
// ------------------------------------------------------------------------------------------------
#include <ctime>
#include <algorithm>
// ------------------------------------------------------------------------------------------------
namespace SqMod {
// ------------------------------------------------------------------------------------------------
ManagerHnd::Managers ManagerHnd::s_Managers;
// ------------------------------------------------------------------------------------------------
void ManagerHnd::Validate() const
{
// Is the handle valid?
if ((m_Hnd == nullptr))
{
STHROWF("Invalid Mongoose manager reference");
}
}
// ------------------------------------------------------------------------------------------------
void ManagerHnd::Validate(CSStr act) const
{
// Is the handle valid?
if ((m_Hnd == nullptr))
{
STHROWF("Invalid Mongoose manager reference while: %s", act);
}
}
// ------------------------------------------------------------------------------------------------
ManagerHnd::Handle::Handle()
: mMgr()
, mRef(1)
{
// Initialize event manager object
mg_mgr_init(&mMgr, this);
// Add this instance to the pool
s_Managers.push_back(this);
}
// ------------------------------------------------------------------------------------------------
ManagerHnd::Handle::~Handle()
{
// Attempt to release manager resources
mg_mgr_free(&mMgr);
// Remove this from the pool
s_Managers.erase(std::remove(s_Managers.begin(), s_Managers.end(), this), s_Managers.end());
}
// ------------------------------------------------------------------------------------------------
Int64 ManagerHnd::Handle::Pool(Int32 milli)
{
// Pool the manager for events and store the returned timestamp
std::time_t timestamp = mg_mgr_poll(&mMgr, milli);
// Create a tm structure pointing to the unix epoch time
std::tm epoch_strt;
epoch_strt.tm_sec = 0;
epoch_strt.tm_min = 0;
epoch_strt.tm_hour = 0;
epoch_strt.tm_mday = 1;
epoch_strt.tm_mon = 0;
epoch_strt.tm_year = 70;
epoch_strt.tm_isdst = -1;
// Convert it to a time structure
std::time_t basetime = std::mktime(&epoch_strt);
// Return obtained timestamp
return static_cast< Int64 >(std::difftime(timestamp, basetime));
}
} // Namespace:: SqMod

View File

@ -0,0 +1,291 @@
#ifndef _SQMG_HANDLE_MANAGER_HPP_
#define _SQMG_HANDLE_MANAGER_HPP_
// ------------------------------------------------------------------------------------------------
#include "Common.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Manages a reference counted manager and its associated resources.
*/
class ManagerHnd
{
// --------------------------------------------------------------------------------------------
friend class Manager;
friend class Connection;
public:
// --------------------------------------------------------------------------------------------
typedef mg_mgr Type; // The managed type.
// --------------------------------------------------------------------------------------------
typedef Type* Pointer; // Pointer to the managed type.
typedef const Type* ConstPtr; // Constant pointer to the managed type.
// --------------------------------------------------------------------------------------------
typedef Type& Reference; // Reference to the managed type.
typedef const Type& ConstRef; // Constant reference to the managed type.
// --------------------------------------------------------------------------------------------
typedef unsigned int Counter; // Reference counter type.
/* --------------------------------------------------------------------------------------------
* Validate the manager handle and throw an error if invalid.
*/
void Validate() const;
/* --------------------------------------------------------------------------------------------
* Validate the manager handle and throw an error if invalid.
*/
void Validate(CSStr act) const;
protected:
/* --------------------------------------------------------------------------------------------
* The structure that holds the data associated with a physically simulated world.
*/
struct Handle
{
// ----------------------------------------------------------------------------------------
Type mMgr; // The managed manager structure.
Counter mRef; // Reference count to the managed handles.
/* ----------------------------------------------------------------------------------------
* Base constructor.
*/
Handle();
/* ----------------------------------------------------------------------------------------
* Destructor.
*/
~Handle();
/* ----------------------------------------------------------------------------------------
* Pool the managed connections for events.
*/
Int64 Pool(Int32 milli);
};
// --------------------------------------------------------------------------------------------
typedef std::vector< Handle * > Managers; // List of created managers.
// --------------------------------------------------------------------------------------------
static Managers s_Managers;
private:
// --------------------------------------------------------------------------------------------
Handle * m_Hnd; // The managed handle instance.
/* --------------------------------------------------------------------------------------------
* Grab a strong reference to a connection handle.
*/
void Grab()
{
if (m_Hnd)
{
++(m_Hnd->mRef);
}
}
/* --------------------------------------------------------------------------------------------
* Drop a strong reference to a connection handle.
*/
void Drop()
{
if (m_Hnd && --(m_Hnd->mRef) == 0)
{
delete m_Hnd; // Let the destructor take care of cleaning up (if necessary)
}
}
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
ManagerHnd(HndInit init)
: m_Hnd(init == HndInit::InitHnd ? new Handle() : nullptr)
{
/* ... */
}
public:
/* --------------------------------------------------------------------------------------------
* Default constructor (null).
*/
ManagerHnd()
: m_Hnd(nullptr)
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Handle constructor.
*/
ManagerHnd(Handle * hnd)
: m_Hnd(hnd)
{
Grab();
}
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
ManagerHnd(const ManagerHnd & o)
: m_Hnd(o.m_Hnd)
{
Grab();
}
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
ManagerHnd(ManagerHnd && o)
: m_Hnd(o.m_Hnd)
{
o.m_Hnd = nullptr;
}
/* --------------------------------------------------------------------------------------------
* Destructor.
*/
~ManagerHnd()
{
Drop();
}
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
ManagerHnd & operator = (const ManagerHnd & o)
{
if (m_Hnd != o.m_Hnd)
{
Drop();
m_Hnd = o.m_Hnd;
Grab();
}
return *this;
}
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
ManagerHnd & operator = (ManagerHnd && o)
{
if (m_Hnd != o.m_Hnd)
{
m_Hnd = o.m_Hnd;
o.m_Hnd = nullptr;
}
return *this;
}
/* --------------------------------------------------------------------------------------------
* Perform an equality comparison between two connection handles.
*/
bool operator == (const ManagerHnd & o) const
{
return (m_Hnd == o.m_Hnd);
}
/* --------------------------------------------------------------------------------------------
* Perform an inequality comparison between two connection handles.
*/
bool operator != (const ManagerHnd & o) const
{
return (m_Hnd != o.m_Hnd);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to boolean for use in boolean operations.
*/
operator bool () const
{
return (m_Hnd != nullptr);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance.
*/
operator Pointer ()
{
return (m_Hnd != nullptr) ? &(m_Hnd->mMgr) : nullptr;
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance.
*/
operator Pointer () const
{
return (m_Hnd != nullptr) ? &(m_Hnd->mMgr) : nullptr;
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance.
*/
operator Reference ()
{
assert((m_Hnd != nullptr));
return (m_Hnd->mMgr);
}
/* --------------------------------------------------------------------------------------------
* Implicit conversion to the managed instance.
*/
operator ConstRef () const
{
assert((m_Hnd != nullptr));
return (m_Hnd->mMgr);
}
/* --------------------------------------------------------------------------------------------
* Member operator for dereferencing the managed pointer.
*/
Handle * operator -> () const
{
assert(m_Hnd != nullptr);
return m_Hnd;
}
/* --------------------------------------------------------------------------------------------
* Indirection operator for obtaining a reference of the managed pointer.
*/
Handle & operator * () const
{
assert(m_Hnd != nullptr);
return *m_Hnd;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the raw handle structure pointer.
*/
Handle * HndPtr()
{
return m_Hnd;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the raw handle structure pointer.
*/
Handle * HndPtr() const
{
return m_Hnd;
}
/* --------------------------------------------------------------------------------------------
* Retrieve the number of active references to the managed instance.
*/
Counter Count() const
{
return (m_Hnd != nullptr) ? m_Hnd->mRef : 0;
}
};
} // Namespace:: SqMod
#endif // _SQMG_HANDLE_MANAGER_HPP_

View File

@ -7,9 +7,6 @@
#include <cstring> #include <cstring>
#include <cstdlib> #include <cstdlib>
// ------------------------------------------------------------------------------------------------
#include <sqrat.h>
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {

View File

@ -2,7 +2,7 @@
#define _SQMG_MANAGER_HPP_ #define _SQMG_MANAGER_HPP_
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include "Handles.hpp" #include "Handle/Manager.hpp"
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {

View File

@ -1,37 +1,17 @@
// -------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------
#include "Module.hpp"
#include "Common.hpp" #include "Common.hpp"
#include "Manager.hpp" #include "Manager.hpp"
#include "Connection.hpp" #include "Connection.hpp"
// -------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <cstring>
#include <cstdarg>
// --------------------------------------------------------------------------------------------
#include <sqrat.h>
// --------------------------------------------------------------------------------------------
#if defined(WIN32) || defined(_WIN32)
#include <Windows.h>
#endif
// ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {
// --------------------------------------------------------------------------------------------
PluginFuncs* _Func = nullptr;
PluginCallbacks* _Clbk = nullptr;
PluginInfo* _Info = nullptr;
// --------------------------------------------------------------------------------------------
HSQAPI _SqAPI = nullptr;
HSQEXPORTS _SqMod = nullptr;
HSQUIRRELVM _SqVM = nullptr;
/* ------------------------------------------------------------------------------------------------ /* ------------------------------------------------------------------------------------------------
* Bind speciffic functions to certain server events. * Bind specific functions to certain server events.
*/ */
void BindCallbacks(); void BindCallbacks();
@ -40,22 +20,22 @@ void BindCallbacks();
*/ */
void UnbindCallbacks(); void UnbindCallbacks();
/* -------------------------------------------------------------------------------------------- /* ------------------------------------------------------------------------------------------------
* Register the module API under the specified virtual machine. * Register the module API under the specified virtual machine.
*/ */
void RegisterAPI(HSQUIRRELVM vm); void RegisterAPI(HSQUIRRELVM vm);
/* -------------------------------------------------------------------------------------------- /* ------------------------------------------------------------------------------------------------
* Initialize the plugin by obtaining the API provided by the host plugin. * Initialize the plug-in by obtaining the API provided by the host plug-in.
*/ */
void OnSquirrelInitialize() void OnSquirrelInitialize()
{ {
// Attempt to import the plugin API exported by the host plugin // Attempt to import the plug-in API exported by the host plug-in
_SqMod = sq_api_import(_Func); _SqMod = sq_api_import(_Func);
// Did we failed to obtain the plugin exports? // Did we failed to obtain the plug-in exports?
if (!_SqMod) if (!_SqMod)
{ {
OutputError("Failed to attach [%s] on host plugin.", SQMG_NAME); OutputError("Failed to attach [%s] on host plug-in.", SQMG_NAME);
} }
else else
{ {
@ -66,12 +46,12 @@ void OnSquirrelInitialize()
} }
} }
/* -------------------------------------------------------------------------------------------- /* ------------------------------------------------------------------------------------------------
* Load the module on the virtual machine provided by the host module. * Load the module on the virtual machine provided by the host module.
*/ */
void OnSquirrelLoad() void OnSquirrelLoad()
{ {
// Make sure that we have a valid plugin API // Make sure that we have a valid plug-in API
if (!_SqMod) if (!_SqMod)
{ {
return; // Unable to proceed. return; // Unable to proceed.
@ -91,7 +71,7 @@ void OnSquirrelLoad()
OutputMessage("Registered: %s", SQMG_NAME); OutputMessage("Registered: %s", SQMG_NAME);
} }
/* -------------------------------------------------------------------------------------------- /* ------------------------------------------------------------------------------------------------
* The virtual machine is about to be terminated and script resources should be released. * The virtual machine is about to be terminated and script resources should be released.
*/ */
void OnSquirrelTerminate() void OnSquirrelTerminate()
@ -107,13 +87,13 @@ void OnSquirrelTerminate()
// Release script resources... // Release script resources...
} }
/* -------------------------------------------------------------------------------------------- /* ------------------------------------------------------------------------------------------------
* Validate the module API to make sure we don't run into issues. * Validate the module API to make sure we don't run into issues.
*/ */
bool CheckAPIVer(CCStr ver) bool CheckAPIVer(CCStr ver)
{ {
// Obtain the numeric representation of the API version // Obtain the numeric representation of the API version
long vernum = std::strtol(ver, nullptr, 10); const LongI vernum = std::strtol(ver, nullptr, 10);
// Check against version mismatch // Check against version mismatch
if (vernum == SQMOD_API_VER) if (vernum == SQMOD_API_VER)
{ {
@ -126,8 +106,8 @@ bool CheckAPIVer(CCStr ver)
return false; return false;
} }
/* -------------------------------------------------------------------------------------------- /* ------------------------------------------------------------------------------------------------
* React to command sent by other plugins. * React to command sent by other plug-ins.
*/ */
static uint8_t OnPluginCommand(uint32_t command_identifier, CCStr message) static uint8_t OnPluginCommand(uint32_t command_identifier, CCStr message)
{ {
@ -150,8 +130,8 @@ static uint8_t OnPluginCommand(uint32_t command_identifier, CCStr message)
return 1; return 1;
} }
/* -------------------------------------------------------------------------------------------- /* ------------------------------------------------------------------------------------------------
* The server was initialized and this plugin was loaded successfully. * The server was initialized and this plug-in was loaded successfully.
*/ */
static uint8_t OnServerInitialise() static uint8_t OnServerInitialise()
{ {
@ -180,7 +160,7 @@ void UnbindCallbacks()
_Clbk->OnPluginCommand = nullptr; _Clbk->OnPluginCommand = nullptr;
} }
// -------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------
void RegisterAPI(HSQUIRRELVM vm) void RegisterAPI(HSQUIRRELVM vm)
{ {
Table mgns(vm); Table mgns(vm);
@ -189,7 +169,7 @@ void RegisterAPI(HSQUIRRELVM vm)
// Constructors // Constructors
.Ctor() .Ctor()
.Ctor< const Manager & >() .Ctor< const Manager & >()
// Core Metamethods // Core Meta-methods
.Func(_SC("_cmp"), &Manager::Cmp) .Func(_SC("_cmp"), &Manager::Cmp)
.SquirrelFunc(_SC("_typename"), &Manager::Typename) .SquirrelFunc(_SC("_typename"), &Manager::Typename)
.Func(_SC("_tostring"), &Manager::ToString) .Func(_SC("_tostring"), &Manager::ToString)
@ -208,7 +188,7 @@ void RegisterAPI(HSQUIRRELVM vm)
// Constructors // Constructors
.Ctor() .Ctor()
.Ctor< const Connection & >() .Ctor< const Connection & >()
// Core Metamethods // Core Meta-methods
.Func(_SC("_cmp"), &Connection::Cmp) .Func(_SC("_cmp"), &Connection::Cmp)
.SquirrelFunc(_SC("_typename"), &Connection::Typename) .SquirrelFunc(_SC("_typename"), &Connection::Typename)
.Func(_SC("_tostring"), &Connection::ToString) .Func(_SC("_tostring"), &Connection::ToString)
@ -290,119 +270,33 @@ void RegisterAPI(HSQUIRRELVM vm)
); );
} }
// --------------------------------------------------------------------------------------------
void OutputMessageImpl(const char * msg, va_list args)
{
#if defined(WIN32) || defined(_WIN32)
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csb_before;
GetConsoleScreenBufferInfo( hstdout, &csb_before);
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN);
std::printf("[SQMOD] ");
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY);
std::vprintf(msg, args);
std::puts("");
SetConsoleTextAttribute(hstdout, csb_before.wAttributes);
#else
std::printf("%c[0;32m[SQMOD]%c[0m", 27, 27);
std::vprintf(msg, args);
std::puts("");
#endif
}
// --------------------------------------------------------------------------------------------
void OutputErrorImpl(const char * msg, va_list args)
{
#if defined(WIN32) || defined(_WIN32)
HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csb_before;
GetConsoleScreenBufferInfo( hstdout, &csb_before);
SetConsoleTextAttribute(hstdout, FOREGROUND_RED | FOREGROUND_INTENSITY);
std::printf("[SQMOD] ");
SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY);
std::vprintf(msg, args);
std::puts("");
SetConsoleTextAttribute(hstdout, csb_before.wAttributes);
#else
std::printf("%c[0;91m[SQMOD]%c[0m", 27, 27);
std::vprintf(msg, args);
std::puts("");
#endif
}
// --------------------------------------------------------------------------------------------
void OutputDebug(const char * msg, ...)
{
#ifdef _DEBUG
// Initialize the arguments list
va_list args;
va_start(args, msg);
// Call the output function
OutputMessageImpl(msg, args);
// Finalize the arguments list
va_end(args);
#else
SQMOD_UNUSED_VAR(msg);
#endif
}
// --------------------------------------------------------------------------------------------
void OutputMessage(const char * msg, ...)
{
// Initialize the arguments list
va_list args;
va_start(args, msg);
// Call the output function
OutputMessageImpl(msg, args);
// Finalize the arguments list
va_end(args);
}
// --------------------------------------------------------------------------------------------
void OutputError(const char * msg, ...)
{
// Initialize the arguments list
va_list args;
va_start(args, msg);
// Call the output function
OutputErrorImpl(msg, args);
// Finalize the arguments list
va_end(args);
}
} // Namespace:: SqMod } // Namespace:: SqMod
// -------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------
SQMOD_API_EXPORT unsigned int VcmpPluginInit(PluginFuncs * functions, PluginCallbacks * callbacks, PluginInfo * info) SQMOD_API_EXPORT unsigned int VcmpPluginInit(PluginFuncs * functions, PluginCallbacks * callbacks, PluginInfo * info)
{ {
using namespace SqMod; using namespace SqMod;
// Output plugin header // Output plug-in header
std::puts(""); std::puts("");
OutputMessage("--------------------------------------------------------------------"); OutputMessage("--------------------------------------------------------------------");
OutputMessage("Plugin: %s", SQMG_NAME); OutputMessage("Plug-in: %s", SQMG_NAME);
OutputMessage("Author: %s", SQMG_AUTHOR); OutputMessage("Author: %s", SQMG_AUTHOR);
OutputMessage("Legal: %s", SQMG_COPYRIGHT); OutputMessage("Legal: %s", SQMG_COPYRIGHT);
OutputMessage("--------------------------------------------------------------------"); OutputMessage("--------------------------------------------------------------------");
std::puts(""); std::puts("");
// Attempt to find the host plugin ID // Attempt to find the host plug-in ID
int host_plugin_id = functions->FindPlugin((char *)(SQMOD_HOST_NAME)); const int host_plugin_id = functions->FindPlugin(SQMOD_HOST_NAME);
// See if our plugin was loaded after the host plugin // See if our plug-in was loaded after the host plug-in
if (host_plugin_id < 0) if (host_plugin_id < 0)
{ {
OutputError("%s could find the host plugin", SQMG_NAME); OutputError("%s could find the host plug-in", SQMG_NAME);
// Don't load! // Don't load!
return SQMOD_FAILURE; return SQMOD_FAILURE;
} }
// Should never reach this point but just in case // Should never reach this point but just in case
else if (static_cast< Uint32 >(host_plugin_id) > info->pluginId) else if (static_cast< Uint32 >(host_plugin_id) > info->pluginId)
{ {
OutputError("%s loaded after the host plugin", SQMG_NAME); OutputError("%s loaded after the host plug-in", SQMG_NAME);
// Don't load! // Don't load!
return SQMOD_FAILURE; return SQMOD_FAILURE;
} }
@ -410,15 +304,15 @@ SQMOD_API_EXPORT unsigned int VcmpPluginInit(PluginFuncs* functions, PluginCallb
_Func = functions; _Func = functions;
_Clbk = callbacks; _Clbk = callbacks;
_Info = info; _Info = info;
// Assign plugin version // Assign plug-in version
_Info->pluginVersion = SQMG_VERSION; _Info->pluginVersion = SQMG_VERSION;
_Info->apiMajorVersion = PLUGIN_API_MAJOR; _Info->apiMajorVersion = PLUGIN_API_MAJOR;
_Info->apiMinorVersion = PLUGIN_API_MINOR; _Info->apiMinorVersion = PLUGIN_API_MINOR;
// Assign the plugin name // Assign the plug-in name
std::snprintf(_Info->name, sizeof(_Info->name), "%s", SQMG_HOST_NAME); std::snprintf(_Info->name, sizeof(_Info->name), "%s", SQMG_HOST_NAME);
// Bind callbacks // Bind callbacks
BindCallbacks(); BindCallbacks();
// Notify that the plugin was successfully loaded // Notify that the plug-in was successfully loaded
OutputMessage("Successfully loaded %s", SQMG_NAME); OutputMessage("Successfully loaded %s", SQMG_NAME);
// Dummy spacing // Dummy spacing
std::puts(""); std::puts("");

View File

@ -1,41 +0,0 @@
#ifndef _SQMG_MODULE_HPP_
#define _SQMG_MODULE_HPP_
// ------------------------------------------------------------------------------------------------
#include "SqMod.h"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Proxies to comunicate with the server.
*/
extern PluginFuncs* _Func;
extern PluginCallbacks* _Clbk;
extern PluginInfo* _Info;
/* ------------------------------------------------------------------------------------------------
* Proxies to comunicate with the Squirrel plugin.
*/
extern HSQAPI _SqAPI;
extern HSQEXPORTS _SqMod;
extern HSQUIRRELVM _SqVM;
/* ------------------------------------------------------------------------------------------------
* Output a message only if the _DEBUG was defined.
*/
void OutputDebug(const char * msg, ...);
/* ------------------------------------------------------------------------------------------------
* Output a formatted user message to the console.
*/
void OutputMessage(const char * msg, ...);
/* ------------------------------------------------------------------------------------------------
* Output a formatted error message to the console.
*/
void OutputError(const char * msg, ...);
} // Namespace:: SqMod
#endif // _SQMG_MODULE_HPP_

View File

@ -2,9 +2,6 @@
#include "WebSocket.hpp" #include "WebSocket.hpp"
#include "Manager.hpp" #include "Manager.hpp"
// ------------------------------------------------------------------------------------------------
#include <sqrat.h>
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {

View File

@ -2,7 +2,7 @@
#define _SQMG_WEBSOCKET_HPP_ #define _SQMG_WEBSOCKET_HPP_
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#include "Handles.hpp" #include "Handle/Connection.hpp"
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace SqMod { namespace SqMod {