first commit

This commit is contained in:
2026-06-22 11:49:35 +02:00
commit d805f2ba86
619 changed files with 126873 additions and 0 deletions

View File

@ -0,0 +1,163 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NARCHIVE__
#define __NARCHIVE__
#include "nstring/nstring.h"
#include "container/nlist.h"
#include "memory/nauto_ptr.h"
#include "filesystem/io_handle.h"
namespace GS {
namespace Threading { class Mutex; }
/// Archive index entry.
struct ArchiveEntry
{
// Do not change this enumeration order!
enum Method
{
MethodRaw = 0,
MethodZLibCompress
};
String path; ///< Entry path.
char method; ///< Compression method.
size_t offset; ///< Data offset in archive.
size_t length; ///< Original length.
size_t compressed_length; ///< Compressed length.
};
/*!
@short Archive index.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class ArchiveIndex
{
friend class Archive;
protected:
AutoList <ArchiveEntry *> index;
public:
/// Find an entry in the index file.
ArchiveEntry *FindEntry(const char *alias) const;
/// Load archive index.
bool Load(const char *uri);
/// Save archive index.
bool Save(const char *uri);
};
/*!
@short Archive storage.
A pretty straightforward solid archive file format.
Supports per-file compression algorithm selection.
@author Emmanuel Julien
*/
class Archive
{
public:
enum Revision
{
Legacy = 0,
EnhancedLegacy
};
protected:
AutoPtr <Threading::Mutex> access_mutex;
bool verbose;
bool append_mode; ///< Archive open in append mode.
ArchiveIndex index; ///< Archive index table.
AutoPtr <IO::Handle> handle;
Revision revision;
size_t offset_padding, ///< File offset padding.
size_padding; ///< File size padding.
public:
/*!
@short Set file offset padding.
Padding archive content is necessary on some platforms that do not
support seeking or reading an arbitrary amount of bytes inside a
file. This is often the case with the DVD unit of console systems.
*/
void SetOffsetPadding(size_t padding = 0)
{ offset_padding = padding; }
/*!
@short Set file size padding.
@see SetOffsetPadding().
*/
void SetSizePadding(size_t padding = 0)
{ size_padding = padding; }
/// Return internal index object.
const List <ArchiveEntry *> &GetIndex() const
{ return index.index; }
/// Set the verbose mode.
void SetVerbose(bool v = true)
{ verbose = v; }
/// Load current archive index file.
bool LoadIndex(const char *path);
/// Save current archive index file.
bool SaveIndex(const char *path);
/*!
@short Open archive.
@note If no index is provided one will automatically be created
upon archive opening. Although this a fast process it
requires that the archive be opened on a stream-able
file system and that the whole archive be seeked through.
*/
bool OpenRead(const char *uri, const char *index_uri = 0);
/// Create a new archive.
bool CreateNew(const char *);
/// Close archive.
void Close();
/// Check if a file exists in archive.
ArchiveEntry *Exists(const char *path) const
{ return index.FindEntry(path); }
/*!
@short Load a file from the archive.
@note The output buffer is expected to old enough room to store
the decompressed data.
@see Exists().
*/
bool FileRead(const char *, void *);
/// Write a memory block to the archive.
ArchiveEntry *MemoryBlockWrite(const char *, const void *, size_t, int compression_level = 6);
/// Write a file to the archive.
ArchiveEntry *FileWrite(const char *path, const char *alias = 0, int compression_level = 6);
Archive();
~Archive();
};
} // GS
#endif // __NARCHIVE__

View File

@ -0,0 +1,63 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __AUDIOOGGSTREAM__
#define __AUDIOOGGSTREAM__
#include "filesystem/io_handle.h"
#define STB_VORBIS_HEADER_ONLY
#include "stb_vorbis.c"
#undef STB_VORBIS_HEADER_ONLY
#include "audio/stream_interface.h"
#include "memory/ring_buffer.h"
#include "memory/nauto_ptr.h"
namespace GS {
/*
@short OGG audio stream.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class AudioStreamOGG : public IAudioStream
{
protected:
AutoPtr <IO::Handle> h;
Array <char> buffer;
size_t byte_left;
size_t RefillBuffer();
void ConsumeBuffer(size_t);
int seek_correction, consumed, err;
stb_vorbis_info vorbis_info;
stb_vorbis *vf;
public:
/// Return the stream data format (eg. "OGG").
const char *GetFormat() { return "OGG"; }
bool Seek(int t_ms = 0);
bool IsEOF() const;
size_t GetPCM(void *);
size_t GetPCMBufferSize() const;
bool Open(const char *uri);
void Close();
AudioStreamOGG();
~AudioStreamOGG();
};
} // GS
#endif // __AUDIOOGGSTREAM__

View File

@ -0,0 +1,31 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __OGGSTREAMFACTORY__
#define __OGGSTREAMFACTORY__
#include "audio/stream_factory.h"
namespace GS {
/*
@short OGG stream factory.
@author Emmanuel Julien (ejulien@owloh.com)
*/
struct OGGStreamFactory : public IAudioStreamFactory
{
/// Get factory name.
virtual const char *GetName() { return "OGG"; }
/// Open a stream.
virtual IAudioStream *Open(const char *path);
};
} // GS
#endif // __OGGSTREAMFACTORY__

View File

@ -0,0 +1,68 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __SCRIPT_NETWORK_DEBUGGER__
#define __SCRIPT_NETWORK_DEBUGGER__
#include "async/async_call_queue.h"
#include "script/script_vm_debug_profile_base.h"
namespace GS {
namespace Script {
class NetworkDebuggerThread;
/*!
@short Networked debugger VM event handler.
This event handler spawns and communicates with a network controller thread.
@author Emmanuel Julien (ejulien@owloh.com)
*/
class NetworkDebugger : public IDebuggerProfiler
{
NetworkDebuggerThread *thread;
bool start_signal;
public:
ASync::CallQueue async;
String GetPeerAddress();
bool IsConnected() const;
void Stop();
void BroadcastNetworkCommand(const String &);
bool GetStartSignal() const { return start_signal; }
// Network debugger interface.
virtual void OnNetworkReady(const String &, int) {}
virtual void OnControllerConnected() {}
virtual void OnControllerDisconnected() {}
virtual void OnControllerPacketReceived(const Array <char> &);
// Debugger interface implementation.
void OnSuspendExecution(const char *source, int line);
bool OnUpdateSuspendedExecution();
// VM interface implementation.
void OnFatalError(const char *reason);
void OnCompilerError(const char *error, const char *source, int line);
void OnRuntimeException(const char *error);
NetworkDebugger(IVM *vm, IDebugger *dbg, const char *address, int port);
~NetworkDebugger();
};
} // Script
} // GS
#endif // __SCRIPT_NETWORK_DEBUGGER__

View File

@ -0,0 +1,76 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NETWORK_DEBUGGER_THREAD__
#define __NETWORK_DEBUGGER_THREAD__
#include "network_enet/enet_network.h"
#include "async/async_call_queue.h"
#include "thread/thread.h"
#include "nstring/nstring.h"
namespace GS {
namespace Script {
class NetworkDebugger;
/*!
@short Debugger network controller.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class NetworkDebuggerThread : public Threading::Thread, public Network::Enet
{
protected:
String address;
int port;
NetworkDebugger &ctl;
private:
static const int StateStopped = 0;
static const int StateWaitingController = 1;
static const int StateControllerConnected = 2;
static const int StateStop = 3;
Threading::Atomic32 connected, state;
void *ctl_peer;
virtual void OnPeerConnection(void *);
virtual void OnPacketReceived(void *, const void *, size_t);
virtual void OnConnectionClosed(void *);
virtual bool OpenServer(const char *address = "127.0.0.1", int port = 999);
virtual bool OpenClient(const char *address = "127.0.0.1", int port = 999) { return false; }
virtual void Execute();
public:
String GetControllerAddress();
bool IsConnected() const { return asbool(connected.Get()); }
void DisconnectController();
void SendToController(const String &);
void Stop();
ASync::CallQueue async;
NetworkDebuggerThread(NetworkDebugger &h, const char *address, int port);
~NetworkDebuggerThread();
};
} // Script
} // GS
#endif // __NETWORK_DEBUGGER_THREAD__

View File

@ -0,0 +1,64 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __FT2FONT__
#define __NTEXTFONT__
#include <ft2build.h>
#include FT_FREETYPE_H
#include "font/font_interface.h"
#include "geometry/rect.h"
#include "nstring/nstring.h"
namespace GS {
/// Freetype 2 font.
class Freetype2Font : public IFont
{
friend class Freetype2FontFactory;
String name;
Array <char> buffer;
bool has_kerning;
FT_Face face;
public:
/// Return the font name.
virtual const char *GetName() const { return name; }
/// Return the bounding rect for a given string.
virtual iRect GetTextBoundRect(const char *) const;
/// Set font size in pixels.
virtual bool SetPixelSize(int);
/// Get font height in pixels.
virtual int GetHeight() const;
/// Get font current glyph advance.
virtual int GetAdvance() const;
/// Return true if the font supports kerning.
virtual bool HasKerning() const;
/// Return the kerning for a codepoint pair.
virtual int GetKerning(uint previous_codepoint, uint codepoint) const;
/// Load the glyph corresponding to a UTF-32 codepoint.
virtual bool LoadGlyph(uint codepoint, bool for_render);
/// Render currently loaded glyph to a picture.
virtual bool RenderCurrentGlyph(Picture &picture, const iPoint &position, const iRect &clip, const Color &color = Color::White);
Freetype2Font() : face(0) {}
~Freetype2Font();
};
} // GS
#endif // __NTEXTFONT__

View File

@ -0,0 +1,36 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __FT2FONTFACTORY__
#define __FT2FONTFACTORY__
#include "ft2build.h"
#include FT_FREETYPE_H
#include "font/font_factory.h"
namespace GS {
struct IFont;
/// Font factory.
class Freetype2FontFactory : public IFontFactory
{
FT_Library ft2;
public:
/// Load a font.
virtual IFont *LoadFont(const char *);
Freetype2FontFactory();
virtual ~Freetype2FontFactory();
};
} // GS
#endif // __FT2FONTFACTORY__

View File

@ -0,0 +1,48 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __HTTPCURL__
#define __HTTPCURL__
#include "http/http_interface.h"
#include "async/async_call_queue.h"
namespace GS {
namespace HTTP {
class CurlThread;
/*!
@short CURL based HTTP helper.
@author Emmanuel Julien (ejulien@owloh.com)
*/
class Curl : public IHTTP
{
CurlThread *curl_thread;
int u_ticket_id;
int GetTicketId();
public:
ASync::CallQueue event_queue;
/// Post an asynchronous HTTP request.
virtual int Post(const char *url, const char *post);
/// Process pending event dispatch in the caller thread.
virtual void Update();
Curl();
~Curl();
};
} // Http
} // GS
#endif // __HTTPCURL__

View File

@ -0,0 +1,118 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __FBXIMPORT__
#define __FBXIMPORT__
#define FBXSDK_NEW_API
#include "fbxsdk.h"
#include "import/import_interface.h"
#include "automation/automated_property_provider.h"
#include "core/resource_factory_event_interface.h"
#include "container/nlist.h"
namespace GS {
namespace Core {
class Motion;
class Geometry;
struct Material;
}
namespace S3D {
class MItem;
struct MObject;
/// Exported node cache.
struct ExportedNode
{
FbxNode *node;
MItem *item;
ExportedNode(FbxNode *n, MItem *i) : node(n), item(i) {}
};
/*!
@short Autodesk FBX Importer.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class FBXImporter : public IImport
{
int current_node_index;
String input_path;
Scene *scene;
const Config *config;
FbxManager *sdk_manager;
FbxScene *fbx_scene;
List <Core::Geometry *> geometry_list;
List <ExportedNode *> node_list;
/// Save material.
String SaveMaterial(const Core::Material &, const char *);
/// Get the item corresponding to a node, if it has been exported already.
bool GetNodeItem(FbxNode *, MItem **);
/// Export motion channels.
void ExportMotionChannel(FbxNode *, FbxAnimCurve *, Core::Motion *, Core::MotionChannel::Type);
/// Bake transformation.
void BakeTransformation(FbxNode *, MItem *, Core::Motion *);
/// Export motions.
void ExportMotions(FbxNode *, MItem *);
/// Export mesh layer.
void ExportMeshLayer(FbxMesh *, Core::Geometry *, int layer_index = 0);
/// Export skin.
bool ExportDeformers(FbxMesh *, FbxNode *, Core::Geometry &, MObject *);
/// Export vertex color.
void ExportMeshVertexColor(FbxMesh *, Core::Geometry *);
/// Export tangent frame.
void ExportMeshTangentFrame(FbxMesh *, Core::Geometry *);
/// Export a geometry (topology and normals).
String ExportGeometry(FbxMesh *, FbxNode *, MObject *);
/// Export a file-based texture.
String ExportFileTexture(FbxFileTexture *);
/// Export a layered texture.
String ExportLayeredTexture(FbxLayeredTexture *);
/// Export a material.
String ExportMaterial(FbxSurfaceMaterial *, FbxMesh *, bool use_skin);
/// Export a camera.
MItem *ExportCamera(FbxNodeAttribute *, FbxNode * = 0);
/// Export a mesh.
MObject *ExportObject(FbxNodeAttribute *, FbxNode * = 0);
/// Export a light.
MItem *ExportLight(FbxNodeAttribute *, FbxNode * = 0);
/// Dispatch the node to the correct exporter.
MItem *ExportNode(FbxNode *pNode);
/// Create and import an FBX file to a native FBX scene.
FbxScene *LoadNativeScene(const char *fbx_path);
public:
/// Return the geometries created during import.
const List <Core::Geometry *> &GeometryList() const { return geometry_list; }
/// Test importer on a file.
virtual bool TestImport(const char *uri);
/// Import scene from file.
virtual bool ImportScene(Scene *, const char *uri, const Config &, Group ** = 0);
FBXImporter();
~FBXImporter();
};
} // S3D
} // GS
#endif // __FBXIMPORT__

View File

@ -0,0 +1,46 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NOBJ_IMPORT__
#define __NOBJ_IMPORT__
#include "import/import_interface.h"
struct ObjMtl;
namespace GS {
namespace Core { class Geometry; }
namespace S3D {
/*
@short OBJ importer.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class OBJImporter : public IImport
{
const Config *config;
/// Load a material library from file.
bool LoadMaterialLibrary(List <ObjMtl *> &, const char *uri);
public:
/// Import geometry.
Core::Geometry *ImportGeometry(const char *uri, IResourceFactoryEvent * = 0);
/// Test importer on a file.
virtual bool TestImport(const char *uri);
/// Import as scene from obj groups.
virtual bool ImportScene(Scene *, const char *uri, const Config &, Group ** = 0);
};
} // S3D
} // GS
#endif // __NOBJ_IMPORT__

View File

@ -0,0 +1,62 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NIOARCHIVE__
#define __NIOARCHIVE__
#include "archive/archive.h"
#include "container/narray.h"
namespace GS {
namespace IO {
//
struct ArchiveHandle : public Handle
{
size_t cursor;
Array <char> data;
ArchiveHandle(Base *io) : Handle(io), cursor(0) {}
};
/*!
@short I/O Archive
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class Archive : public Base
{
GS::Archive archive;
bool connected;
public:
virtual uint GetCaps() const;
virtual Handle *Open(const char *, Mode = ModeRead);
virtual void Close(Handle *);
virtual bool Delete(const char *);
virtual size_t Tell(Handle *);
virtual size_t Seek(Handle *, ptrdiff_t offset, SeekRef = SeekCurrent);
virtual size_t Read(Handle *, void *, size_t);
virtual size_t Write(Handle *, const void *, size_t);
virtual bool MkDir(const char *) { return false; }
bool IsConnected() const { return connected; }
Archive(const char *uri, const char *index_uri = 0);
};
} // IO
} // GS
#endif // __NIOARCHIVE__

View File

@ -0,0 +1,73 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NIONETCLIENT__
#define __NIONETCLIENT__
#include "io_net/io_net_client_worker_thread.h"
#include "memory/nauto_ptr.h"
namespace GS {
namespace IO {
//
class NetHandle : public Handle
{
friend class Net;
int remote_id;
public:
NetHandle(Base *io, int id) : Handle(io), remote_id(id) {}
~NetHandle();
};
/*!
@short Networked I/O client.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class Net : public Base
{
NetWorkerThread worker;
bool QueueTask(NetWorkerBaseTask &);
public:
virtual uint GetCaps() const;
virtual Handle *Open(const char *, Mode = ModeRead);
virtual void Close(Handle *);
virtual String Hash(const char *uri);
virtual bool Delete(const char *) { return false; }
virtual size_t Tell(Handle *);
virtual size_t Seek(Handle *, ptrdiff_t offset, SeekRef = SeekCurrent);
virtual size_t Read(Handle *, void *, size_t);
virtual size_t Write(Handle *, const void *, size_t) { return 0; }
virtual bool MkDir(const char *) { return false; }
//---------------------------------------------------------------------
bool IsConnected() const;
bool Connect(const char *ip, int port);
void Disconnect();
//---------------------------------------------------------------------
~Net() { Disconnect(); }
};
} // IO
} // GS
#endif // __NIONETCLIENT__

View File

@ -0,0 +1,131 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NIONETCLIENTWORKERTHREAD__
#define __NIONETCLIENTWORKERTHREAD__
#include "network_enet/enet_network.h"
#include "filesystem/io_handle.h"
#include "container/narray.h"
#include "container/nlist.h"
#include "nstring/nstring.h"
#include "thread/thread.h"
#include "thread/mutex.h"
namespace GS {
namespace IO {
//-----------------------------------------------------------------------------
struct NetWorkerBaseTask
{
enum TaskType
{ TypeOpen = 0, TypeClose, TypeSeek, TypeTell, TypeRead, TypeHash };
TaskType type;
// [EJ] a full memory barrier is required when accessing these two variables
Threading::Atomic32 processed;
Threading::Atomic32 success;
};
struct NetWorkerOpenTask : public NetWorkerBaseTask
{
String path;
Mode mode;
NetWorkerOpenTask(const char *p, Mode m) : path(p), mode(m) { type = TypeOpen; }
int handle;
};
struct NetWorkerCloseTask : public NetWorkerBaseTask
{
int handle;
NetWorkerCloseTask(int h) : handle(h) { type = TypeClose; }
};
struct NetWorkerSeekTask : public NetWorkerBaseTask
{
int handle;
ptrdiff_t offset;
Base::SeekRef seek_ref;
NetWorkerSeekTask(int h, ptrdiff_t o, Base::SeekRef ref) : handle(h), offset(o), seek_ref(ref) { type = TypeSeek; }
size_t pos;
};
struct NetWorkerTellTask : public NetWorkerBaseTask
{
int handle;
NetWorkerTellTask(int h) : handle(h) { type = TypeTell; }
size_t pos;
};
struct NetWorkerReadTask : public NetWorkerBaseTask
{
int handle;
void *data;
size_t size;
NetWorkerReadTask(int h, void *p, size_t s) : handle(h), data(p), size(s) { type = TypeRead; }
size_t read_size;
};
struct NetWorkerHashTask : public NetWorkerBaseTask
{
String path;
NetWorkerHashTask(const char *p) : path(p) { type = TypeHash; }
String hash;
};
//-----------------------------------------------------------------------------
/*
@short I/O Network worker thread.
@author Emmanuel Julien (ejulien@owloh.com)
*/
class NetWorkerThread : public Threading::Thread, public Network::Enet
{
String ip;
int port;
void *server_peer;
int handshaking;
Array <char> response;
bool WaitServerResponse();
void ClearServerResponse();
void ProcessIOPacket(const void *, size_t);
virtual void OnPeerConnection(void *peer);
virtual void OnPacketReceived(void *peer, const void *, size_t);
virtual void OnConnectionClosed(void *peer);
virtual void Execute();
Threading::Mutex task_mutex;
List <NetWorkerBaseTask *> task_queue;
bool ProcessOpenTask(NetWorkerOpenTask &);
bool ProcessCloseTask(NetWorkerCloseTask &);
bool ProcessSeekTask(NetWorkerSeekTask &);
bool ProcessTellTask(NetWorkerTellTask &);
bool ProcessReadTask(NetWorkerReadTask &);
bool ProcessHashTask(NetWorkerHashTask &);
void ProcessTask(NetWorkerBaseTask &);
Threading::Atomic32 running;
public:
bool IsConnected() const { return asbool(server_peer); }
bool QueueTask(NetWorkerBaseTask &);
bool CancelTask(NetWorkerBaseTask &);
bool Start(const char *ip, int port);
void Stop();
NetWorkerThread();
};
} // IO
} // GS
#endif // __NIONETCLIENTWORKERTHREAD__

View File

@ -0,0 +1,118 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NIONETSERVER__
#define __NIONETSERVER__
#include "network_enet/enet_network.h"
#include "filesystem/io_handle.h"
#include "memory/nauto_ptr.h"
#include "container/nlist.h"
#include "nstring/nstring.h"
#include "time/ntime.h"
namespace GS {
namespace NML { class File; }
namespace IO {
//
template <typename T> struct Measure
{
Time time;
T value;
};
/*!
@short Networked I/O server.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class NetServer : public Network::Enet
{
SharedPtr <Base> basefs; // Support IO system.
Measure <int> bandwidth_measure;
int bandwidth;
// Client handle info
struct ClientHandleInfo
{
int id;
String name;
AutoPtr <Handle> handle;
ClientHandleInfo() : id(0) {}
};
// Connected peer
struct Client
{
void *peer;
int handshake_step;
AutoList <ClientHandleInfo *> handles;
Client(void *p) : peer(p), handshake_step(0) {}
};
AutoList <Client *> clients;
bool ProcessOpenCommand(Client &, StringList &);
bool ProcessReadCommand(Client &, StringList &);
bool ProcessSeekCommand(Client &, StringList &);
bool ProcessTellCommand(Client &, StringList &);
bool ProcessCloseCommand(Client &, StringList &);
bool ProcessHashCommand(Client &, StringList &);
bool ProcessClientRequest(Client &, const String &);
int GetClientOpenHandleCount(const Client &) const;
int GetClientFreeHandleIndex(const Client &) const;
Handle *GetClientHandle(const Client &, int handle_id) const;
Client *GetClient(void *peer);
public:
struct Statistics
{
bool connected;
int sent_data; // in bytes
int bandwidth; // in bytes
int packet_loss; // in %
struct Handle
{
String name;
};
Array <Handle> handles;
Statistics() : connected(false), sent_data(0), bandwidth(0), packet_loss(0) {}
};
void GetStatistics(Statistics &);
const AutoList <Client *> &GetClients() const { return clients; }
virtual void OnPeerConnection(void *peer);
virtual void OnPacketReceived(void *peer, const void *, size_t);
virtual void OnConnectionClosed(void *peer);
bool Start(const char *ip, int port);
void Stop();
NetServer(Base *);
~NetServer();
};
} // IONet
} // GS
#endif // __NIONETSERVER__

View File

@ -0,0 +1,51 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NIONETSERVERTHREAD__
#define __NIONETSERVERTHREAD__
#include "io_net/io_net_server.h"
#include "thread/mutex.h"
#include "thread/thread.h"
#include "thread/atomic_value.h"
#include "filesystem/io_base.h"
#include "memory/nshared_ptr.h"
#include "nstring/nstring.h"
namespace GS {
namespace IO {
//
class NetServerThread : public Threading::Thread
{
String ip;
int port;
SharedPtr <Base> basefs;
Threading::Atomic32 state;
Threading::Mutex server_mutex;
AutoPtr <NetServer> server;
public:
void GetStatistics(NetServer::Statistics &);
void Execute();
bool Start(const char *ip, int port);
void Stop();
NetServerThread(Base *fs) : basefs(fs) {}
~NetServerThread();
};
} // IO
} // GS
#endif // __NIONETSERVERTHREAD__

View File

@ -0,0 +1,74 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NIOZIP__
#define __NIOZIP__
#include <stdio.h>
#include "filesystem/io_handle.h"
#include "filesystem/io_memory.h"
#include "container/nmap.h"
#include "nstring/nstring.h"
#include "memory/nauto_ptr.h"
namespace GS {
namespace IO {
//
class ZipHandle : public Handle
{
friend class Zip;
AutoPtr <Handle> h;
Pair <String, int> *p;
public:
ZipHandle(Base *io) : Handle(io), p(0) {}
};
/*!
@short Zip-based I/O.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class Zip : public Base
{
void *zfile;
String password;
Map <String, int> refc_map;
SharedPtr <Memory> memfs; // Support IO system.
public:
bool SetArchive(const char *uri, const char *password = 0);
virtual uint GetCaps() const;
virtual Handle *Open(const char *, Mode = ModeRead);
virtual void Close(Handle *);
virtual bool Delete(const char *);
virtual size_t Tell(Handle *);
virtual size_t Seek(Handle *, ptrdiff_t offset, SeekRef = SeekCurrent);
virtual size_t Read(Handle *, void *, size_t);
virtual size_t Write(Handle *, const void *, size_t);
virtual bool MkDir(const char *) { return false; }
Zip(const char *uri, const char *password = 0);
~Zip();
};
} // IO
} // GS
#endif // __NIOZIP__

View File

@ -0,0 +1,40 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NAVMESH__
#define __NAVMESH__
namespace GS {
namespace Core { class Geometry; }
namespace Nav {
class Mesh
{
public:
/// Agent configuration.
struct AgentConfig
{
float height,
radius,
max_climb;
};
/// Build configuration.
struct BuildConfig
{
AgentConfig agent;
};
/// Build navigation mesh from configuration.
bool Build(const Core::Geometry *, const BuildConfig &);
};
} // Nav
} // GS
#endif // __NAVMESH__

View File

@ -0,0 +1,13 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __PATHFINDING_PATH__
#define __PATHFINDING_PATH__
#endif // __PATHFINDING_PATH__

View File

@ -0,0 +1,63 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __ENETNETWORK__
#define __ENETNETWORK__
#include <enet/enet.h>
#include "network/network_interface.h"
namespace GS {
namespace Network {
/*
@short Enet network.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Enet : public INetwork
{
protected:
ENetHost *host;
public:
virtual void GetStatistics(Statistics &);
virtual int GetPeerPacketLossRatio(void *peer);
/*!
@name Communication interface.
@{
*/
virtual void UpdateHost();
virtual bool Send(void *peer, const void *data, size_t size);
virtual bool Broadcast(const void *data, size_t size);
/// @}
bool IsOpen() const { return asbool(host); }
virtual bool GetHostAddress(String &address);
virtual bool GetPeerAddress(void *peer, String &address);
virtual void SetPeerTimeout(void *peer, Timeout = TimeoutDefault);
virtual bool OpenServer(const char *address = "127.0.0.1", int port = 999);
virtual bool OpenClient(const char *address = "127.0.0.1", int port = 999);
virtual void Disconnect(void *peer);
void Close();
Enet();
~Enet();
};
} // Network
} // GS
#endif // __ENETNETWORK__

View File

@ -0,0 +1,189 @@
#ifndef CC_PHYSICS_H
#define CC_PHYSICS_H
#include "BulletCollision/CollisionDispatch/btGhostObject.h"
#include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
#include "BulletCollision/CollisionShapes/btCapsuleShape.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
#include "BulletCollision/CollisionDispatch/btCollisionWorld.h"
#include "LinearMath/btDefaultMotionState.h"
#include "BulletDynamics/Character/btCharacterControllerInterface.h"
//
class btCustomCharacterController : public btCharacterControllerInterface
{
btScalar mHalfHeight;
btPairCachingGhostObject *mGhostObject;
btConvexShape *mConvexShape;
btConvexShape *mStandingConvexShape;
btConvexShape *mDuckingConvexShape;
btCollisionWorld *mCollisionWorld;
btVector3 mStepVelocity;
btScalar mVerticalVelocity;
btScalar mVerticalOffset;
btScalar mFallSpeed;
btScalar mJumpSpeed;
btScalar mMaxJumpHeight;
btScalar mMaxSlopeRadians;
btScalar mMaxSlopeCosine;
btScalar mGravity;
btScalar mTurnAngle;
btScalar mStepHeight;
btScalar mAddedMargin;
btVector3 mWalkDirection;
btVector3 mNormalizedDirection;
btVector3 mCurrentPosition;
btManifoldArray mManifoldArray;
bool mGroundContact;
btVector3 mGroundNormal;
bool mTouchingContact;
bool dbg_step_high;
bool dbg_down_sweep_hit;
void performStep(btScalar dt);
bool SweepAndSlide(btVector3 &from, btVector3 &to, int);
bool mUseWalkDirection;
btScalar mVelocityTimeInterval;
int mUpAxis;
btVector3 mLinearVelocity;
btScalar mMass;
class ClosestNotMeRayResultCallback : public btCollisionWorld::ClosestRayResultCallback
{
btCollisionObject *mMe;
public:
ClosestNotMeRayResultCallback(btCollisionObject * me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0, 0, 0), btVector3(0, 0, 0)), mMe(me) {}
btScalar addSingleResult(btCollisionWorld::LocalRayResult &rayResult, bool normalInWorldSpace)
{
if (rayResult.m_collisionObject == mMe)
return 1.0;
return btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
}
};
class ClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
{
btCollisionObject *mMe;
const btVector3 mUp;
btScalar mMinSlopeDot;
public:
ClosestNotMeConvexResultCallback(btCollisionObject *me, const btVector3 &up, btScalar minSlopeDot) : btCollisionWorld::ClosestConvexResultCallback(btVector3(0, 0, 0), btVector3(0, 0, 0)), mMe(me), mUp(up), mMinSlopeDot(minSlopeDot) {}
btScalar addSingleResult(btCollisionWorld::LocalConvexResult &convexResult, bool normalInWorldSpace)
{
if (convexResult.m_hitCollisionObject == mMe)
return 1.0;
btVector3 hitNormalWorld;
if (normalInWorldSpace)
hitNormalWorld = convexResult.m_hitNormalLocal;
else
hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal;
btScalar dotUp = mUp.dot(hitNormalWorld);
if (dotUp < mMinSlopeDot)
return 1.0;
return btCollisionWorld::ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace);
}
};
static btVector3 *getUpAxisDirections()
{
static btVector3 sUpAxisDirection[3] = { btVector3(1, 0, 0), btVector3(0, 1, 0), btVector3(0, 0, 1) };
return sUpAxisDirection;
}
static btVector3 getNormalizedVector(const btVector3& v)
{
btVector3 n = v.normalized();
if (n.length() < SIMD_EPSILON)
n.setValue(0, 0, 0);
return n;
}
bool SweepTest(const btVector3 &, const btVector3 &, btScalar &fraction, btVector3 *normal = 0, btVector3 *hit = 0);
btVector3 computeReflectionDirection(const btVector3 & direction, const btVector3 & normal);
void setPlayerMode();
public:
btCustomCharacterController(btPairCachingGhostObject *ghostObject, btConvexShape *convexShape, btScalar stepHeight, btCollisionWorld *collisionWorld, int upAxis = 1);
btVector3 getUpAxisDirection() const { return getUpAxisDirections()[mUpAxis]; }
void setDuckingConvexShape(btConvexShape * shape);
bool recoverFromPenetration(const btVector3 &step_direction);
void stepUp(btCollisionWorld * collisionWorld);
void setRBForceImpulseBasedOnCollision();
void updateTargetPositionBasedOnCollision(const btVector3 & hitNormal, btScalar tangentMag = 0, btScalar normalMag = 1);
void stepForwardAndStrafe(btCollisionWorld * collisionWorld, const btVector3 & walkMove);
void stepDown(btCollisionWorld * collisionWorld, btScalar dt);
void setVelocityForTimeInterval(const btVector3 & velocity, btScalar timeInterval);
void reset() {}
void warp(const btVector3 & origin);
void preStep(btCollisionWorld * collisionWorld);
void playerStep(btCollisionWorld * collisionWorld, btScalar dt);
void setFallSpeed(btScalar fallSpeed);
void setJumpSpeed(btScalar jumpSpeed);
void setMaxJumpHeight(btScalar maxJumpHeight);
bool canJump() const;
void jump();
void duck();
void stand();
bool canStand();
void setGravity(const btScalar gravity);
btScalar getGravity() const;
void setMaxSlope(btScalar slopeRadians);
btScalar getMaxSlope() const;
bool onGround() const;
void setWalkDirection(const btVector3 & walkDirection);
void setWalkDirection(const btScalar x, const btScalar y, const btScalar z);
void setOrientation(const btQuaternion & orientation);
btVector3 getWalkDirection() const;
btVector3 getPosition() const;
void debugDraw(btIDebugDraw * debugDrawer);
void updateAction(btCollisionWorld * collisionWorld, btScalar dt);
};
#endif // CC_PHYSICS_H

View File

@ -0,0 +1,51 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NBULLET_CONSTRAINT__
#define __NBULLET_CONSTRAINT__
#include "physic/physic_constraint.h"
class btDiscreteDynamicsWorld;
class btTypedConstraint;
namespace GS {
namespace S3D {
/*
@short Bullet physic constraint.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class BulletConstraint : public PhysicConstraint
{
friend class BulletWorld;
btDiscreteDynamicsWorld *world;
btTypedConstraint *constraint;
public:
void setLimitHinge(float low, float high, float _softness = 0.9f, float _biasFactor = 0.3f, float _relaxationFactor = 1.0f);
void SetPivotA(const Matrix4 &);
void SetPivotB(const Matrix4 &);
bool SetupConstraint(const PhysicConstraintDesc &);
void DeleteConstraint();
void Enable(bool = true);
BulletConstraint(btDiscreteDynamicsWorld *);
virtual ~BulletConstraint();
};
} // S3D
} // GS
#endif // __NBULLET_CONSTRAINT__

View File

@ -0,0 +1,75 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NBULLETDEBUG__
#define __NBULLETDEBUG__
#include "btBulletDynamicsCommon.h"
#include "color/color.h"
#include "math/vector.h"
#include "container/narray.h"
namespace GS {
namespace Core { class Camera; }
namespace Render {
class Renderer;
class RasterFont;
}
namespace S3D {
using Render::Renderer;
using Render::RasterFont;
using Core::Camera;
/*!
@short Bullet debug interface.
*/
class BulletDebugDraw : public btIDebugDraw
{
friend class BulletWorld;
protected:
Renderer &renderer;
Camera *camera;
RasterFont *raster_font;
int debug_mode;
Array <Vector4> vtx_cache;
Array <Color> col_cache;
uint line_count;
bool xray_first_pass;
public:
float GetXRayAlpha() const;
void SetXRayFirstPass(bool pass);
void SetDebugMode(int mode) { debug_mode = mode; }
void drawLine(const btVector3 &from, const btVector3 &to, const btVector3 &color);
void drawContactPoint(const btVector3 &PointOnB, const btVector3 &normalOnB, btScalar distance, int lifeTime, const btVector3 &color);
void reportErrorWarning(const char *warningString);
void draw3dText(const btVector3 &location, const char *textString);
void setDebugMode(int mode) { debug_mode = mode; }
int getDebugMode() const { return debug_mode; }
void Flush();
BulletDebugDraw(Renderer &);
};
} // S3D
} // GS
#endif // __NBULLETDEBUG__

View File

@ -0,0 +1,175 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NBULLET_ITEM__
#define __NBULLET_ITEM__
#include "physic_bullet/bullet_world.h"
#include "physic/physic_item.h"
#include "math/matrix4.h"
#include "container/narray.h"
#include "memory/nauto_ptr.h"
#include "BulletDynamics/Character/btKinematicCharacterController.h"
namespace GS {
namespace S3D {
class BulletPhysicItem;
//
class BulletMotionState : public btDefaultMotionState
{
BulletPhysicItem *item;
Matrix4 bullet_matrix, engine_matrix;
public:
/// Return the last matrix Bullet sent.
const Matrix4 &GetGraphicMatrix() const { return bullet_matrix; }
void SetEngineMatrix(const Matrix4 &m) { engine_matrix = m; }
/// Transform to Bullet.
virtual void getWorldTransform(btTransform &centerOfMassWorldTrans) const;
/// Transform from Bullet.
virtual void setWorldTransform(const btTransform &centerOfMassWorldTrans);
BulletMotionState(BulletPhysicItem *);
};
/*
@short Bullet physic item.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class BulletPhysicItem : public PhysicItem
{
friend class BulletWorld;
btDiscreteDynamicsWorld *btworld;
struct ShapeData
{
AutoPtr <btCollisionShape> shape;
SharedPtr <BulletConvex> convex;
SharedPtr <BulletMesh> mesh;
};
Array <ShapeData> shapes;
uint collision_mask, self_mask; // cached copies to properly handle activation/deactivation.
public:
AutoPtr <BulletMotionState> motion_state;
AutoPtr <btCompoundShape> compound;
AutoPtr <btRigidBody> rigid_body;
AutoPtr <btDefaultVehicleRaycaster> vehicle_raycaster;
AutoPtr <btRaycastVehicle> vehicle;
AutoPtr <btPairCachingGhostObject> ghost_object;
AutoPtr <btConvexShape> convex_shape;
AutoPtr <btCharacterControllerInterface> character_controller;
Vector4 center;
Vector4 scale;
bool SetupCharacterController(const PhysicItemDesc &);
bool SetupKinematicDynamicBody(const PhysicItemDesc &, PhysicWorld *);
float SetupCollisionShapes(const PhysicItemDesc &, Array <btScalar> &, PhysicWorld *);
void ForceUpdateMassShapePhysic(const PhysicItemDesc &, PhysicWorld *);
/// Create a Bullet transformation from a 4x4 matrix.
static void TransformFromMatrix4(const Matrix4 &, btTransform &);
/// Create a 4x4 matrix to a Bullet transformation.
static void TransformToMatrix4(const btTransform &, Matrix4 &);
/*
@short Return the center of mass offset.
Bullet does not handle offset center of mass directly.
*/
const Vector4 &GetCenter() const { return center; }
void SetScale(const Vector4 &);
Vector4 GetScale() const;
//----------------------------------------------------------------------
void SetSelfMask(uint m);
uint GetSelfMask() const;
void SetCollisionMask(uint m);
uint GetCollisionMask() const;
//----------------------------------------------------------------------
//----------------------------------------------------------------------
void SetLinearFactor(const Vector4 &);
void SetAngularFactor(const Vector4 &);
void SetLinearDamping(float = 0.999f);
float GetLinearDamping() const;
void SetAngularDamping(float = 0.99f);
float GetAngularDamping() const;
void SetGravity(const Vector4 &);
Vector4 GetGravity() const;
void ApplyImpulse(const Vector4 &I, const Vector4 *p = 0);
void ApplyForce(const Vector4 &F, const Vector4 *p = 0);
void ApplyTorque(const Vector4 &T);
void SetAngularVelocity(const Vector4 &);
Vector4 GetAngularVelocity() const;
void SetLinearVelocity(const Vector4 &);
Vector4 GetLinearVelocity() const;
Vector4 GetLocalPointVelocity(const Vector4 &) const;
Vector4 GetWorldPointVelocity(const Vector4 &) const;
Vector4 GetCenterOfMass() const;
//----------------------------------------------------------------------
//----------------------------------------------------------------------
void GetGraphicMatrix(Matrix4 &);
void SetEngineMatrix(const Matrix4 &);
void GetMatrix(Matrix4 &);
void SetMatrix(const Matrix4 &);
//----------------------------------------------------------------------
//----------------------------------------------------------------------
virtual void VehicleSetForce(float F, uint wheel_index);
virtual void VehicleSetBrake(float F, uint wheel_index);
virtual void VehicleSetSteering(float v, uint wheel_index);
virtual void VehicleSetFriction(float f, uint wheel_index);
virtual Matrix4 VehicleGetWheelMatrix(uint wheel_index);
//----------------------------------------------------------------------
//----------------------------------------------------------------------
virtual void CharacterSetRotationMatrix(const Matrix3 &);
virtual void CharacterSetVelocity(const Vector4 &);
//----------------------------------------------------------------------
virtual void SetSleeping(bool sleep = false);
virtual bool IsSleeping() const;
virtual void SetActive(bool active);
virtual bool GetActive() const;
virtual void ResetBody();
virtual bool SetupBody(const PhysicItemDesc &, PhysicWorld *);
virtual void DeleteBody();
BulletPhysicItem(btDiscreteDynamicsWorld * = 0);
virtual ~BulletPhysicItem();
};
} // S3D
} // GS
#endif // __NBULLET_ITEM__

View File

@ -0,0 +1,127 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NBULLETPHYSICWORLD__
#define __NBULLETPHYSICWORLD__
#include "nstring/nstring.h"
/*
@short Enable multi-threading support in Bullet Dynamics.
Not working at the moment (need to let the API stabilize a bit first).
*/
#define __ENABLE_BULLET_MULTITHREAD__ 0
/*
@short Number of thread used by Bullet.
*/
#define __BULLET_THREAD_COUNT__ 3
#include "memory/nauto_ptr.h"
#include "memory/nshared_ptr.h"
#include "physic/physic_world.h"
#include "btBulletDynamicsCommon.h"
#include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
#if __ENABLE_BULLET_MULTITHREAD__
#include "BulletMultiThreaded/SpuGatheringCollisionDispatcher.h"
#include "BulletMultiThreaded/PlatformDefinitions.h"
#if __PLATFORM_WINDOWS__
#include "BulletMultiThreaded/Win32ThreadSupport.h"
#include "BulletMultiThreaded/SpuNarrowPhaseCollisionTask/SpuGatheringCollisionTask.h"
#elif __PLATFORM_LINUX__
#include "BulletMultiThreaded/PosixThreadSupport.h"
#include "BulletMultiThreaded/SpuNarrowPhaseCollisionTask/SpuGatheringCollisionTask.h"
#endif
#endif
namespace GS {
namespace S3D {
class Scene;
class BulletDebugDraw;
/// Bullet convex hull.
struct BulletConvex : public SharedObject
{
String name;
Vector4 center;
AutoPtr <btConvexHullShape> convex;
};
/// Bullet mesh.
struct BulletMesh : public SharedObject
{
String name;
String suffix;
Vector4 center;
Array <String> bt_mat;
Array <ushort> bt_id_mat;
Array <btScalar> bt_vtx;
Array <int> bt_idx;
AutoPtr <btTriangleIndexVertexArray> mesh_interface;
AutoPtr <btBvhTriangleMeshShape> mesh;
};
/*!
@short Bullet physic world.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class BulletWorld : public PhysicWorld
{
protected:
SharedList <BulletMesh *> mesh_cache;
SharedList <BulletConvex *> convex_cache;
AutoPtr <btDiscreteDynamicsWorld> world;
AutoPtr <btBroadphaseInterface> broadphase;
AutoPtr <btCollisionDispatcher> dispatcher;
AutoPtr <btDefaultCollisionConfiguration> collision_config;
AutoPtr <btSequentialImpulseConstraintSolver> solver;
AutoPtr <btOverlappingPairCallback> pair_callback;
#if __ENABLE_BULLET_MULTITHREAD__
AutoPtr <btThreadSupportInterface> thread_support_collision;
#endif
AutoPtr <BulletDebugDraw> debug_draw;
public:
PhysicItem *NewItem();
PhysicConstraint *NewConstraint();
BulletConvex *LoadConvex(const char *);
BulletMesh *LoadMesh(const char *, const char *suffix);
void ClearConvexMeshCache();
bool HasDebugger() const;
void CreateDebugger(Renderer * = 0);
void DrawDebug(Renderer &, Camera *, RasterFont *, bool xray_first_pass);
/// Raytrace world, the callback object Process() method is called on each hit.
bool Raytrace(const Vector4 &s, const Vector4 &d, PhysicTrace &, int collision_mask = ~0, int shape_mask = ~0, float max_distance = -1.f);
uint GetCollisionPairCount();
bool GetCollisionPair(uint, CollisionPair &);
void Step(const Time &dt);
bool Create();
void Delete();
BulletWorld();
~BulletWorld();
};
} // S3D
} // GS
#endif // __NBULLETPHYSICWORLD__

View File

@ -0,0 +1,34 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __PICTJPEGLIBCODEC__
#define __PICTJPEGLIBCODEC__
#include "picture/pict_io_codec.h"
namespace GS {
/*
@short IJG jpeglib codec.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct PictureJpeglibCodec : public PictureCodec
{
virtual bool Load(IO::Handle &, Picture &);
virtual bool Save(IO::Handle &, const Picture &);
virtual const char *GetName() const { return "IJG"; }
virtual const char *GetDesc() const { return "IJG jpeglib read/write codec"; }
virtual uint GetCaps() const { return CanRead | CanWrite | WriteLossy | AlphaChannel; }
};
}
#endif // __PICTJPEGLIBCODEC__

View File

@ -0,0 +1,34 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __PICTSTBCODEC__
#define __PICTSTBCODEC__
#include "picture/pict_io_codec.h"
namespace GS {
/*
@short STB (Sean Barrett picture) codec.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
struct PictureSTBCodec : public PictureCodec
{
bool Load(IO::Handle &, Picture &);
const char *GetName() const { return "STB"; }
const char *GetDesc() const { return "STB image (Sean Barrett image library) codec"; }
uint GetCaps() const { return CanRead; }
};
} // GS
#endif // __PICTSTBCODEC__

View File

@ -0,0 +1,296 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __TRACER_CORE__
#define __TRACER_CORE__
#include "raytracer/raytracer_scene.h"
#include "raytracer/raytracer_spread.h"
#include "core/shader_tree.h"
#include "core/material.h"
#include "picture/pict.h"
namespace GS {
struct Color;
namespace Core {
struct ShaderBlock;
struct ShaderBlockValue;
}
namespace S3D { class Scene; }
namespace Raytrace {
//
struct Bounce
{
uint indirect,
reflection,
refraction;
};
/// Ray grid (ray density estimation).
struct RayGrid
{
Vector4 p[4], d[4];
RayGrid(const Vector4 &_p, const Vector4 &_d)
{ p[0] = _p; d[0] = _d; }
};
//
struct Statistics
{
uint ray_count,
tri_test;
void Reset()
{
ray_count = 0;
tri_test = 0;
}
Statistics()
{ Reset(); }
};
//
struct Configuration
{
uint trace_shadow_transparency_max_recursion,
trace_reflection_max_recursion,
trace_refraction_max_recursion,
indirect_gi_bounce,
gi_sample,
aa_sample;
bool trace_shadow,
trace_gi,
trace_aa,
trace_transparency,
trace_reflection,
trace_refraction,
gi_use_ambient,
aa_jitter,
ao_activate,
fresnel_activate;
float ao_length,
ao_angle;
bool interlaced, ///< Interlaced render.
interlace_even, ///< Start with even ordered scanline.
interlaced_trace_half_frame; ///< When rendering interlaced, compute half-frames instead of full ones (at a very small cost in quality).
float aa_threshold;
uint job_affinity;
Configuration()
{
trace_shadow_transparency_max_recursion = 32;
trace_reflection_max_recursion = 2;
trace_refraction_max_recursion = 6;
indirect_gi_bounce = 1;
trace_shadow = true;
trace_reflection = true;
trace_refraction = true;
trace_gi = false;
trace_aa = true;
trace_transparency = true;
ao_length = 1.0f;
ao_angle = 90.0f;
ao_activate = false;
fresnel_activate = false;
gi_use_ambient = false;
gi_sample = 8;
aa_sample = 4;
aa_threshold = 0.0075f;
aa_jitter = false;
interlaced = false;
interlace_even = true;
interlaced_trace_half_frame = true;
job_affinity = uint(~0);
}
};
class Raytracer;
//
struct Progress
{
const Raytracer *instance;
String description;
uint start_clock; ///< System clock when rendering started.
float progress;
int w, h;
Color *buffer;
bool aborted; ///< Rendering aborted.
bool done; ///< Rendering done.
};
/// Progress hook.
struct ProgressHook
{ virtual bool RaytracerProgress(const Progress &) = 0; };
/*!
@short Raytracer.
This class can be used as a generic raytracer to render raytraced pictures
of a scene or as a baking tool for the nGeometry class.
Supports, forward raytracing, Monte-Carlo raytracing, photon mapping along
more common material properties, diffuse, specular, reflection, refraction,
etc...
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class Raytracer
{
public:
/// Geometry attributes.
enum GeometryAttribute
{
GeometryNormal = 0,
GeometryVertexColor
};
protected:
bool abort;
Core::ResourceFactory *gf;
const S3D::Scene *scene;
SceneBIH scene_tree, ///< Scene tree.
scene_shadow_tree; ///< Shadow scene tree.
Array <Light> lgt; ///< Light array.
Statistics statistics;
Configuration configuration;
Spread monte_carlo[32]; ///< Monte-Carlo vector spread.
Vector2 viewport; ///< Output resolution of the current rendering.
float render_clock; ///< Reference clock frozen at frame start.
/// Compute the Fresnel factor
float Fresnel(const Vector4 &v, const Vector4 &np, float eta);
/// Compute trace result radiance.
void ComputeRadiance(Trace &trace, Color &o, Bounce &bounce);
/// Raytrace.
void Raytrace(const RayGrid &ray, Color &o, Bounce &bounce, Trace *previous_trace = 0);
/// Evaluate shader block on the CPU.
bool EvaluateShaderBlock(const Trace &trace, const Core::ShaderBlock *block, Core::ShaderBlockValue &out);
/// Sample material opacity.
float SampleMaterialOpacity(const Trace &trace);
/// Sample material sink.
virtual Vector4 SampleMaterialSink(const Trace &trace, Core::ShaderTree::ShaderSinkType sink);
/// Sample material attribute.
Vector4 SampleMaterialAttribute(const Trace &trace, Core::MaterialChannel channel);
/// Sample geometry attribute.
Vector4 SampleGeometryAttribute(const Trace &trace, GeometryAttribute attr);
/// Shadow feel.
float ShadowFeel(const Vector4 &s, const Vector4 &d, float l, int r);
/*!
@name Interlace support.
@{
*/
bool interlace_even; ///< Internal interlace parity.
Picture interlace_half_frame; ///< The previous interlace frame.
/// @}
public:
ProgressHook *hook;
/// Get system configuration.
Configuration &GetConfiguration()
{ return configuration; }
/// Set system configuration.
void SetConfiguration(const Configuration &config);
/// Return system statistics object.
const Statistics &GetStatistics() const { return statistics; }
/// Abort current rendering.
void Abort();
/// Last render abort flag.
bool Aborted() const { return abort; }
/*!
@short Start a rendering sequence.
@note This call is only necessary when rendering an interlaced
sequence.
*/
void StartInterlacedSequence();
/// Trace a primary ray across the scene tree, returns resulting HDR color.
void PrimaryRay(const RayGrid &ray, Color &o);
/*!
@short Raytrace scene to a raw raytracing structure.
Use this function if you need the intersected scene object and its
geometric properties rather than a fully computed evaluation.
*/
void RawPrimaryRay(const Vector4 &s, const Vector4 &d, Trace &t, float l = -1.f) { scene_tree.RaytraceScene(t, s, d, l); }
/*!
@short Perform a full scene raytracing.
@note The raytracer internally only works with real colors.
The frame is converted by the end of the render to rgb24.
@note The provided picture object will be reallocated to the
render output dimensions and all previous content will be
lost.
*/
bool Render(Picture &, uint width = 640, uint height = 480);
/// Return the internal scene BIH tree.
SceneBIH &GetBIH() { return scene_tree; }
/// Return the internal scene shadow BIH tree.
SceneBIH &GetShadowBIH() { return scene_shadow_tree; }
/*!
@short Setup a scene for use by the raytracer.
@note The raytracer does not mirror any data from the scene
so it will rely on the object remaining valid as long
as it is registered as the current raytracer scene.
@warning Before deleting the referred scene object do not forget
to call SetScene(NULL) in order to release all
references.
*/
bool SetScene(const S3D::Scene *);
void Free();
Raytracer(Core::ResourceFactory * = 0);
virtual ~Raytracer() {}
};
} // Raytrace
} // GS
#endif // __TRACER_CORE__

View File

@ -0,0 +1,58 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRAYTRACERJOB__
#define __NRAYTRACERJOB__
#include "raytracer/raytracer_core.h"
#include "async/job.h"
namespace GS {
namespace Raytrace {
//
struct RaytraceJob : public ASync::Job
{
virtual void Execute(uint);
Raytracer *core;
Color *hdr;
int pitch;
int start_height, end_height;
int start_width, end_width;
Vector4 s;
Vector4 dt_l, pt_l, dt_r, pt_r;
RaytraceJob() : Job("Raytrace") {}
};
//
struct AntialiasJob : public ASync::Job
{
virtual void Execute(uint);
Raytracer *core;
Color *hdr;
int pitch;
int start_height, end_height;
int start_width, end_width;
Vector4 s;
Vector4 dt_l, pt_l, dt_r, pt_r;
AntialiasJob() : Job("Antialias") {}
};
} // Raytrace
} // GS
#endif // __NRAYTRACERJOB__

View File

@ -0,0 +1,124 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRAYTRACERSCENE__
#define __NRAYTRACERSCENE__
#include "core/geometry_tree.h"
#include "bih/bih.h"
namespace GS {
namespace Core {
class Object;
class Geometry;
struct Material;
}
namespace S3D {
class Scene;
struct MLight;
struct MObject;
}
namespace Raytrace {
using Core::IGeometryTree;
//
struct Trace : public Core::GeometryTrace
{
Vector4 pi; ///< Intersection point.
Vector4 n; ///< Normal.
float ir; ///< Current media index of refraction.
float td; ///< Total distance traveled by the ray.
Core::Object *o; ///< Object intersected.
Trace(bool closest = true) : Core::GeometryTrace(closest)
{
ir = 1;
td = 0;
m = NULL;
}
};
///
struct Object
{
Core::Object *o; ///< Object.
Core::sGeometry og, g; ///< Associated geometry.
AutoPtr <IGeometryTree> tree;
Object() : o(0) {}
};
///
struct Light
{
IGeometryTree *g; ///< Shadow cache tree.
uint ip; ///< Shadow cache polygon index.
S3D::MLight *l;
Light() : l(0) {}
};
/*!
@short Raytracer scene acceleration structure.
*/
class SceneBIH : BIH::Tree
{
Array <Object> obj; ///< Object array.
/// Trace leaf content.
void TraceLeaf(BIH::Node *, float tmin, float tmax, BIH::Trace &, void *parm = 0);
/// Add an object to the scene BIH.
void AddObject(Core::ResourceFactory &, S3D::MObject *, uint &obj_count, MinMax *varray, bool shadow);
public:
/*!
@short Translate proxy geometry.
The raytracer may need to make a hard copy of a geometry for example
to freeze its modifiers before building the acceleration structure.
This function returns the original geometry from the proxy one as
returned by a primary ray test.
@note If the geometry is not a proxy, it will be returned as is.
*/
Core::Geometry *TranslateGeometry(Core::Geometry *) const;
/*!
@group Statistics
@{
*/
uint ray_count; ///< Number of ray traced.
/// Reset internal statistic counters.
void ResetStats();
/// @}
/// Build scene tree based on a scene instance.
virtual bool SetScene(Core::ResourceFactory &, const S3D::Scene *, bool shadow = false);
/// Free tree structures.
virtual void Free();
/// Raytrace hierarchy.
virtual void RaytraceScene(Trace &, const Vector4 &s, const Vector4 &d, float l = -1.f);
SceneBIH() { min_leaf_vcount = 3; }
};
} // Raytrace
} // GS
#endif // __NRAYTRACERSCENE__

View File

@ -0,0 +1,31 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRAYTRACER_SPREAD__
#define __NRAYTRACER_SPREAD__
#include "math/vector.h"
#include "container/narray.h"
namespace GS {
namespace Raytrace {
//
struct Spread
{
Array <Vector4> spread;
bool Initialize(uint u_count, uint v_count, float max_spread = Units::Deg(90.f));
void Free();
};
} // Raytrace
} // GS
#endif // __NRAYTRACER_SPREAD__

View File

@ -0,0 +1,58 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __COBJECT__
#define __COBJECT__
#include "script/script_engine_types.h"
#include "script_squirrel/squirrel_vm.h"
#include "thread/mutex.h"
namespace GS {
namespace Script {
struct EngineVM;
/*!
@short Weak/shared reference to native C/C++ objects for the Squirrel VM.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class CObject
{
EngineVM *vm;
public:
/// Pop safe user pointer.
static bool Get(HSQUIRRELVM, int stack_index, void **, CObjectType = typetag_Undefined);
/// Get safe user pointer type.
static bool GetType(HSQUIRRELVM, int idx, CObjectType &);
// Get a base object from derived types.
static bool GetBase(HSQUIRRELVM, int idx, void **, CObjectType *derived_types);
/// Push safe user pointer.
static bool Push(HSQUIRRELVM, void *, CObjectType, bool managed = false);
/// Initialize reference to a native type.
void Initialize(CObjectType, void *, bool managed);
/// Release reference to a native type.
void Release();
bool managed;
List <CObject *> ::Item *list_item; // Needs to be cached for fast deletion.
CObjectType type;
void *native;
CObject(EngineVM *vm, CObjectType = typetag_Undefined, void *p = 0, bool managed = false);
~CObject();
};
} // Script
} // GS
#endif // __COBJECT__

View File

@ -0,0 +1,20 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __COBJECT_DECL
#define __COBJECT_DECL
#include "script_squirrel/cobject/squirrel_bindings_utils.h"
namespace GS { class CObject; }
_DECL_CLASS(CObject);
_DECL_NATIVE_CONSTRUCTION(CObject, GS::CObject);
#endif // __COBJECT_DECL

View File

@ -0,0 +1,20 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __COBJECT_GEOMETRY_TEMPLATE_DECL__
#define __COBJECT_GEOMETRY_TEMPLATE_DECL__
#include "script_squirrel/cobject/squirrel_bindings_utils.h"
class nGeometryTemplate;
_DECL_CLASS(GeometryTemplate)
_DECL_NATIVE_CONSTRUCTION(GeometryTemplate, nGeometryTemplate)
#endif // __COBJECT_GEOMETRY_TEMPLATE_DECL__

View File

@ -0,0 +1,25 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __COBJECT_MATRIX_DECL__
#define __COBJECT_MATRIX_DECL__
#include "script_squirrel/cobject/squirrel_bindings_utils.h"
namespace GS {
class Matrix3;
class Matrix4;
}
_DECL_CLASS(Matrix3)
_DECL_NATIVE_CONSTRUCTION(Matrix3, GS::Matrix3)
_DECL_CLASS(Matrix4)
_DECL_NATIVE_CONSTRUCTION(Matrix4, GS::Matrix4)
#endif // __COBJECT_MATRIX_DECL__

View File

@ -0,0 +1,24 @@
/* -----------------------------------------------------------------------------
nEngine - GSFramework
Copyright 2001-2012 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __COBJECT_QUATERNION_DECL__
#define __COBJECT_QUATERNION_DECL__
#include "script_squirrel/cobject/squirrel_bindings_utils.h"
#ifndef _T
#define _T
#endif
struct nQuaternion;
_DECL_CLASS(Quaternion)
_DECL_NATIVE_CONSTRUCTION(Quaternion, nQuaternion)
#endif // __COBJECT_QUATERNION_DECL__

View File

@ -0,0 +1,239 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __CU_BINDING_UTILS__
#define __CU_BINDING_UTILS__
#include "squirrel.h"
#include "script_squirrel/cobject/squirrel_object.h"
namespace GS {
namespace Script {
class CObject;
}
}
struct ScriptClassMemberDecl
{
const SQChar *name;
SQFUNCTION func;
int params;
const SQChar *typemask;
};
struct SquirrelClassDecl
{
const SQChar *name;
const SQChar *base;
const ScriptClassMemberDecl *members;
};
struct ScriptConstantDecl
{
const SQChar *name;
SQObjectType type;
union value
{
value(int v = 0) { i = v; }
value(float v) { f = v; }
value(const SQChar *v) { s = v; }
float f;
int i;
const SQChar *s;
} val;
};
struct ScriptNamespaceDecl
{
const SQChar *name;
const ScriptClassMemberDecl *members;
const ScriptConstantDecl *constants;
const ScriptClassMemberDecl *delegate;
};
//------------------------------------------------------------------------------
#define case_ItemDerived \
case typetag_Camera: \
case typetag_Object: \
case typetag_Light: \
case typetag_Trigger: \
case typetag_Item:
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#define _GetCObject(_CPP_CLASS, _TYPETAG, _VAR, _IDX) \
_CPP_CLASS *_VAR = NULL; \
{ \
_GetParamAt(GS::Script::CObject, CObject, _IDX) \
if (self->type != _TYPETAG) \
return sa.ThrowError("Invalid type"); \
if (!self->native) \
return sa.ThrowError("Object is null"); \
_VAR = (_CPP_CLASS *)self->native; \
}
#define _GetSelfNonNull \
_GetSelf(GS::Script::CObject, CObject); \
if (!self->native) \
return sa.ThrowError("Object is null");
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#define _BEGIN_CLASS(classname)\
SQInteger __##classname##__SCypeof(HSQUIRRELVM v)\
{\
sq_pushstring(v,_SC(#classname),-1);\
return 1;\
}\
struct ScriptClassMemberDecl __##classname##_members[] = {\
{_SC("_SCypeof"),__##classname##__SCypeof,1,NULL},
#define _BEGIN_NAMESPACE(xnamespace) struct ScriptClassMemberDecl __##xnamespace##_members[] = {
#define _BEGIN_NAMESPACE_CONSTANTS(xnamespace) {NULL,NULL,NULL,NULL}}; \
struct ScriptConstantDecl __##xnamespace##_constants[] = {
#define _BEGIN_DELEGATE(xnamespace) struct ScriptClassMemberDecl __##xnamespace##_delegate[] = {
#define _DELEGATE(xnamespace) __##xnamespace##_delegate
#define _END_DELEGATE(classname) {NULL,NULL,NULL,NULL}};
#define _CONSTANT(name,type,val) {_SC(#name),type,val},
#define _CONSTANT_IMPL(name,type) {_SC(#name),type,name},
#define _MEMBER_FUNCTION(classname,name,nparams,typemask) \
{_SC(#name),__##classname##_##name,nparams,typemask},
#define _END_NAMESPACE(classname,delegate) {NULL,OT_NULL,0}}; \
struct ScriptNamespaceDecl __##classname##_decl = { \
_SC(#classname), __##classname##_members,__##classname##_constants,delegate };
#define _END_CLASS(classname) {NULL,NULL,NULL,NULL}}; \
struct SquirrelClassDecl __##classname##_decl = { \
_SC(#classname), NULL, __##classname##_members };
#define _END_CLASS_INHERITANCE(classname,base) {NULL,NULL,NULL,NULL}}; \
struct SquirrelClassDecl __##classname##_decl = { \
_SC(#classname), _SC(#base), __##classname##_members };
#define _MEMBER_FUNCTION_IMPL(classname,name) \
SQInteger __##classname##_##name(HSQUIRRELVM v) \
{ \
StackHandler sa(v);
#define _END_IMPL }
#define _INIT_STATIC_NAMESPACE(vm,classname) CreateStaticNamespace(vm,&__##classname##_decl);
#define _INIT_CLASS(vm,classname)CreateClass(vm,&__##classname##_decl);
#define _DECL_STATIC_NAMESPACE(xnamespace) extern struct ScriptNamespaceDecl __##xnamespace##_decl;
#define _DECL_CLASS(classname) extern struct SquirrelClassDecl __##classname##_decl;
#define _GetSelf(cppclass,scriptclass) \
cppclass *self = NULL; \
if (SQ_FAILED(sq_getinstanceup(v,1,(SQUserPointer*)&self,(SQUserPointer)&__##scriptclass##_decl))) \
return sq_throwerror(v,_SC("Invalid instance type"));\
if (!self)\
return sa.ThrowError("Internal failure");
#define _GetParamAt(cppclass,scriptclass,idx) \
cppclass *self = NULL; \
if (SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer*)&self,(SQUserPointer)&__##scriptclass##_decl))) \
return sq_throwerror(v,_SC("Invalid instance type")); \
if (!self) \
return sa.ThrowError("Internal failure");
#define _CHECK_INST_PARAM_RAW(pname,idx,cppclass,scriptclass) \
cppclass *pname = NULL; \
if (SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer*)&pname,(SQUserPointer)&__##scriptclass##_decl))) pname = NULL;
//------------------------------------------------------------------------------
#define _GetTypedParam(pname,idx,cppclass,scriptclass) \
cppclass *pname = NULL; \
if (SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer*)&pname,(SQUserPointer)&__##scriptclass##_decl))) \
return sq_throwerror(v,_SC("Invalid instance type"));
#define _CHECK_INST_PARAM_COBJECT(__PARAM__, __IDX__, __CPPCLASS__) \
__CPPCLASS__ *__PARAM__ = NULL; \
{ \
_GetTypedParam(c_object, __IDX__, GS::CObject, CObject) \
if (!c_object->c_object) \
return sq_throwerror(v, "C Object is null"); \
__PARAM__ = (__CPPCLASS__ *)c_object->c_object; \
}
#define _CHECK_INST_PARAM_BREAK(pname,idx,cppclass,scriptclass) \
cppclass *pname = NULL; \
if (SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer*)&pname,(SQUserPointer)&__##scriptclass##_decl))) \
break;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#define _CLASS_SCAG(classname) ((SQUserPointer)&__##classname##_decl)
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#define _DECL_NATIVE_CONSTRUCTION(classname,cppclass)\
bool push_##classname(HSQUIRRELVM v, const cppclass &quat);\
SquirrelObject new_##classname(HSQUIRRELVM v, const cppclass &quat);
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#define _IMPL_NATIVE_CONSTRUCTION(classname, cppclass)\
static SQInteger classname##_release_hook(SQUserPointer p, SQInteger size)\
{\
if (p)\
{\
cppclass *pv = (cppclass *)p;\
delete pv;\
}\
return 0;\
}\
bool push_##classname(HSQUIRRELVM vm, const cppclass &quat)\
{\
cppclass *newquat = new cppclass;\
*newquat = quat;\
if (!CreateNativeClassInstance(vm,#classname,newquat,classname##_release_hook))\
{\
delete newquat;\
return false;\
}\
return true;\
}\
::SquirrelObject new_##classname(HSQUIRRELVM vm, const cppclass &quat)\
{\
::SquirrelObject ret(vm);\
if (push_##classname(vm, quat))\
{\
ret.AttachToStackObject(-1);\
sq_pop(vm, 1);\
}\
return ret;\
}\
int construct_##classname(HSQUIRRELVM vm, cppclass *p)\
{\
sq_setinstanceup(vm, 1, p);\
sq_setreleasehook(vm, 1, classname##_release_hook);\
return 1;\
}
//------------------------------------------------------------------------------
bool CreateStaticClass(HSQUIRRELVM v, SquirrelClassDecl *cd);
bool CreateStaticNamespace(HSQUIRRELVM v, ScriptNamespaceDecl *sn);
bool CreateClass(HSQUIRRELVM v, SquirrelClassDecl *cd);
bool InitScriptClasses(HSQUIRRELVM v);
bool CreateNativeClassInstance(HSQUIRRELVM v, const SQChar *classname, SQUserPointer ud, SQRELEASEHOOK hook);
int refcounted_release_hook(SQUserPointer p, int size);
int construct_RefCounted(void *p);
//------------------------------------------------------------------------------
#define _SA_RETURN_OBJECT(__EXP__) { ::SquirrelObject o = __EXP__; return sa.Return(o); }
#define _ReturnCObject(__OBJECT__, __TYPE__) { GS::Script::CObject::Push(v, __OBJECT__, __TYPE__); return 1; }
//------------------------------------------------------------------------------
#endif // __CU_BINDING_UTILS__

View File

@ -0,0 +1,187 @@
#ifndef _SQUIRREL_OBJECT_H_
#define _SQUIRREL_OBJECT_H_
class SquirrelObject
{
// friend class SquirrelVM;
public:
SquirrelObject(HSQUIRRELVM vm);
virtual ~SquirrelObject();
SquirrelObject(const SquirrelObject &o);
SquirrelObject(HSQOBJECT &o);
SquirrelObject & operator =(const SquirrelObject &o);
SquirrelObject & operator =(int n);
void Append(const SquirrelObject &o);
void AttachToStackObject(int idx);
SquirrelObject Clone();
bool SetValue(const SquirrelObject &key,const SquirrelObject &val);
bool SetValue(SQInteger key,const SquirrelObject &val);
bool SetValue(int key,bool b);
bool SetValue(int key,int n);
bool SetValue(int key,float f);
bool SetValue(int key,const SQChar *s);
bool SetValue(const SQChar *key,const SquirrelObject &val);
bool SetValue(const SQChar *key,bool b);
bool SetValue(const SQChar *key,int n);
bool SetValue(const SQChar *key,float f);
bool SetValue(const SQChar *key,const SQChar *s);
bool SetInstanceUP(SQUserPointer up);
bool IsNull() const;
bool IsNumeric() const;
int Len() const;
bool SetDelegate(SquirrelObject &obj);
SquirrelObject GetDelegate();
const SQChar* ToString();
bool ToBool();
SQInteger ToInteger();
SQFloat ToFloat();
SQUserPointer GetInstanceUP(SQUserPointer tag) const;
SquirrelObject GetValue(const SQChar *key) const;
bool Exists(const SQChar *key) const;
float GetFloat(const SQChar *key) const;
int GetInt(const SQChar *key) const;
const SQChar *GetString(const SQChar *key) const;
bool GetBool(const SQChar *key) const;
SquirrelObject GetValue(int key) const;
float GetFloat(int key) const;
int GetInt(int key) const;
const SQChar *GetString(int key) const;
bool GetBool(int key) const;
SquirrelObject GetAttributes(const SQChar *key = 0);
SQObjectType GetType();
HSQOBJECT &GetObject(){return _o;}
bool BeginIteration();
bool Next(SquirrelObject &key,SquirrelObject &value);
void EndIteration();
private:
bool GetSlot(const SQChar *name) const;
bool GetSlot(int key) const;
HSQOBJECT _o;
HSQUIRRELVM vm;
};
struct StackHandler {
StackHandler(HSQUIRRELVM v) {
_top = sq_gettop(v);
this->v = v;
}
SQFloat GetFloat(int idx) {
SQFloat x = 0.0f;
if(idx > 0 && idx <= _top) {
sq_getfloat(v,idx,&x);
}
return x;
}
SQInteger GetInt(int idx) {
SQInteger x = 0;
if(idx > 0 && idx <= _top) {
sq_getinteger(v,idx,&x);
}
return x;
}
HSQOBJECT GetObject(int idx) {
HSQOBJECT x;
if(idx > 0 && idx <= _top) {
sq_resetobject(&x);
sq_getstackobj(v,idx,&x);
}
return x;
}
const SQChar *GetString(int idx)
{
const SQChar *x = 0;
if(idx > 0 && idx <= _top) {
sq_getstring(v,idx,&x);
}
return x;
}
SQUserPointer GetUserPointer(int idx)
{
SQUserPointer x = 0;
if(idx > 0 && idx <= _top) {
sq_getuserpointer(v,idx,&x);
}
return x;
}
SQUserPointer GetInstanceUp(int idx,SQUserPointer tag)
{
SQUserPointer self;
if(SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer*)&self,tag)))
return 0;
return self;
}
SQUserPointer GetUserdata(int idx,SQUserPointer tag)
{
SQUserPointer otag;
SQUserPointer up;
if(idx > 0 && idx <= _top) {
if(SQ_SUCCEEDED(sq_getuserdata(v,idx,&up,&otag))) {
if(tag == otag)
return up;
}
}
return 0;
}
bool GetBool(int idx)
{
SQBool ret;
if(idx > 0 && idx <= _top) {
if(SQ_SUCCEEDED(sq_getbool(v,idx,&ret)))
return ret ? true : false;
}
return false;
}
int GetType(int idx)
{
if(idx > 0 && idx <= _top) {
return sq_gettype(v,idx);
}
return -1;
}
SQInteger GetParamCount() {
return _top;
}
int Return(const SQChar *s)
{
sq_pushstring(v,s,-1);
return 1;
}
int Return(float f)
{
sq_pushfloat(v,f);
return 1;
}
int Return(int i)
{
sq_pushinteger(v,i);
return 1;
}
int Return(unsigned int i)
{
sq_pushinteger(v,i);
return 1;
}
int Return(bool b)
{
sq_pushbool(v,b);
return 1;
}
int Return(SquirrelObject &o)
{
sq_pushobject(v,o.GetObject());
return 1;
}
int Return() { return 0; }
SQInteger ThrowError(const SQChar *error) {
return sq_throwerror(v,error);
}
private:
SQInteger _top;
HSQUIRRELVM v;
};
#endif //_SQUIRREL_OBJECT_H_

View File

@ -0,0 +1,18 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __UC_BINDING__
#define __UC_BINDING__
#include "squirrel.h"
/// Register fast OO Squirrel binding.
void RegisterUCBinding(HSQUIRRELVM vm);
#endif // __UC_BINDING__

View File

@ -0,0 +1,19 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __COBJECT_UV_DECL__
#define __COBJECT_UV_DECL__
#include "script_squirrel/cobject/squirrel_bindings_utils.h"
#include "math/vector.h"
_DECL_CLASS(UV)
_DECL_NATIVE_CONSTRUCTION(UV, GS::Vector2)
#endif // __COBJECT_UV_DECL__

View File

@ -0,0 +1,20 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __COBJECT_VECTOR_DECL__
#define __COBJECT_VECTOR_DECL__
#include "script_squirrel/cobject/squirrel_bindings_utils.h"
namespace GS { struct Vector4; }
_DECL_CLASS(Vector)
_DECL_NATIVE_CONSTRUCTION(Vector, GS::Vector4)
#endif // __COBJECT_VECTOR_DECL__

View File

@ -0,0 +1,41 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NENGINEVM__
#define __NENGINEVM__
#include "script_squirrel/squirrel_vm.h"
namespace GS {
namespace Script {
class CObject;
/*
@short Squirrel based virtual machine.
*/
struct EngineVM : public SquirrelVM
{
List <CObject *> cobjects;
/// Release all native references.
void ReleaseAllNativeReferences();
/// Push a variant onto the Squirrel stack.
virtual bool PushVariant(const Variant &);
/// Invalidate all references to a user object.
virtual int InvalidateNativeReference(void *);
virtual bool Open();
virtual void Close();
};
} // Script
} // GS
#endif // __NENGINEVM__

View File

@ -0,0 +1,31 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __ENGINE_VM_DEBUGGER__
#define __ENGINE_VM_DEBUGGER__
#include "script_squirrel/squirrel_debugger.h"
namespace GS {
namespace Script {
struct EngineVM;
/*
@short Editor Squirrel debugger interface.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
struct EngineDebugger : public SquirrelDebugger
{
EngineDebugger(EngineVM &);
};
} // Script
} // GS
#endif // __ENGINE_VM_DEBUGGER__

View File

@ -0,0 +1,35 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __MONITOR_SCRIPT_PROFILER__
#define __MONITOR_SCRIPT_PROFILER__
#include "script/script_profiler.h"
#include "script/script_vm.h"
#include "squirrel.h"
namespace GS {
namespace Script {
/*
@short Engine VM profiler interface.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
struct EngineProfiler : public Profiler
{
/// Get function profile.
FunctionProfile *GetFunctionProfile(const char *source, const char *function, int line, FunctionProfile *profile) { return 0; }
/// Update profiler.
void Update(int type, FunctionProfile *profile) {}
};
} // Script
} // GS
#endif // __MONITOR_SCRIPT_PROFILER__

View File

@ -0,0 +1,201 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NBINDING_HELPERS__
#define __NBINDING_HELPERS__
#include "script_squirrel/cobject/uc_binding.h"
#include "script_squirrel/cobject/cobject.h"
#include "script_squirrel/cobject/vector_decl.h"
#include "math/vector.h"
#include "log/log.h"
namespace GS {
class MinMax;
struct Color;
struct Vector4;
template <class T> struct Rect;
namespace Script {
/// Register a native closure in the vm.
void sq_register(HSQUIRRELVM v, SQFUNCTION f, const char *fname, const SQChar *mask);
/// Create a new class instance on the vm stack.
bool CreateClassInstance(HSQUIRRELVM vm, const char *class_name, bool call = false);
void PushColor(HSQUIRRELVM vm, const Color &c);
void PushVector2(HSQUIRRELVM vm, const Vector2 &v);
void GetVector2(HSQUIRRELVM vm, SQInteger idx, Vector2 &v);
void PushVector(HSQUIRRELVM vm, const Vector4 &v, bool push_w = false);
void GetVector(HSQUIRRELVM vm, SQInteger idx, Vector4 &v, bool get_w = false);
void GetUV(HSQUIRRELVM vm, SQInteger idx, Vector2 &uv);
void PushMinMax(HSQUIRRELVM vm, const MinMax &v);
void GetMinMax(HSQUIRRELVM vm, SQInteger idx, MinMax &v);
void PushRect(HSQUIRRELVM vm, const Rect <float> &r);
void GetRect(HSQUIRRELVM vm, SQInteger idx, Rect <float> &r);
void PushRect(HSQUIRRELVM vm, const Rect <int> &r);
void GetRect(HSQUIRRELVM vm, SQInteger idx, Rect <int> &r);
#define GetTableKey(_KEY_, _TYPE_GET_, _IDX_, _TO_)\
{\
sq_pushstring(vm, _KEY_, -1);\
sq_get(vm, (_IDX_) - 1);\
_TYPE_GET_(vm, -1, &_TO_);\
sq_pop(vm, 1);\
}
#define SetTableKey(_KEY_, _TYPE_PUSH_, _IDX_, _V_)\
{\
sq_pushstring(vm, _KEY_, -1);\
_TYPE_PUSH_(vm, _V_);\
sq_set(vm, (_IDX_) - 2);\
}
//------------------------------------------------------------------------------
#define __SQ_INVALIDATENATIVEREF(__PTR__) ((SquirrelVM *)sq_getforeignptr(vm))->InvalidateNativeReference(__PTR__);
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#define __SQ_GETSTART(__ARGCOUNT__) \
int __sq_stackpos = -(__ARGCOUNT__), __sq_argcount = __ARGCOUNT__;
#define __SQ_GETUPDATESTACK \
__sq_stackpos++;
#define __SQ_GETEND \
sq_pop(vm, __sq_argcount);
/*
sq_pop(vm, __sq_argcount);\
if (sq_gettop(vm) != 1)\
return sq_throwerror(vm, "Internal binding error, stack configuration is invalid");
*/
#define __SQ_STACKPOS __sq_stackpos
#define __SQ_GETSAFEPTR(__VARNAME__, __TYPE__, __TAG__) \
__TYPE__ *__VARNAME__; if (!GS::Script::CObject::Get(vm, __sq_stackpos, (void **)&__VARNAME__, __TAG__)) return -1; if (!__VARNAME__) return sq_throwerror(vm, "Object is null"); __SQ_GETUPDATESTACK
#define __SQ_GETSAFEPTRALLOWNULL(__VARNAME__, __TYPE__, __TAG__) \
__TYPE__ *__VARNAME__; if (!GS::Script::CObject::Get(vm, __sq_stackpos, (void **)&__VARNAME__, __TAG__)) return -1; __SQ_GETUPDATESTACK
#define __SQ_GETCOBJECTBASE(__VARNAME__, __TYPE__, __TAGS__) \
__TYPE__ *__VARNAME__; if (!GS::Script::CObject::GetBase(vm, __sq_stackpos, (void **)&__VARNAME__, __TAGS__)) return -1; if (!__VARNAME__) return sq_throwerror(vm, "Object is null"); __SQ_GETUPDATESTACK
#define __SQ_GETCOBJECTBASEALLOWNULL(__VARNAME__, __TYPE__, __TAGS__) \
__TYPE__ *__VARNAME__; if (!GS::Script::CObject::GetBase(vm, __sq_stackpos, (void **)&__VARNAME__, __TAGS__)) return -1; __SQ_GETUPDATESTACK
#define __SQ_GETOBJECT(__VARNAME__) \
HSQOBJECT __VARNAME__; sq_getstackobj(vm, __sq_stackpos, &__VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETINT(__VARNAME__) \
SQInteger __VARNAME__; sq_getinteger(vm, __sq_stackpos, &__VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETFLOAT(__VARNAME__) \
SQFloat __VARNAME__; sq_getfloat(vm, __sq_stackpos, &__VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETBOOL(__VARNAME__) \
SQBool __VARNAME__; sq_getbool(vm, __sq_stackpos, &__VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETSTRING(__VARNAME__) \
const SQChar *__VARNAME__; sq_getstring(vm, __sq_stackpos, &__VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETCOLOR(__VARNAME__) \
GS::Color __VARNAME__; GetVector(vm, __sq_stackpos, __VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETVECTOR2(__VARNAME__) \
GS::Vector2 __VARNAME__; GetVector2(vm, __sq_stackpos, __VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETVECTORTO(__VECTOR__, __CONDITION__) \
if (__CONDITION__) GetVector(vm, __sq_stackpos, __VECTOR__); __SQ_GETUPDATESTACK
#define __SQ_GETVECTORTOALWAYS(__VECTOR__) \
GetVector(vm, __sq_stackpos, __VECTOR__); __SQ_GETUPDATESTACK
#define __SQ_GETUVTO(__UV__) \
GetUV(vm, __sq_stackpos, __UV__); __SQ_GETUPDATESTACK
#define __SQ_GETRECT(__VARNAME__) \
GS::Rect <int> __VARNAME__; GetRect(vm, __sq_stackpos, __VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETFRECT(__VARNAME__) \
GS::Rect <float> __VARNAME__; GetRect(vm, __sq_stackpos, __VARNAME__); __SQ_GETUPDATESTACK
#define __SQ_GETRECTTO(__RECT__) \
GetRect(vm, __sq_stackpos, __RECT__); __SQ_GETUPDATESTACK
#define __SQ_GETSINGLE(__G) \
__SQ_GETSTART(1) __G __SQ_GETEND
#define __SQ_RETURNSAFEPTR(Val, Tag) { GS::Script::CObject::Push(vm, Val, Tag); return 1; }
#define __SQ_RETURNMANAGEDSAFEPTR(Val, Tag) { GS::Script::CObject::Push(vm, Val, Tag, true); return 1; }
#define __SQ_RETURNMINMAX(Val) { PushMinMax(vm, Val); return 1; }
#define __SQ_RETURNRECT(Val) { PushRect(vm, Val); return 1; }
#define __SQ_RETURNCOLOR(Val) { PushColor(vm, Val); return 1; }
#define __SQ_RETURNVECTOR2(Val) { PushVector2(vm, Val); return 1; }
#define __SQ_RETURNVECTORW(Val) { PushVector(vm, Val, true); return 1; }
#define __SQ_RETURNMINMAX(Val) { PushMinMax(vm, Val); return 1; }
//------------------------------------------------------------------------------
// Wrap old accessors to the much faster OO ones.
#ifndef _T
#define _T
#endif
#define __SQ_GETMATRIX3(__VARNAME__) \
GS::Matrix3 __VARNAME__;\
{ HSQUIRRELVM v = vm;\
_GetTypedParam(__mtx, __sq_stackpos, GS::Matrix3, Matrix3);\
__VARNAME__ = *__mtx;\
__SQ_GETUPDATESTACK }
#define __SQ_GETMATRIX4(__VARNAME__) \
GS::Matrix4 __VARNAME__;\
{ HSQUIRRELVM v = vm;\
_GetTypedParam(__mtx, __sq_stackpos, GS::Matrix4, Matrix4);\
__VARNAME__ = *__mtx;\
__SQ_GETUPDATESTACK }
#define __SQ_RETURNMATRIX3(__V__) \
{ StackHandler sa(vm);\
_SA_RETURN_OBJECT(new_Matrix3(vm, __V__)) }
#define __SQ_RETURNMATRIX4(__V__) \
{ StackHandler sa(vm);\
_SA_RETURN_OBJECT(new_Matrix4(vm, __V__)) }
#define __SQ_GETVECTORW(__VARNAME__) \
GS::Vector4 __VARNAME__;\
{ HSQUIRRELVM v = vm;\
_GetTypedParam(__vec, __sq_stackpos, GS::Vector4, Vector);\
__VARNAME__ = *__vec;\
__SQ_GETUPDATESTACK }
#define __SQ_GETVECTOR(__VARNAME__) \
__SQ_GETVECTORW(__VARNAME__) \
__VARNAME__.w = 1;
#define __SQ_RETURNVECTOR(Val) \
{ StackHandler sa(vm);\
_SA_RETURN_OBJECT(new_Vector(vm, Val)) }
//------------------------------------------------------------------------------
#define __SQ_RETURNINT(Val) { sq_pushinteger(vm, Val); return 1; }
#define __SQ_RETURNFLOAT(Val) { sq_pushfloat(vm, Val); return 1; }
#define __SQ_RETURNBOOL(Val) { sq_pushbool(vm, Val ? SQTrue : SQFalse); return 1; }
#define __SQ_RETURNNULL { sq_pushnull(vm); return 1; }
#define __SQ_RETURNSTRING(Val) { sq_pushstring(vm, Val, -1); return 1; }
#define __SQ_RETURNOBJECT(Val) { sq_pushobject(vm, Val); return 1; }
#define __SQ_RETURN return 0;
#define __SQ_GETSINGLESAFEPTR(Name, Type, Tag) \
__SQ_GETSTART(1) \
__SQ_GETSAFEPTR(Name, Type, Tag) \
__SQ_GETEND
#define __SQ_GETSINGLESAFEPTRALLOWNULL(Name, Type, Tag) \
__SQ_GETSTART(1) \
__SQ_GETSAFEPTRALLOWNULL(Name, Type, Tag) \
__SQ_GETEND
//------------------------------------------------------------------------------
} // Script
} // GS
#endif // __NBINDING_HELPERS__

View File

@ -0,0 +1,63 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NMANAGER_SCRIPT_BINDING__
#define __NMANAGER_SCRIPT_BINDING__
/// Squirrel API compatible version.
#define __SQUIRREL_API_VERSION_COMPATIBILITY__ 1
/// Current Squirrel API version.
#define __SQUIRREL_API_VERSION__ 2
typedef struct SQVM* HSQUIRRELVM;
void RegisterAIBinding(HSQUIRRELVM);
void RegisterAnimationBinding(HSQUIRRELVM);
void RegisterCameraBinding(HSQUIRRELVM);
void RegisterClockBinding(HSQUIRRELVM);
void RegisterCollisionBinding(HSQUIRRELVM);
void RegisterEmitterBinding(HSQUIRRELVM);
void RegisterGeometryBinding(HSQUIRRELVM);
void RegisterFontBinding(HSQUIRRELVM);
void RegisterGroupBinding(HSQUIRRELVM);
void RegisterHashBinding(HSQUIRRELVM);
void RegisterHTTPBinding(HSQUIRRELVM);
void RegisterWebSocketBinding(HSQUIRRELVM);
void RegisterInstanceBinding(HSQUIRRELVM);
void RegisterIOBinding(HSQUIRRELVM);
void RegisterItemBinding(HSQUIRRELVM);
void RegisterLightBinding(HSQUIRRELVM);
void RegisterProfilerBinding(HSQUIRRELVM);
void RegisterMaterialBinding(HSQUIRRELVM);
void RegisterMatrixBinding(HSQUIRRELVM);
void RegisterMixerBinding(HSQUIRRELVM);
void RegisterMotionBinding(HSQUIRRELVM);
void RegisterNMLBinding(HSQUIRRELVM);
void RegisterObjectBinding(HSQUIRRELVM);
void RegisterPhysicBinding(HSQUIRRELVM);
void RegisterPictureBinding(HSQUIRRELVM);
void RegisterProjectBinding(HSQUIRRELVM);
void RegisterRaytracerBinding(HSQUIRRELVM);
void RegisterRendererBinding(HSQUIRRELVM);
void RegisterResourceFactoryBinding(HSQUIRRELVM);
void RegisterSceneBinding(HSQUIRRELVM);
void RegisterSoundBinding(HSQUIRRELVM);
void RegisterSystemBinding(HSQUIRRELVM);
void RegisterTextureBinding(HSQUIRRELVM);
void RegisterTriggerBinding(HSQUIRRELVM);
void RegisterUIBinding(HSQUIRRELVM);
void RegisterPlatformBinding(HSQUIRRELVM);
void RegisterMaterialShaderBinding(HSQUIRRELVM);
void RegisterAllSquirrelBinding(HSQUIRRELVM);
#define GetVMObject(__VM__) ((GS::Script::SquirrelVM *)sq_getforeignptr(__VM__))
#endif // __NMANAGER_SCRIPT_BINDING__

View File

@ -0,0 +1,118 @@
#ifndef WS_MANAGER_H
#define WS_MANAGER_H
// Must be defined before including any Windows headers
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <queue>
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0601 // Windows 7 or later
#endif
// Winsock and Bluetooth headers
#include <winsock2.h>
#include <ws2bth.h>
#include <bluetoothapis.h>
#include <thread>
#include <mutex>
#include <chrono>
#include <vector>
#include <atomic>
#include <squirrel.h>
// Link required libraries
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Bthprops.lib")
#ifndef BT_PORT_ANY
#define BT_PORT_ANY ((ULONG)-1)
#endif
#ifndef BTH_ADDR_NULL
#define BTH_ADDR_NULL ((BTH_ADDR)0)
#endif
class WebSocketManager {
public:
struct CallbackEvent {
enum Type { CONNECT, DISCONNECT, MESSAGE };
Type type;
std::string data;
SOCKET client_socket;
};
struct ClientConnection {
SOCKET socket;
std::thread receive_thread;
std::atomic<bool> active;
ClientConnection(SOCKET s) : socket(s), active(true) {}
};
private:
SOCKET m_listen_socket;
std::vector<ClientConnection*> m_connections;
mutable std::mutex m_connections_mutex;
std::thread m_accept_thread;
std::atomic<bool> m_running;
bool m_initialized;
std::chrono::steady_clock::time_point m_start_time;
uint16_t m_port;
// Squirrel VM and callbacks
HSQUIRRELVM m_vm;
HSQOBJECT m_on_connect_callback;
HSQOBJECT m_on_disconnect_callback;
HSQOBJECT m_on_message_callback;
bool m_has_on_connect;
bool m_has_on_disconnect;
bool m_has_on_message;
// Event queue - car la VM Squirrel n'est pas thread-safe
// Les callbacks doivent être appelés depuis le thread principal
std::queue<CallbackEvent> m_event_queue;
mutable std::mutex m_queue_mutex;
void InternalOnConnect(SOCKET client_socket);
void InternalOnDisconnect(SOCKET client_socket);
void InternalOnMessage(SOCKET client_socket, const std::string& message);
void InitializeServer();
void AcceptLoop();
void ReceiveLoop(ClientConnection* connection);
bool SendToClient(SOCKET client_socket, const std::string& message);
public:
WebSocketManager(HSQUIRRELVM vm);
~WebSocketManager();
// Server control
bool Start(uint16_t port);
void Stop();
bool IsRunning() const { return m_running; }
// Messaging
void Broadcast(const std::string& message);
// Statistics
int GetConnectionCount() const;
float GetUptime() const;
uint16_t GetPort() const { return m_port; }
// Squirrel callbacks
void SetOnConnectCallback(HSQOBJECT callback);
void SetOnDisconnectCallback(HSQOBJECT callback);
void SetOnMessageCallback(HSQOBJECT callback);
// Process events - DOIT être appelé depuis le thread principal !
// C'est ici que les callbacks Squirrel sont réellement invoqués
void ProcessEvents();
};
#endif // WS_MANAGER_H

View File

@ -0,0 +1,44 @@
/*
Tau [Physic engine]
Emmanuel Julien 2004~2005.
http://xbarr.ninomojo.com
mailto:ejulien@nengine.fr
------------------------------------------
*/
#ifndef __MMF_SYSTEM__
#define __MMF_SYSTEM__
#include <TCHAR.H>
#include <windows.H>
/**
*/
class CMMF
{
public:
CMMF(LPCTSTR MMFName, int size, LPCTSTR mutexName);
~CMMF();
void Read(void* pData, bool read = true);
void Write(void* pData);
LPVOID GetMMF() { return m_pSharedData; }
protected:
LPVOID m_pSharedData;
private:
CMMF() {}
int m_nSize;
HANDLE m_hFileMapping;
HANDLE m_hMutex;
};
#endif // __MMF_SYSTEM__

View File

@ -0,0 +1,104 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NSQUIRRELANALYZER__
#define __NSQUIRRELANALYZER__
#include "memory/nshared_ptr.h"
#include "memory/nweak_ptr.h"
#include "container/nlist.h"
#include "nstring/nstring.h"
namespace GS {
namespace SquirrelAnalyzer {
struct Offset
{
int line, column;
Offset(int l = 0, int c = 0) : line(l), column(c) {}
};
struct Symbol : public SharedObject
{
enum Type
{
TypeNone,
TypeVariable,
TypeFunction,
TypeClass
};
String name;
Type type;
Offset offset;
Symbol() : type(TypeNone) {}
};
struct Variable : public Symbol
{
enum VarType
{
VarNone,
VarLocal,
VarGlobal,
VarMember,
VarEnum
};
VarType var_type;
Variable() : var_type(VarNone) { type = TypeVariable; }
};
struct Function : public Symbol
{
SharedList <Symbol *> symbols;
String prototype;
Function() { type = TypeFunction; }
};
struct Class : public Symbol
{
String extends;
SharedList <Symbol *> symbols;
Class() { type = TypeClass; }
};
struct Source
{
String name;
SharedList <Symbol *> symbols;
};
struct SourceSymbol
{
SharedPtr <Source> source;
SharedPtr <Symbol> symbol;
};
struct Program
{
AutoList <Source *> sources;
bool FindSymbol(const char *name, AutoList <SourceSymbol *> &symbols);
};
void DumpProgram(const Program &);
/// Analyze a source, store result in program object.
Source *Analyze(const char *nut, Program &, bool replace = true);
} // SquirrelAnalyser
} // GS
#endif // __NSQUIRRELANALYZER__

View File

@ -0,0 +1,63 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __SQUIRREL_DEBUGGER__
#define __SQUIRREL_DEBUGGER__
#include "script/script_debugger.h"
#include "squirrel.h"
namespace GS {
namespace Script {
class SquirrelVM;
/*
@short Squirrel debugger interface.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class SquirrelDebugger : public IDebugger
{
protected:
HSQUIRRELVM vm;
/// Insert a variable in the variable tree.
DebuggerVariable *InsertVariable(const char *name, AutoList <DebuggerVariable *> &tree, int level);
public:
/*!
@name Interface.
@{
*/
/// Format variable parameter.
virtual String FormatParameter(DebuggerVariable *variable);
/// Format safe ptr parameter.
virtual String FormatUserObjectParameter(CObjectType type);
/// Convert a debugger variable to a meta string.
virtual void VariableToMetatagString(DebuggerVariable *, String &);
/// Get call stack depth.
virtual int GetCallstackDepth();
/// Get current script execution call frame index.
virtual int GetStackFrameIndex();
/// Refresh stack locals list.
virtual void RefreshStackFrameLocalsCache();
/// Get source/line info for the current debug stack frame.
virtual void GetStackFrameSource(const char *&, int &);
/// @}
SquirrelDebugger(SquirrelVM &);
};
} // Script
} // GS
#endif // __SQUIRREL_DEBUGGER__

View File

@ -0,0 +1,116 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NSQUIRRELVM__
#define __NSQUIRRELVM__
#include "squirrel.h"
#include "script/script_vm.h"
#include "script/script_object.h"
namespace GS {
namespace Script {
class SquirrelVM;
//
struct SquirrelObject : public Object
{
HSQOBJECT object;
SquirrelObject(SquirrelVM &, HSQOBJECT);
~SquirrelObject();
};
/*
@short Squirrel based virtual machine.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class SquirrelVM : public IVM
{
protected:
HSQUIRRELVM vm;
int call_arg_count;
public:
/// Get VM name.
const char *GetName() const { return "Squirrel"; }
/// Get VM call stack.
void GetCallStack(AutoList <CallStackEntry *> &);
/*!
@name Squirrel specific API.
@{
*/
HSQUIRRELVM VM() const { return vm; }
/// Set event hook table.
virtual void SetDebugInterface(IDebug *, bool enable_step_hook = false);
/// Dump VM call stack.
static void DumpCallStack(HSQUIRRELVM, const char *desc, String *msg = 0);
/// Push null value onto the stack.
virtual bool PushNull();
/// Push property onto the stack.
virtual bool PushVariant(const Variant &);
/// Get Squirrel value from stack.
virtual bool GetVariantFromStack(int stack_index, Variant &);
/// Get a reference to a stack object.
Object *GetObjectFromStack(int stack_index);
/// @}
/// Get a reference to a VM object.
virtual Object *GetObjectFromName(const char *name, const Object *context = 0);
/// Setup a function call in the VM.
virtual bool SetupFunctionCall(const char *func, const Object *function_object = 0, const Object *search_context = 0);
/// Set function call context.
virtual bool SetFunctionCallContext(const Variant &);
/// Push function call null argument.
virtual bool PushNullArgument();
/// Push function call argument.
virtual bool PushArgument(const Variant &);
/// Execute a function call in the VM.
virtual bool DoFunctionCall(Variant *return_value = 0);
/// Invalidate all references to a user object.
virtual int InvalidateNativeReference(void *) { return 0; }
/// Compile a script.
virtual bool Compile(const char *source, uint size, const Object *context = 0, const char *sourcename = 0);
/// Create a table object.
virtual Object *CreateTable();
/// Set a VM variable.
virtual bool Set(const char *name, const Variant &, const Object *context = 0);
/// Get a VM variable.
virtual bool Get(const char *name, Variant &, const Object *context = 0);
/// Create a script array.
virtual Object *CreateArray();
/// Append a VM variable to an array.
virtual bool Append(const Variant &, const Object *context = 0);
/// Is the VM open.
virtual bool IsOpen() const { return asbool(vm); }
virtual bool Open();
virtual void Close();
SquirrelVM();
virtual ~SquirrelVM();
};
} // Script
} // GS
#endif // __NSQUIRRELVM__

View File

@ -0,0 +1,24 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NGEOMETRYMERGETOOL__
#define __NGEOMETRYMERGETOOL__
namespace GS {
class Matrix4;
namespace Core {
class Geometry;
/// Merge two geometries together.
Geometry *MergeGeometry(Geometry *, Geometry *, const Matrix4 * = 0, const Matrix4 * = 0);
} // Core
} // GS
#endif // __NGEOMETRYMERGETOOL__

View File

@ -0,0 +1,93 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __RESOURCEEXPLORER__
#define __RESOURCEEXPLORER__
#include "nstring/nstring.h"
#include "container/nlist.h"
#include "memory/nauto_ptr.h"
#include "metafile/nml.h"
namespace GS {
namespace Resource {
//------------------------------------------------------------------------------
struct DependencyRule
{
const char *path;
const char *type;
};
struct ExplorerRule
{
const char *type, *root;
DependencyRule *rules;
};
//------------------------------------------------------------------------------
//
struct Explorer
{
struct Dependency
{
bool missing;
virtual const char *GetName() const = 0;
virtual void SetName(const char *) = 0;
Dependency() : missing(true) {}
virtual ~Dependency() {}
};
struct DependencyTag : public Dependency
{
NML::Tag *tag;
virtual const char *GetName() const;
virtual void SetName(const char *);
DependencyTag(NML::Tag *t) : tag(t) {}
};
struct Resource
{
String name, type;
AutoPtr <NML::File> file;
AutoList <Dependency *> dependencies;
const Dependency *FindDependency(const char *) const;
bool HasMissingDependencies() const;
Resource(const char *n, const char *t) : name(n), type(t) {}
};
private:
String project_path, core_path;
bool recursive;
AutoList <Resource *> resources;
void ExploreResourceRuleTags(const StringList &, uint pos, NML::Tag *, Resource *, int depth);
bool ExploreResourceRule(ExplorerRule &, Resource *, int depth);
public:
void Clear();
const AutoList <Resource *> &GetResources() const { return resources; }
const Resource *FindResource(const char *) const;
// Explore dependencies for a given resource.
Resource *ExploreResource(const char *name, const char *base_path, const char *core_path, int max_depth = 128);
};
} // Resource
} // GS
#endif // __RESOURCEEXPLORER__

View File

@ -0,0 +1,30 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __MERGEOBJECTLIST__
#define __MERGEOBJECTLIST__
#include "scene3d/mitem.h"
#include "core/geometry.h"
namespace GS {
namespace Core { struct ResourceFactory; }
namespace S3D {
class Scene;
struct SceneMergeObjectList
{
virtual bool OnProgress(int current, int total) { return true; }
bool Merge(Scene *, const SharedList <MItem *> &, Core::ResourceFactory &, sMItem &out_i, Core::sGeometry &out_g);
};
} // S3D
} // GS
#endif // __MERGEOBJECTLIST__

View File

@ -0,0 +1,222 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __VIEWERBASE__
#define __VIEWERBASE__
#include "viewer_base/viewer_base_vmhook.h"
#include "gpu/gpu_triangle_batch.h"
#include "project/project.h"
#include "scene3d/scene.h"
#include "ui/ui.h"
#include "core/mixer.h"
#include "core/renderer.h"
#include "core/resource_factories.h"
#include "core/graphic_resource_factory.h"
#include "core/render_resource_factory.h"
#include "core/mixer_resource_factory.h"
#include "debug_enet/network_debugger.h"
#include "io_net/io_net_client.h"
#include "timing/loop_benchmark.h"
#include "container/nstack.h"
namespace GS {
/*
@short Engine viewer base class.
Derive from this class and implement the pure virtual functions to create
a platform specific viewer.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class ViewerBase
{
String GetBaseCommandLineParm() const;
public:
enum SessionType
{
SessionScene = 0,
SessionProject
};
enum SessionSource
{
SessionSourceFilesystem = 0,
SessionSourceArchive,
SessionSourceArchiveBootstrap
};
enum State
{
ViewerSetup = 0,
ViewerClose,
WaitRemoteSetup,
WaitRemoteController,
SessionSetup,
SessionRunning,
SessionClose,
};
State state;
protected:
bool paused;
bool missing_resource;
LoopBenchmark fps;
AutoPtr <GPU::TriangleBatch> gpu_batch;
virtual bool OpenVideo() = 0;
virtual bool OpenAudio() = 0;
bool LoadSessionData();
List <Variant *> define_list;
StringList include_list;
/// Platform specific update.
virtual bool PlatformUpdate() = 0;
/// Called when a command line parameter is unknown to the base command line parser.
virtual bool OnUnknownCommandLineParam(Stack <String> &_arg, int &n) { return false; }
/// Print additional usage.
virtual void PrintAdditionalUsage() {}
virtual bool OpenScriptVM();
void SetVMGlobals();
bool OpenSession();
virtual void ExecuteSession();
bool CheckRuntimeError();
void CloseSession();
void ExecuteMonitor();
virtual Script::NetworkDebugger *CreateVMDebugInterface();
public:
void PrintHeader();
void PrintUsage();
enum MessageType
{
MessageNormal = 0,
MessageWarning,
MessageError
};
/// Platform specific display message to the user.
virtual void DisplayUserMessage(MessageType, const char *) = 0;
/// Instantiate the renderer object.
virtual bool CreateRenderer() = 0;
/// Instantiate the mixer object.
virtual bool CreateMixer() = 0;
bool SetupSessionSource();
NML::File config_file;
SessionSource session_source;
SessionType session_type;
String s_render, s_mixer;
String mixer_output;
String session_source_path;
String input_path;
String config_path;
String raytrace_path;
String bootstrap_script;
int raytrace_width,
raytrace_height,
raytrace_aa;
int time_start,
time_live;
int frame_count;
bool ignore_esc,
ignore_bootstrap,
ignore_missing_resource;
bool enable_profiler,
memory_profiler,
enable_pause,
display_fps;
bool active_debug;
//---------------------------------------------------------------------
bool remote;
int remote_port;
SharedPtr <IO::Base> remote_fs;
NML::File remote_project,
remote_scene;
//---------------------------------------------------------------------
bool tool_mode;
bool safe_mode;
bool fullscreen;
int width, height;
float aspect_ratio;
Script::sVM script_vm;
Script::NetworkDebugger *script_debugger;
Core::sResourceFactories factories;
AutoPtr <Render::Renderer> renderer;
AutoPtr <Audio::IMixer> mixer;
AutoPtr <Core::Project> project;
AutoPtr <S2D::Scene> scene_2d;
AutoPtr <S3D::Scene> scene_3d;
Render::RasterFont *profiler_font[2], *fps_font;
/*!
@name Viewer API
@{
*/
/// Application has been sent to background.
void Suspend();
/// Application returned to foreground.
void Resume();
bool ParseCommandLine(Stack <String> &_arg);
bool LoadViewerConfig(const char *path);
bool LocateAndParseBootstrap(Stack <String> &_arg);
void SetupVersion(const char *);
virtual bool OpenViewer();
virtual State Execute();
virtual void CloseViewer();
/// @}
ViewerBase();
virtual ~ViewerBase() { CloseViewer(); }
};
} // GS
#endif // __VIEWERBASE__

View File

@ -0,0 +1,42 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __VIEWERBASEMONITOREVENTHANDLER__
#define __VIEWERBASEMONITOREVENTHANDLER__
#include "debug_enet/network_debugger.h"
namespace GS {
class ViewerBase;
namespace Script {
/*!
@short Viewer base debugger VM event handler.
This event handler augments the network debugger to include the viewer
protocol commands.
@author Emmanuel Julien (ejulien@owloh.com)
*/
struct ViewerBaseDebugger : public NetworkDebugger
{
ViewerBase &viewer;
// Viewer base debugger interface.
virtual void SetViewerStatus(const char *);
virtual IO::Base *WrapRemoteFileSystem(IO::Base *remote_fs);
// Network debugger interface.
void OnControllerPacketReceived(const Array <char> &);
ViewerBaseDebugger(ViewerBase &, IDebugger *, const char *address, int port);
};
} // Script
} // GS
#endif // __VIEWERBASEMONITOREVENTHANDLER__

View File

@ -0,0 +1,42 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NMSVIEW_VMHOOK__
#define __NMSVIEW_VMHOOK__
#include "script/script_vm.h"
namespace GS {
class ViewerBase;
namespace Script {
//
class ViewerEventHookTable : public IVM::IDebug
{
ViewerBase *viewer;
public:
/// Handle a runtime debug step.
virtual void OnStep(char type, const char *source, int line, const char *funcname);
/// Handle a VM kill event.
virtual void Kill(const char *reason);
/// Handle a compiler error.
virtual void OnCompilerError(const char *error, const char *source, int line);
/// Handle a runtime error.
virtual void OnRuntimeException(const char *error);
ViewerEventHookTable(ViewerBase *v) : viewer(v) {}
};
} // Script
} // GS
#endif // __NMSVIEW_VMHOOK__