diff --git a/Makefile b/Makefile index 7ba3ff6..b1c7cae 100644 --- a/Makefile +++ b/Makefile @@ -42,14 +42,12 @@ SERVER_OBJS := \ CLIENT_OBJS := \ $(OBJDIR)/src/camera.o \ $(OBJDIR)/src/client_main.o \ - $(OBJDIR)/src/Client.o \ $(OBJDIR)/src/cube.o \ $(OBJDIR)/src/FileIO.o \ $(OBJDIR)/src/lib_GL_common.o \ $(OBJDIR)/src/object.o \ $(OBJDIR)/src/quad.o \ $(OBJDIR)/src/shader.o \ - $(OBJDIR)/src/UDP_Write.o \ $(COMMON_OBJS) IMGUI_OBJS := $(patsubst %,$(OBJDIR)/%.o,$(basename $(IMGUI_SRCS))) @@ -59,7 +57,7 @@ TEST_OBJ_COMMON := \ $(COMMON_OBJS) -TESTS := test_FileIO test_File_Write_UDP test_Object test_lua +TESTS := test_FileIO test_Object test_lua TEST_PROGS := $(addprefix $(TESTDIR)/,$(TESTS)) # {{{ Flags @@ -150,16 +148,16 @@ test: $(TEST_PROGS) test/test_FileIO: $(TEST_OBJ_COMMON) $(OBJDIR)/src/util.o -test/test_File_Write_UDP: $(TEST_OBJ_COMMON) $(OBJDIR)/src/UDP_Write.o $(OBJDIR)/src/Client.o - test/test_Object: $(TEST_OBJ_COMMON) $(OBJDIR)/src/object.o $(OBJDIR)/src/quad.o $(OBJDIR)/src/cube.o $(OBJDIR)/src/lib_GL_common.o test/test_lua: $(TEST_OBJ_COMMON) $(OBJDIR)/src/lib_lua_common.o -test/test_Client: $(TEST_OBJ_COMMON) $(OBJDIR)/src/UDP_Write.o $(OBJDIR)/src/Client.o +test/client: $(TEST_OBJ_COMMON) $(OBJDIR)/src/UDPbase.o $(OBJDIR)/src/lib_SDL_common.o test/test_UDP_DumpPacket: $(TEST_OBJ_COMMON) $(OBJDIR)/src/util.o +test/server: $(TEST_OBJ_COMMON) + $(OBJDIR)/%.o: %.c $(OBJDIR)/%.o: %.c $(DEPDIR)/%.d $(PRECOMPILE) diff --git a/glsl/camera.v.glsl b/glsl/camera.v.glsl new file mode 100644 index 0000000..c76ebfd --- /dev/null +++ b/glsl/camera.v.glsl @@ -0,0 +1,17 @@ +/* vim: set ft=c: */ + +#version 440 core + +layout(location = 0) in vec3 aPos; +layout(location = 1) in vec2 aTexCoord; + +out vec2 iTexCoord; + +uniform mat4 Model; +uniform mat4 View; +uniform mat4 Projection; + +void main(void) { + gl_Position = Projection * View * Model * vec4(aPos, 1.0f); + iTexCoord = aTexCoord; +} diff --git a/include/Client.h b/include/Client.h deleted file mode 100644 index be95d91..0000000 --- a/include/Client.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include "debug.h" - -#include -#include - -#include - -class Client -{ - std::string mHost; - Uint16 mPort; - int mChannel; - std::vector UDPsocks; - public: - Client (void) - { - DEBUG_LOG ("Client::Client ()"); - } - Client (const char* host, const Uint16 port, const int channel); - UDPsocket UDP_Open (const char* host, const Uint16 port, const int channel); - void UDP_CloseAll (void); - UDPsocket First (void) - { - return UDPsocks.at (0); - } -}; diff --git a/include/FileIO.h b/include/FileIO.h index 6b60b96..ab9b96a 100644 --- a/include/FileIO.h +++ b/include/FileIO.h @@ -16,25 +16,15 @@ class FileIO FILE* fp; std::string path; public: - ~FileIO (void) - { - if (fp) - { - Close (); - fp = NULL; - } - } + FileIO (FILE* f); FileIO (const std::string&, const std::string&); - FileIO (FILE* f) - { - fp = f; - } - FILE* Open (const std::string&, const std::string&); + ~FileIO (void); + FILE *Open (const std::string&, const std::string&); int Close (void); int Seek (const off_t, const int); off_t Tell (void); - size_t Read(void*, const size_t); - size_t Write (const void*, const size_t); + size_t Read (void *, const size_t); + size_t Write (const void *, const size_t); void Rewind (void); /* I added these. */ time_t Mtime (void); diff --git a/include/Server.h b/include/Server.h index 89daeec..844c98c 100644 --- a/include/Server.h +++ b/include/Server.h @@ -3,40 +3,41 @@ #include #include -#include -#include +#include "lib_lua_common.h" +#include "UDPbase.h" -/* MTU */ -#define MAX_PACKET_SIZE (1024*1024) - -class Server +class Server : public UDPbase { SDL_mutex* mProcessPacketMutex; - SDL_TimerID mProcessPacketCallbackTimerID; - static Uint32 ProcessPacketCallback (Uint32, void*); + SDL_TimerID mFetchPacketsCallbackTimerID; + + std::vector TCPsocks; + std::vector UDPsocks; + UDPpacket** UDPPacketV; + SDLNet_SocketSet SocketSet; + lua_State *mLuaState; + public: - std::vector UDPsocks; - SDLNet_SocketSet SocketSet; - UDPpacket **UDPPacketV; - Server (void) - { - UDPsocks.clear (); - SocketSet = NULL; - UDPPacketV = NULL; - mProcessPacketMutex = NULL; - } Server (const char* host, const Uint16 port); - UDPsocket UDP_Open (Uint16 port); - void UDP_CloseAll (void); - void ProcessPacket (UDPpacket* packet); + ~Server (void); + + static Uint32 FetchPacketsCallback (Uint32 interval, void* param); + void ProcessPacketHelper (UDPpacket* packet); + void RunLua (const std::string& buf); + int AllocateApproximateBufferSpace (const int nclients); int Start (void); int Stop (void); int Lock (void) { return SDL_LockMutex (mProcessPacketMutex); } - int Unlock (void) + int Unlock (void) { return SDL_UnlockMutex (mProcessPacketMutex); } + lua_State* getLuaState(void) const { return mLuaState; } + const TCPsocket* getTCPsock (size_t idx) const { return &TCPsocks.at (idx); } + const UDPsocket* getUDPsock (size_t idx) const { return &UDPsocks.at (idx); } + UDPpacket* getUDPPacketV (size_t idx) const { return UDPPacketV[idx]; } + SDLNet_SocketSet getSocketSet (void) const { return SocketSet; } }; diff --git a/include/ToggleFullscreen.h b/include/ToggleFullscreen.h deleted file mode 100644 index e69de29..0000000 diff --git a/include/UDP_Write.h b/include/UDP_Write.h deleted file mode 100644 index ed63385..0000000 --- a/include/UDP_Write.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include - -int Buffer_Write_UDP (UDPsocket udpsock, const int channel, const size_t mtu, const void* buf, const size_t size); -int File_Write_UDP (UDPsocket udpsock, const int channel, const size_t mtu, const char* path); -int SendFile_UDP (const char* host, const Uint16 port, const int channel, const size_t mtu, const char* path); -int SendBuffer_UDP (const char* host, const Uint16 port, const int channel, const size_t mtu, const void* buf, const size_t size); diff --git a/include/UDPbase.h b/include/UDPbase.h new file mode 100644 index 0000000..12b68eb --- /dev/null +++ b/include/UDPbase.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include + +#define MAX_PACKET_SIZE 250 + +class UDPbase +{ + IPaddress addr; + public: + UDPbase (const char* host, const Uint16 port) + { + if (SDLNet_ResolveHost (&addr, host, SDLNet_Read16 (&port)) < 0) + { + throw "SDLNet_ResolveHost: " + std::string (SDLNet_GetError ()); + } + } + ~UDPbase (void) + { + } + UDPsocket Open (void) + { + return Open (addr.port); + } + UDPsocket Open (const Uint16 port) + { + UDPsocket sock = NULL; + IPaddress* addr; + if (NULL == (sock = SDLNet_UDP_Open (port))) + { + throw "SDLNet_UDP_Open: " + std::string (SDLNet_GetError ()); + } + if (NULL != (addr = SDLNet_UDP_GetPeerAddress (sock, -1))) + { + SDL_Log ("Opened UDP port %d", SDLNet_Read16 (&addr->port)); + } + return sock; + } + int Bind (UDPsocket sock, const int channel) + { + int binding; + SDL_assert (NULL != sock); + if (-1 == (binding = SDLNet_UDP_Bind (sock, channel, &addr))) + { + throw "SDLNet_UDP_Bind: " + std::string (SDLNet_GetError ()); + } + SDL_Log ("Binding UDP socket %s ch%d", this->toString ().c_str (), binding); + return binding; + } + void Close (UDPsocket sock) + { + SDL_assert (NULL != sock); + SDLNet_UDP_Close (sock); + sock = NULL; + } + std::string toString (void) + { + return std::string (SDLNet_ResolveIP (&addr)) + ":" + std::to_string (addr.port); + } +}; diff --git a/include/camera.h b/include/camera.h index b41c2e3..1931ed1 100644 --- a/include/camera.h +++ b/include/camera.h @@ -1,8 +1,6 @@ #pragma once -#include -#include -#include +#include /** * Default camera values @@ -14,6 +12,8 @@ #define DEFAULT_CAMERA_SENSITIVITY (1.0f) #define DEFAULT_CAMERA_JOYSENSITIVITY (1.0f) #define DEFAULT_CAMERA_ZOOM (45.0f) +#define DEFAULT_CAMERA_ZNEAR (0.1f) +#define DEFAULT_CAMERA_ZFAR (1000.0f) /* * Decelerate at gravity speed (9.8 m/s) / ??? @@ -25,19 +25,21 @@ class Camera { /** * An abstract camera class that processes input and calculates the corresponding + * ... */ glm::vec3 Position; glm::vec3 Front; - glm::vec3 Right; - glm::vec3 Up; glm::vec3 WorldUp; - /** Euler Angles, Vectors and Matrices for use in OpenGL. */ + /** + * ... Euler Angles, Vectors and Matrices for use in OpenGL. */ + glm::vec3 Right; + glm::vec3 Up; glm::vec3 Angles; - /* XXX Maybe we shouldn't let the camera move? */ + /* TODO combine with Object */ glm::vec3 Direction; /* Position movement */ - glm::vec2 ViewDirection; /* Yaw, Pitch movement */ + glm::vec3 ViewDirection; /* Yaw, Pitch movement */ void updateCameraVectors (void); @@ -52,20 +54,19 @@ class Camera }; /** Camera options */ - float MovementSpeed, MouseSensitivity, Zoom; - float DecelerationSpeed, ViewDecelerationSpeed, JoystickSensitivity; - float zNear, zFar; + float MovementSpeed, MouseSensitivity, JoystickSensitivity, DecelerationSpeed, ViewDecelerationSpeed; + float Zoom, zNear, zFar; Camera ( const glm::vec3 position = glm::vec3(0.0f, 0.0f, 1.0f) - , const glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f) - , const float yaw = DEFAULT_CAMERA_YAW - , const float pitch = DEFAULT_CAMERA_PITCH - , const float roll = DEFAULT_CAMERA_ROLL); + , const glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f) + , const float yaw = DEFAULT_CAMERA_YAW + , const float pitch = DEFAULT_CAMERA_PITCH + , const float roll = DEFAULT_CAMERA_ROLL); glm::mat4 GetViewMatrix (const bool constrainPitch = true); - void ProcessJoystickMovement (const float xoffset, const float yoffset, const float deltaTime); - void ProcessKeyboard (const Camera::Movement direction, const float deltaTime); - void ProcessMouseMovement (const float xoffset, const float yoffset, const float deltaTime); - void ProcessMouseScroll (const float xoffset, const float yoffset, const float deltaTime); + void ProcessJoystickMovement (const float, const float, const float); + void ProcessKeyboard (const Camera::Movement, const float); + void ProcessMouseMovement (const float, const float, const float); + void ProcessMouseScroll (const float, const float, const float); }; diff --git a/include/debug.h b/include/debug.h index 0fb7ac9..972a4f2 100644 --- a/include/debug.h +++ b/include/debug.h @@ -1,20 +1,29 @@ #pragma once #ifdef DEBUG + #include #include -#define DEBUG_LOG(...) debug_log (__FILE__, __LINE__, __func__, __VA_ARGS__) -static void debug_log (const char* filename, const int lineno, const char* func, const char* fmt, ...) -{ - char buf[8192]; - va_list ap; - SDL_memset (buf, 0, sizeof buf); +#define DEBUG_LOG(...) debug_log (__FILE__, __LINE__, __func__, __VA_ARGS__) + +static void +debug_log ( +const char* filename, +const int lineno, +const char* func, +const char* fmt, ...) +{ + va_list ap; + char buf[8192]; + + SDL_memset (buf, 0, sizeof buf); va_start (ap, fmt); vsnprintf (buf, (sizeof buf) - 1, fmt, ap); va_end (ap); - SDL_LogMessage (SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG, "%s:%d: %s(): %s", filename, lineno, func, buf); + SDL_LogMessage (SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG, + "%s:%d: %s(): %s", filename, lineno, func, buf); } diff --git a/include/events_common.h b/include/events_common.h index 74db800..350985a 100644 --- a/include/events_common.h +++ b/include/events_common.h @@ -1,5 +1,7 @@ #pragma once +#include + enum { - PACKET_SDL_EVENT = SDL_USEREVENT, + PACKET_SDL_EVENT = SDL_USEREVENT, }; diff --git a/include/glCheckErrors.h b/include/glCheckErrors.h index 2a558db..d5cfa53 100644 --- a/include/glCheckErrors.h +++ b/include/glCheckErrors.h @@ -1,5 +1,6 @@ #pragma once +#ifdef DEBUG #include #include @@ -12,3 +13,6 @@ fprintf (stderr, "%s:%d: %s\n", __FILE__, __LINE__, glewGetErrorString(err)); \ } \ } while (0) +#else +#define glCheckErrors() +#endif diff --git a/include/lib_SDL_common.h b/include/lib_SDL_common.h index 67ff276..35698f9 100644 --- a/include/lib_SDL_common.h +++ b/include/lib_SDL_common.h @@ -11,6 +11,10 @@ #include #include +/* + * Start SDL with everything enabled. + * Also loads plugins. + */ void common_SDL_Init (void); void common_SDL_Quit (void); diff --git a/include/lib_lua_common.h b/include/lib_lua_common.h index f8deafc..2907c8e 100644 --- a/include/lib_lua_common.h +++ b/include/lib_lua_common.h @@ -5,11 +5,11 @@ #ifdef __cplusplus extern "C" { -#endif -#include -#include -#include -#ifdef __cplusplus + #endif + #include + #include + #include + #ifdef __cplusplus }; #endif diff --git a/include/shader.h b/include/shader.h index 37127f5..e4548fd 100644 --- a/include/shader.h +++ b/include/shader.h @@ -12,25 +12,26 @@ class ShaderProgram { bool mUniformLocationsNeedRefresh; std::map UniformLocationCache; - static GLint my_checkCompileSuccess (const GLuint id, const GLenum type); + static GLint my_checkCompileSuccess (const GLuint, const GLenum); public: GLuint ID; ShaderProgram (void); ShaderProgram (const std::string&, const std::string&, const std::string&); GLint getCachedLoc (const std::string&); void RefreshUniformLocations (void); - void Use (void); - void Bool (const std::string&, const bool&value); - void Float (const std::string&, const float&value); - void Int (const std::string&, const int&value); - void Vec2 (const std::string&, const glm::vec2& value); - void Vec3 (const std::string&, const glm::vec3& value); - void Vec4 (const std::string&, const glm::vec4& value); - void Mat2 (const std::string&, const glm::mat2& value); - void Mat3 (const std::string&, const glm::mat3& value); - void Mat4 (const std::string&, const glm::mat4& value); + void Use (void); + void Bool (const std::string&, const bool&); + void Float (const std::string&, const float&); + void Int (const std::string&, const int&); + void Vec2 (const std::string&, const glm::vec2&); + void Vec3 (const std::string&, const glm::vec3&); + void Vec4 (const std::string&, const glm::vec4&); + void Mat2 (const std::string&, const glm::mat2&); + void Mat3 (const std::string&, const glm::mat3&); + void Mat4 (const std::string&, const glm::mat4&); - GLuint CompileShaderBuffer (const std::string&, const GLenum type); - GLuint CompileShaderPath (const std::string&, const GLenum type); + GLuint CompileShaderBuffer (const std::string&, const GLenum); + GLuint Compile3ShaderBuffers (const std::string&, const std::string&, const std::string&); + GLuint CompileShaderPath (const std::string&, const GLenum); GLint LinkProgram (void); }; diff --git a/include/util.h b/include/util.h index 818b2f7..6178a9d 100644 --- a/include/util.h +++ b/include/util.h @@ -6,8 +6,10 @@ #include -int IsProbablyAscii (const void *, const size_t); -void HexDump (const void *, const size_t); +void error (const char*, ...); -void UDP_DumpPacket (UDPpacket*); -std::string HostAddress (IPaddress*); +int util_IsProbablyAscii (const void *, const size_t); +void util_HexDump (const void *, const size_t); + +void util_UDP_DumpPacket (UDPpacket*); +int util_UDP_ApproximatePacketVSize (UDPpacket*); diff --git a/src/Client.cpp b/src/Client.cpp deleted file mode 100644 index 76cf8a3..0000000 --- a/src/Client.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "debug.h" -#include "Client.h" -#include "util.h" - -Client::Client (const char *host, const Uint16 port, const int channel) -{ - UDPsocket udpsock; - DEBUG_LOG ("Attempting to connect %s:%d ch%d", host, port, channel); - if (NULL != (udpsock = UDP_Open (host, port, channel))) - { - mHost = host; - mPort = port; - mChannel = channel; - UDPsocks.push_back (udpsock); - } -} - - -UDPsocket -Client::UDP_Open (const char *host, const Uint16 port, const int channel) -{ - char hoststring[128]; - IPaddress ipaddress; - UDPsocket udpsock; - if (!(udpsock = SDLNet_UDP_Open (0))) - { - DEBUG_LOG ("SDLNet_UDP_Open: %s", SDLNet_GetError ()); - return NULL; - } - if (SDLNet_ResolveHost (&ipaddress, host, port) < 0) - { - DEBUG_LOG ("SDLNet_ResolveHost: %s", SDLNet_GetError ()); - return NULL; - } - if (SDLNet_UDP_Bind (udpsock, channel, &ipaddress) < 0) - { - DEBUG_LOG ("SDLNet_UDP_Bind: %s", SDLNet_GetError ()); - return NULL; - } - DEBUG_LOG ("Bound socket %s ch%d", HostAddress (&ipaddress).c_str (), channel); - return udpsock; -} - - -void -Client::UDP_CloseAll (void) -{ - size_t i; - const size_t nclients = UDPsocks.size (); - for (i = 0; i < nclients; i++) - { - SDLNet_UDP_Unbind (UDPsocks[i], mChannel); - SDLNet_UDP_Close (UDPsocks[i]); - UDPsocks[i] = NULL; - } - UDPsocks.clear (); -} diff --git a/src/FileIO.cpp b/src/FileIO.cpp index 00719cc..95dd8df 100644 --- a/src/FileIO.cpp +++ b/src/FileIO.cpp @@ -1,6 +1,7 @@ #include "FileIO.h" -#include +#include +#include #include /* errno */ #include /* FILE* */ @@ -8,6 +9,12 @@ #include /* stat */ #include /* stat */ +FileIO::FileIO (FILE* f) +{ + fp = f; +} + + FileIO::FileIO (const std::string& filename, const std::string& mode) { if (!(fp = Open (filename, mode))) @@ -16,6 +23,16 @@ FileIO::FileIO (const std::string& filename, const std::string& mode) } +FileIO::~FileIO(void) +{ + if (fp) + { + Close (); + fp = NULL; + } +} + + FILE* FileIO::Open (const std::string& filename, const std::string& mode) { @@ -93,8 +110,8 @@ FileIO::Size (void) std::string FileIO::ReadToString (void) { - off_t size = Size () + 1; - std::vector b (size); - off_t nread = Read (b.data (), size); - return std::string ((const char *) b.data (), nread); + off_t size = Size (); + std::string b (size + 1, 0); + Read (&b[0], size); + return b; } diff --git a/src/Server.cpp b/src/Server.cpp index d8737d7..7795fba 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -1,63 +1,46 @@ #include "debug.h" -#include "Server.h" #include "events_common.h" #include "util.h" +#include "Server.h" Server::Server (const char *host, const Uint16 port) +: UDPbase (host, port) { - IPaddress ipaddress; - UDPsocket udpsock; - if (SDLNet_ResolveHost (&ipaddress, host, SDL_SwapBE16 (port)) < 0) + UDPsocket sock; + mProcessPacketMutex = SDL_CreateMutex (); + if (NULL != (sock = Open (port))) { - DEBUG_LOG ("SDLNet_ResolveHost: %s", SDLNet_GetError ()); - return; - } - if (NULL != (udpsock = UDP_Open (ipaddress.port))) - { - UDPsocks.push_back (udpsock); - mProcessPacketMutex = SDL_CreateMutex (); - HostAddress (&ipaddress); - } - else - { - SDL_Log ("Unable to bind to port %d; is it in use?", ipaddress.port); + Bind (sock, -1); + UDPsocks.push_back (sock); } + SocketSet = NULL; + UDPPacketV = NULL; } -void -Server::UDP_CloseAll (void) +Server::~Server (void) { - const size_t nclients = UDPsocks.size (); - for (size_t i = 0; i < nclients; i++) - { + int i, n; + n = TCPsocks.size (); + for (i = 0; i < n; i++) + SDLNet_TCP_Close (TCPsocks[i]); + TCPsocks.clear (); + n = UDPsocks.size (); + for (i = 0; i < n; i++) SDLNet_UDP_Close (UDPsocks[i]); - UDPsocks[i] = NULL; - } UDPsocks.clear (); -} - - -/* - * Open and keep track of a UDP socket. - */ -UDPsocket -Server::UDP_Open (const Uint16 port) -{ - UDPsocket udpsock; - if (!(udpsock = SDLNet_UDP_Open (port))) + if (mProcessPacketMutex) { - DEBUG_LOG ("SDLNet_UDP_Open: %s", SDLNet_GetError ()); - return NULL; + SDL_DestroyMutex (mProcessPacketMutex); + mProcessPacketMutex = NULL; } - return udpsock; } void -Server::ProcessPacket (UDPpacket * packet) +Server::ProcessPacketHelper (UDPpacket* packet) { - size_t len; + int len; SDL_Event event; SDL_UserEvent userevent; UDPpacket *temp; @@ -79,15 +62,9 @@ Server::ProcessPacket (UDPpacket * packet) int -Server::Start (void) +Server::AllocateApproximateBufferSpace (const int nclients) { - int l; - int numused; - - if (!mProcessPacketMutex) - { - mProcessPacketMutex = SDL_CreateMutex (); - } + int i, l, numused, total; if ((l = Lock ()) < 0) { @@ -95,38 +72,53 @@ Server::Start (void) return l; } - const size_t nclients = UDPsocks.size (); - if (!nclients) - { - SDL_Log ("No Clients!"); - return -1; - } - else - { - DEBUG_LOG ("Serving %ld clients", nclients); - } + SDL_Log ("Serving %d clients", nclients); if (!(UDPPacketV = SDLNet_AllocPacketV (nclients, MAX_PACKET_SIZE))) { - DEBUG_LOG ("SDLNet_AllocPacketV: %s", SDLNet_GetError ()); - return -1; + SDL_Log ("SDLNet_AllocPacketV: %s", SDLNet_GetError ()); } if (!(SocketSet = SDLNet_AllocSocketSet (nclients))) { - DEBUG_LOG ("SDLNet_AllocSocketSet: %s", SDLNet_GetError ()); - return -1; + SDL_Log ("SDLNet_AllocSocketSet: %s", SDLNet_GetError ()); } - for (size_t i = 0; i < nclients; i++) + + total = 0; + for (i = 0; i < nclients; i++) { numused = SDLNet_UDP_AddSocket (SocketSet, UDPsocks[i]); if (numused < 0) { - DEBUG_LOG ("SDLNet_AddSocket: %s", SDLNet_GetError ()); - return -1; + SDL_Log ("SDLNet_AddSocket: %s", SDLNet_GetError ()); } + total += numused; } - mProcessPacketCallbackTimerID = SDL_AddTimer (10, Server::ProcessPacketCallback, (void *) this); + if (total != UDPsocks.size ()) + SDL_Log ("Total clients: %d (%ld?)", total, UDPsocks.size ()); + + return Unlock (); +} + + +int +Server::Start (void) +{ + int l; + + if ((l = Lock ()) < 0) + { + DEBUG_LOG ("Lock failed: %s", SDL_GetError ()); + return l; + } + + const int nclients = UDPsocks.size (); + AllocateApproximateBufferSpace (nclients); + + mLuaState = luaL_newstate (); + luaL_openlibs (mLuaState); + + mFetchPacketsCallbackTimerID = SDL_AddTimer (10, Server::FetchPacketsCallback, (void *) this); return Unlock (); } @@ -135,17 +127,19 @@ Server::Start (void) int Server::Stop (void) { - int l; + int i, l; if ((l = Lock ()) < 0) { DEBUG_LOG ("Lock failed"); return l; } - SDL_RemoveTimer (mProcessPacketCallbackTimerID); + SDL_RemoveTimer (mFetchPacketsCallbackTimerID); - const size_t nclients = UDPsocks.size (); - for (size_t i = 0; i < nclients; i++) + lua_close (mLuaState); + + const int nclients = UDPsocks.size (); + for (i = 0; i < nclients; i++) { SDLNet_UDP_DelSocket (SocketSet, UDPsocks[i]); } @@ -162,22 +156,28 @@ Server::Stop (void) } -Uint32 -Server::ProcessPacketCallback (Uint32 interval, void *param) +void +Server::RunLua (const std::string& buf) +{ + common_lua_run (mLuaState, "line", buf.c_str (), buf.length ()); +} + + +Uint32 Server::FetchPacketsCallback (Uint32 interval, void *param) { int numrecv, numready; - size_t i, j; + int i, j; SDL_assert (NULL != param); - Server& server = *(Server *) param; + Server* server = (Server *) param; - if (server.Lock () < 0) + if (server->Lock () < 0) { DEBUG_LOG ("Lock failed"); return 0; } - numready = SDLNet_CheckSockets (server.SocketSet, ~0); + numready = SDLNet_CheckSockets (server->getSocketSet (), 1); if (numready < 0) { DEBUG_LOG ("SDLNet_CheckSockets: %s", SDLNet_GetError ()); @@ -189,24 +189,25 @@ Server::ProcessPacketCallback (Uint32 interval, void *param) } /* check all sockets with SDLNet_SocketReady and handle the active ones. */ - for (i = 0; i < (size_t) numready; i++) + for (i = 0; i < numready; i++) { - if (SDLNet_SocketReady (server.UDPsocks[i])) + if (SDLNet_SocketReady (*server->getUDPsock (i))) { - numrecv = SDLNet_UDP_RecvV (server.UDPsocks[i], &server.UDPPacketV[i]); + UDPpacket* packet = server->getUDPPacketV (i); + numrecv = SDLNet_UDP_RecvV (*server->getUDPsock (i), &packet); if (numrecv < 0) { DEBUG_LOG ("SDLNet_UDP_RecvV: %s", SDLNet_GetError ()); break; } - for (j = 0; j < (size_t) numrecv; j++) + for (j = 0; j < numrecv; j++) { - server.ProcessPacket (server.UDPPacketV[i]); + server->ProcessPacketHelper (packet); } } } - server.Unlock (); + server->Unlock (); return interval; } diff --git a/src/UDP_Write.cpp b/src/UDP_Write.cpp deleted file mode 100644 index d4cc19d..0000000 --- a/src/UDP_Write.cpp +++ /dev/null @@ -1,129 +0,0 @@ -#include "debug.h" -#include "FileIO.h" -#include "Client.h" -#include "util.h" - -#include - -#include -#include -#include - -#include -#include - -/* XXX gross */ -int -Buffer_Write_UDP (UDPsocket udpsock, const int channel, const size_t mtu, const void *buf, const size_t size) -{ - const char *bufPtr; - const char *bufPtrEnd; - int numsent, npackets; - IPaddress *ipaddress; - size_t i, our_nsent, our_mtu; - UDPpacket **packetV; - SDL_assert (mtu > 0); - SDL_assert (size > 0); - numsent = 0; - our_mtu = mtu; - if (size < our_mtu) - our_mtu = size; - npackets = ceil ((double) size / (double) our_mtu); - if (!npackets) - { - DEBUG_LOG ("File_Write_UDP: zero length packet"); - return 0; - } - packetV = SDLNet_AllocPacketV (npackets, our_mtu); - if (!packetV) - { - DEBUG_LOG ("SDLNet_AllocPacketV: %s", SDLNet_GetError ()); - return 0; - } - i = 0; - bufPtr = (const char *) buf; - bufPtrEnd = bufPtr + size; - if (NULL == (ipaddress = SDLNet_UDP_GetPeerAddress (udpsock, channel))) - { - DEBUG_LOG ("SDLNet_UDP_GetPeerAddress: %s", SDLNet_GetError ()); - return 0; - } - DEBUG_LOG ("Sending %ld bytes to %s ch%d", size, HostAddress (ipaddress), channel); - size_t nsent = size; - while (i < (size_t) npackets && bufPtr < bufPtrEnd) - { - our_nsent = nsent; - if (our_nsent > our_mtu) - our_nsent = our_mtu; - packetV[i]->channel = channel; - packetV[i]->address = *ipaddress; - SDL_memset (packetV[i]->data, 0, our_mtu); - SDL_memcpy (packetV[i]->data, bufPtr, our_nsent); - packetV[i]->len = our_nsent; - bufPtr += our_mtu; - nsent -= our_mtu; - i++; - } - numsent = SDLNet_UDP_SendV (udpsock, packetV, npackets); - if (!numsent) - { - SDL_Log ("SDLNet_UDP_SendV (%d): %s", npackets, SDLNet_GetError ()); - } - SDLNet_FreePacketV (packetV); - return numsent; -} - - -int -File_Write_UDP (UDPsocket udpsock, const int channel, const char *path, const size_t mtu) -{ - int numsent; - Sint64 size; - numsent = 0; - try - { - FileIO f (path, "r"); - size = f.Size (); - std::vector b (size + 1); - f.Read (b.data (), size); - numsent = Buffer_Write_UDP (udpsock, channel, mtu, b.data (), b.size ()); - } - catch (int err) - { - SDL_Log ("File_Write_UDP: %s", strerror (errno)); - } - - return numsent; -} - - -int -SendBuffer_UDP (const char *host, const Uint16 port, const int channel, const size_t mtu, const void *buf, const size_t size) -{ - int numsent; - UDPsocket udpsock; - numsent = 0; - Client client (host, port, channel); - if (NULL != (udpsock = client.First ())) - { - numsent = Buffer_Write_UDP (udpsock, channel, mtu, buf, size); - client.UDP_CloseAll (); - } - return numsent; -} - - -int -SendFile_UDP (const char *host, const Uint16 port, const int channel, const size_t mtu, const char *path) -{ - int numsent; - UDPsocket udpsock; - numsent = 0; - Client client (host, port, channel); - if (NULL != (udpsock = client.First ())) - { - numsent = File_Write_UDP (udpsock, channel, path, mtu); - client.UDP_CloseAll (); - } - return numsent; -} diff --git a/src/camera.cpp b/src/camera.cpp index 65ad0a4..c9e6487 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -24,21 +24,23 @@ lerp (const glm::vec3 x, const glm::vec3 y, const float t) Camera::Camera (const glm::vec3 position, const glm::vec3 up, const float yaw, const float pitch, const float roll) +: Position (position) +, Front (glm::vec3 (0.0, 0.0, -1.0f)) +, WorldUp (up) +, Right (glm::vec3 (0.0f)) +, Up (glm::vec3 (0.0f)) +, Angles (glm::vec3 (yaw, pitch, roll)) +, Direction (glm::vec3 (0.0f)) +, ViewDirection (glm::vec3 (0.0f)) +, MovementSpeed (DEFAULT_CAMERA_SPEED) +, MouseSensitivity (DEFAULT_CAMERA_SENSITIVITY) +, JoystickSensitivity (DEFAULT_CAMERA_JOYSENSITIVITY) +, DecelerationSpeed (DEFAULT_CAMERA_DECELERATIONSPEED) +, ViewDecelerationSpeed (DEFAULT_CAMERA_MOUSEDECELERATIONSPEED) +, Zoom (DEFAULT_CAMERA_ZOOM) +, zNear (DEFAULT_CAMERA_ZNEAR) +, zFar (DEFAULT_CAMERA_ZFAR) { - Front = glm::vec3 (0.0f, 0.0f, -1.0f); - WorldUp = up; - MovementSpeed = DEFAULT_CAMERA_SPEED; - MouseSensitivity = DEFAULT_CAMERA_SENSITIVITY; - Zoom = DEFAULT_CAMERA_ZOOM; - DecelerationSpeed = DEFAULT_CAMERA_DECELERATIONSPEED; - ViewDecelerationSpeed = DEFAULT_CAMERA_MOUSEDECELERATIONSPEED; - JoystickSensitivity = DEFAULT_CAMERA_JOYSENSITIVITY; - Position = position; - Angles = glm::vec3 (yaw, pitch, roll); - Direction = glm::vec3 (0); - ViewDirection = glm::vec2 (0); - zNear = 0.1f; - zFar = 1000.0f; updateCameraVectors (); } @@ -54,8 +56,8 @@ Camera::updateCameraVectors (void) /** * Calculate the new Front vector */ - Front = glm::normalize (glm::vec3 - ( cos (glm::radians (Angles.x)) * cos (glm::radians (Angles.y)) + Front = glm::normalize (glm::vec3 ( + cos (glm::radians (Angles.x)) * cos (glm::radians (Angles.y)) , sin (glm::radians (Angles.y)) , sin (glm::radians (Angles.x)) * cos (glm::radians (Angles.y)))); // std::cout << glm::to_string (roll_mat) << std::endl; @@ -91,8 +93,7 @@ glm::mat4 Camera::GetViewMatrix (const bool constrainPitch) */ updateCameraVectors (); Direction = lerp (Direction, glm::vec3 (0.0f), DecelerationSpeed); - ViewDirection = - lerp (ViewDirection, glm::vec2 (0.0f), ViewDecelerationSpeed); + ViewDirection = lerp (ViewDirection, glm::vec3 (0.0f), ViewDecelerationSpeed); // std::cout << glm::to_string (Position) << std::endl; return glm::lookAt (Position, Position + Front, Up); } diff --git a/src/client_main.cpp b/src/client_main.cpp index 89f20ba..b3f7a63 100644 --- a/src/client_main.cpp +++ b/src/client_main.cpp @@ -1,5 +1,4 @@ #include "camera.h" -#include "Client.h" #include "cube.h" #include "debug.h" #include "glCheckErrors.h" @@ -8,8 +7,8 @@ #include "quad.h" #include "shader.h" #include "signal_common.h" -#include "UDP_Write.h" #include "unused.h" +#include "UDPbase.h" #include #include @@ -71,17 +70,19 @@ struct Client_State int Window_Width; double ShaderTimeDividend; + bool AnalogInputEnabled; bool ImGuiEnabled; - bool ShaderPlaying; + bool ImpulseInputEnabled; bool InputCaptureMouse; bool InputFirstMouse; bool InputRelativeMouseMode; + bool RenderShaderPlaying; bool RenderShowQuad; }; -static std::shared_ptr cube; -static std::shared_ptr quad; -static std::shared_ptr client; +static std::unique_ptr cube; +static std::unique_ptr quad; +static std::unique_ptr client; static Camera camera; static ShaderProgram shader; @@ -96,7 +97,7 @@ main (int argc, char **argv) my_Init (argc, argv); - shader = ShaderProgram ("../handmade-x/glsl/camera.v.glsl", "", "./glsl/new.f.glsl"); + shader = ShaderProgram ("./glsl/camera.v.glsl", "", "./glsl/new.f.glsl"); if (!shader.ID) { SDL_Log ("Unable to load shader."); @@ -104,17 +105,26 @@ main (int argc, char **argv) } camera = Camera (); - cube = std::make_shared (1); - quad = std::make_shared (1); + values.iResolution.x = state.Window_Width; + values.iResolution.y = state.Window_Height; + values.iResolution.z = 1.0; + + cube = std::make_unique (1); + quad = std::make_unique (1); state.mtu = 1450; state.quit = 0; - client = std::make_shared (state.host, state.port, state.channel); - if (NULL == (state.udpsock = client->First ())) + client = std::make_unique (state.host, state.port); + if (NULL == (state.udpsock = client->Open (0))) { SDL_Log ("Unable to open client port"); goto _out; } + if (-1 == (state.channel = client->Bind (state.udpsock, -1))) + { + SDL_Log ("Unable to bind client port"); + goto _out; + } while (!state.quit) { @@ -137,18 +147,13 @@ main (int argc, char **argv) } my_AnalogInput (); - my_UpdateValues (); - projection = glm::perspective (glm::radians (camera.Zoom), (float) values.iResolution.x / (float) values.iResolution.y, camera.zNear, camera.zFar); view = camera.GetViewMatrix (); model = glm::mat4 (1.0f); - shader.Use (); - shader.Int ("iFrame", values.iFrame); - shader.Float ("iTime", values.iTime); - shader.Float ("iTimeDelta", values.iTimeDelta); - shader.Vec3 ("iResolution", values.iResolution); + my_UpdateValues (); + shader.Use (); shader.Mat4 ("Projection", projection); shader.Mat4 ("View", view); shader.Mat4 ("Model", model); @@ -158,7 +163,7 @@ main (int argc, char **argv) } _out: - client->UDP_CloseAll (); + client->Close (state.udpsock); SDL_GL_DeleteContext (state.GLContext); SDL_DestroyWindow (state.Window); common_SDL_Quit (); @@ -180,10 +185,17 @@ my_Init (int argc, char** argv) common_GL_Init (state.Window, &state.GLContext, 1); SDL_GetWindowSize (state.Window, &state.Window_Width, &state.Window_Height); - state.ShaderPlaying = true; - state.ShaderTimeDividend = 1000; - state.InputRelativeMouseMode = false; + state.AnalogInputEnabled = true; + state.ImpulseInputEnabled = true; + + state.ImGuiEnabled = false; state.InputCaptureMouse = false; + state.InputFirstMouse = true; + state.InputRelativeMouseMode = false; + state.RenderShaderPlaying = true; + state.RenderShowQuad = true; + + state.ShaderTimeDividend = 1000; } @@ -191,14 +203,22 @@ static void my_UpdateValues (void) { values.iFrame++; - if (state.ShaderPlaying) + + if (state.RenderShaderPlaying) { values.iTime += ((double) state.diff / (double) state.ShaderTimeDividend); } + values.iTimeDelta = ((double) state.diff / (double) 1000); values.iResolution.x = state.Window_Width; values.iResolution.y = state.Window_Height; values.iResolution.z = 1.0; + + shader.Use (); + shader.Int ("iFrame", values.iFrame); + shader.Float ("iTime", values.iTime); + shader.Float ("iTimeDelta", values.iTimeDelta); + shader.Vec3 ("iResolution", values.iResolution); } @@ -209,7 +229,7 @@ my_Render (void) glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (state.RenderShowQuad) { - // glEnable (GL_DEPTH_TEST); + glEnable (GL_DEPTH_TEST); cube->Draw (); } else @@ -298,6 +318,9 @@ my_AnalogInput (void) const float dt = 0.016; (void) state; + if (!state.AnalogInputEnabled) + return SDL_FALSE; + camera.ProcessKeyboard (kbd[SDL_SCANCODE_W] ? Camera::Movement::FORWARD : Camera::Movement::NONE, dt); camera.ProcessKeyboard (kbd[SDL_SCANCODE_S] ? Camera::Movement::BACKWARD : Camera::Movement::NONE, dt); camera.ProcessKeyboard (kbd[SDL_SCANCODE_A] ? Camera::Movement::LEFT : Camera::Movement::NONE, dt); @@ -320,6 +343,32 @@ my_Input_Key (SDL_Event * event) SDL_assert (NULL != event); down = event->type == SDL_KEYDOWN; quit = SDL_FALSE; + if (!state.ImpulseInputEnabled) + { + switch (event->key.keysym.sym) + { + case SDLK_i: + state.ImpulseInputEnabled = true; + break; + case SDLK_ESCAPE: + quit = SDL_TRUE; + break; + case SDLK_F11: + { + if (down) + { + state.InputFirstMouse = true; + state.InputCaptureMouse = true; + state.InputRelativeMouseMode = true; + common_SDL_ToggleFullscreen (SDL_GetWindowFromID (event->key.windowID)); + } + } + break; + default: + break; + } + return SDL_FALSE; + } switch (event->key.keysym.sym) { case SDLK_ESCAPE: @@ -336,7 +385,6 @@ my_Input_Key (SDL_Event * event) } } break; - /* case SDLK_m: { if (down) @@ -359,7 +407,6 @@ my_Input_Key (SDL_Event * event) state.RenderShowQuad = !state.RenderShowQuad; } break; - */ default: { if (event->key.keysym.scancode != SDL_GetScancodeFromKey (event->key.keysym.sym)) @@ -367,7 +414,7 @@ my_Input_Key (SDL_Event * event) DEBUG_LOG ("Physical %s key acting as %s key", SDL_GetScancodeName (event->key.keysym.scancode), SDL_GetKeyName (event->key.keysym.sym)); } // SDL_Log ("%d %d %ld", state.channel, state.mtu, sizeof (SDL_Event)); - Buffer_Write_UDP (state.udpsock, state.channel, state.mtu, (const void*)event, sizeof (SDL_Event)); + // Buffer_Write_UDP (state.udpsock, state.channel, state.mtu, (const void*)event, sizeof (SDL_Event)); } } return quit; diff --git a/src/cube.cpp b/src/cube.cpp index 6f006cc..ac43d38 100644 --- a/src/cube.cpp +++ b/src/cube.cpp @@ -1,67 +1,68 @@ #include "cube.h" -Cube::Cube (const GLsizei size) -: Object (size) +Cube::Cube (const GLsizei size): +Object (size) { - const float vertices[] = { - // positions // normals // texture coords - -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, - 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, - -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, + const float vertices[] = + { + // positions // normals // texture coords + -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, + 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, + 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, + 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, + -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, + -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, - -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, + 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, + 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, + -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, + -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, - -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, + -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, + -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, + -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, + -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, + 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, + 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, + 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, - 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, - 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, - 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, - -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, - -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, + -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, + 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, + 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, + 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, + -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, + -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, - -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, - 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, - 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, - 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, - -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, - -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, + 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, + 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, + 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, + -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, + -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, }; glBindVertexArray (VAO); - glBindBuffer (GL_ARRAY_BUFFER, VBO); - glBufferData (GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW); + glBindBuffer (GL_ARRAY_BUFFER, VBO); + glBufferData (GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW); - glBindVertexArray (VAO); - glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); - glEnableVertexAttribArray (0); + glBindVertexArray (VAO); + glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof (float), (void *) 0); + glEnableVertexAttribArray (0); - // glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); - // glEnableVertexAttribArray (1); + // glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof (float), (void*)(3 * sizeof (float))); + // glEnableVertexAttribArray (1); - glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); - glEnableVertexAttribArray (1); + glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof (float), (void *) (6 * sizeof (float))); + glEnableVertexAttribArray (1); } diff --git a/src/lib_SDL_common.cpp b/src/lib_SDL_common.cpp index b5e2b9b..90e8036 100644 --- a/src/lib_SDL_common.cpp +++ b/src/lib_SDL_common.cpp @@ -1,6 +1,7 @@ #include "debug.h" -#include "unused.h" #include "lib_SDL_common.h" +#include "unused.h" +#include "signal_common.h" #include /* exit */ @@ -9,13 +10,29 @@ #define DEFAULT_WINDOW_HEIGHT 600 static void +my_SDL_Linked_Version (const char* lib, const SDL_version* compile_version, const SDL_version* link_version) +{ + const char* msg = "%8s with %9s version: %d.%d.%d"; + SDL_assert (NULL != lib); + SDL_assert (NULL != compile_version); + SDL_assert (NULL != link_version); + SDL_Log (msg, "compiled", lib, compile_version->major, compile_version->minor, compile_version->patch); + SDL_Log (msg, "linked", lib, link_version->major, link_version->minor, link_version->patch); +} + +static void my_SDLNet_Init (void) { + SDL_version compile_version; + const SDL_version* link_version; if (SDLNet_Init () == -1) { SDL_Log ("SDLNet_Init: %s", SDLNet_GetError ()); exit (EXIT_FAILURE); } + link_version = SDLNet_Linked_Version (); + SDL_NET_VERSION (&compile_version); + my_SDL_Linked_Version ("SDL_Net", &compile_version, link_version); } @@ -23,6 +40,8 @@ static void my_IMG_Init (int flags) { int initted; + SDL_version compile_version; + const SDL_version* link_version; initted = IMG_Init (flags); if ((initted & flags) != flags) { @@ -30,18 +49,26 @@ my_IMG_Init (int flags) exit (EXIT_FAILURE); } SDL_assert ((initted & flags) == flags); + link_version = IMG_Linked_Version (); + SDL_IMAGE_VERSION (&compile_version); + my_SDL_Linked_Version ("SDL_image", &compile_version, link_version); } static void my_TTF_Init (void) { + const SDL_version* link_version; + SDL_version compile_version; if (TTF_Init () == -1) { SDL_Log ("TTF_Init: %s", TTF_GetError ()); exit (EXIT_FAILURE); } SDL_assert (1 == TTF_WasInit ()); + link_version = TTF_Linked_Version (); + SDL_TTF_VERSION (&compile_version); + my_SDL_Linked_Version ("SDL_TTF", &compile_version, link_version); } @@ -49,6 +76,8 @@ static void my_Mix_Init (int flags) { int initted; + SDL_version compile_version; + const SDL_version* link_version; initted = Mix_Init (flags); if ((initted & flags) != flags) { @@ -56,11 +85,14 @@ my_Mix_Init (int flags) exit (EXIT_FAILURE); } SDL_assert ((initted & flags) == flags); + link_version = Mix_Linked_Version (); + SDL_MIXER_VERSION (&compile_version); + my_SDL_Linked_Version ("SDL_mixer", &compile_version, link_version); } static SDL_AssertState -my_SDL_AssertionHandler(const SDL_AssertData* data, void* userdata) +my_SDL_AssertionHandler (const SDL_AssertData* data, void* userdata) { UNUSED (data); UNUSED (userdata); @@ -71,7 +103,7 @@ my_SDL_AssertionHandler(const SDL_AssertData* data, void* userdata) static void my_SDL_Assert_Init (void) { - SDL_SetAssertionHandler(my_SDL_AssertionHandler, NULL); + SDL_SetAssertionHandler (my_SDL_AssertionHandler, NULL); } @@ -79,6 +111,9 @@ void common_SDL_Init (void) { Uint32 Flags; + + common_Signal_Init (); + Flags = SDL_INIT_EVERYTHING; if (SDL_Init (Flags) < 0) { @@ -106,18 +141,20 @@ common_SDL_Quit (void) void -common_SDL_CreateWindow (SDL_Window ** wind) +common_SDL_CreateWindow (SDL_Window** wind) { Uint32 Flags; SDL_assert (NULL != wind); Flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL; - *wind = SDL_CreateWindow (DEFAULT_WINDOW_TITLE, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT, Flags); + *wind = + SDL_CreateWindow (DEFAULT_WINDOW_TITLE, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, DEFAULT_WINDOW_WIDTH, + DEFAULT_WINDOW_HEIGHT, Flags); SDL_assert (NULL != *wind); } int -common_SDL_ToggleFullscreen (SDL_Window * window) +common_SDL_ToggleFullscreen (SDL_Window* window) { Uint32 Flags = SDL_GetWindowFlags (window); if (Flags & SDL_WINDOW_FULLSCREEN_DESKTOP) @@ -133,10 +170,10 @@ common_SDL_ToggleFullscreen (SDL_Window * window) } -SDL_Surface * +SDL_Surface* common_SDL_LoadSurfacePath (const std::string& path) { - SDL_Surface *image; + SDL_Surface* image; if (!(image = IMG_Load (path.c_str ()))) { DEBUG_LOG ("IMG_Load: %s", IMG_GetError ()); diff --git a/src/lib_lua_common.cpp b/src/lib_lua_common.cpp index efb3e69..0e54f62 100644 --- a/src/lib_lua_common.cpp +++ b/src/lib_lua_common.cpp @@ -1,4 +1,5 @@ #include "lib_lua_common.h" +#include "util.h" #include #include @@ -8,7 +9,6 @@ static int l_map (lua_State*); static int l_split (lua_State*); static void call_va (lua_State*, const char*, const char*, ...); -static void error (lua_State*, const char*, ...); int common_lua_run (lua_State* L, const char* name, const char* buff, const size_t buff_len) @@ -55,14 +55,13 @@ common_lua_stack_dump (lua_State* L) static void -error (lua_State* L, const char* fmt, ...) +Lua_error (lua_State* L, const char* fmt, ...) { va_list argp; va_start (argp, fmt); - vfprintf (stderr, fmt, argp); + error (fmt, argp); va_end (argp); lua_close (L); - exit (EXIT_FAILURE); } @@ -70,15 +69,15 @@ static void load (const char* filename, int* width, int* height) { lua_State* L = luaL_newstate (); - luaL_openlibs (L); + luaL_openlibs (L); if (luaL_loadfile (L, filename) || lua_pcall (L, 0, 0, 0)) - error (L, "cannot run configuration file: %s", lua_tostring (L, -1)); + Lua_error (L, "cannot run configuration file: %s", lua_tostring (L, -1)); lua_getglobal (L, "width"); lua_getglobal (L, "height"); if (!lua_isnumber (L, -2)) - error (L, "`width' should be a number\n"); + Lua_error (L, "`width' should be a number\n"); if (!lua_isnumber (L, -1)) - error (L, "`height' should be a number\n"); + Lua_error (L, "`height' should be a number\n"); *width = (int) lua_tonumber (L, -2); *height = (int) lua_tonumber (L, -1); lua_close (L); @@ -110,7 +109,7 @@ call_va (lua_State* L, const char* func, const char* sig, ...) case '>': goto endwhile; default: - error (L, "invalid option (%c)", *(sig - 1)); + Lua_error (L, "invalid option (%c)", *(sig - 1)); } narg++; luaL_checkstack (L, 1, "too many arguments"); @@ -120,7 +119,7 @@ call_va (lua_State* L, const char* func, const char* sig, ...) nres = strlen (sig); /* number of expected results */ /* do the call */ if (lua_pcall (L, narg, nres, 0) != 0) - error (L, "error running function `%s': %s", func, lua_tostring (L, -1)); + Lua_error (L, "error running function `%s': %s", func, lua_tostring (L, -1)); /* retrieve results */ nres = -nres; /* stack index of first result */ while (*sig) @@ -129,21 +128,21 @@ call_va (lua_State* L, const char* func, const char* sig, ...) { case 'd': /* double result */ if (!lua_isnumber (L, nres)) - error (L, "wrong result type"); + Lua_error (L, "wrong result type"); *va_arg (vl, double *) = lua_tonumber (L, nres); break; case 'i': /* int result */ if (!lua_isnumber (L, nres)) - error (L, "wrong result type"); + Lua_error (L, "wrong result type"); *va_arg (vl, int *) = (int) lua_tonumber (L, nres); break; case 's': /* string result */ if (!lua_isstring (L, nres)) - error (L, "wrong result type"); + Lua_error (L, "wrong result type"); *va_arg (vl, const char **) = lua_tostring (L, nres); break; default: - error (L, "invalid option (%c)", *(sig - 1)); + Lua_error (L, "invalid option (%c)", *(sig - 1)); } nres++; } diff --git a/src/server_main.cpp b/src/server_main.cpp index 94ff552..db1c8db 100644 --- a/src/server_main.cpp +++ b/src/server_main.cpp @@ -1,46 +1,61 @@ #include "debug.h" #include "lib_SDL_common.h" /* SDL* */ -#include "Server.h" #include "signal_common.h" #include "unused.h" #include "events_common.h" #include "trim.h" #include "lib_lua_common.h" #include "util.h" +#include "Server.h" +#include +#include +#include +#include #include #include /* exit */ #include /* getopt */ #include /* getopt */ +static bool done = false; +static const char* host = NULL; +static Uint16 port = 6666; +static const char* prompt_str = "> "; + +static std::unique_ptr server; + static bool my_SDL_UserEvent (SDL_Event *); +static int my_StdinThread(void*); static void my_Usage (const char *); static void my_GetOpt (int, char **); static void my_ProcessPacket (UDPpacket *); - -static const char* host = NULL; -static Uint16 port = 6666; +static bool my_StdinThread_Helper (const std::string&); +static void my_ShowPrompt (void); int main (int argc, char **argv) { - bool done; SDL_Event ev; - Server server; my_GetOpt (argc, argv); common_Signal_Init (); common_SDL_Init (); - server = Server (host, port); - if (server.Start () < 0) + server = std::make_unique (host, port); + + if (server->Start () < 0) { SDL_Log ("Couldn't start server!"); exit (EXIT_FAILURE); } done = false; + SDL_Thread* stdin_loop = SDL_CreateThread(my_StdinThread, "my_StdinThread", (void*)NULL); + if (NULL == stdin_loop) { + error ("SDL_CreateThread failed: %s\n", SDL_GetError()); + } + while (!done) { SDL_Delay (1); @@ -62,8 +77,9 @@ main (int argc, char **argv) } } - server.UDP_CloseAll (); - server.Stop (); + server->Stop (); + + SDL_WaitThread (stdin_loop, NULL); common_SDL_Quit (); @@ -101,7 +117,6 @@ my_ProcessPacket (UDPpacket* packet) { char c; size_t len; - char hoststring[128]; SDL_Event event; if (!packet) @@ -118,17 +133,14 @@ my_ProcessPacket (UDPpacket* packet) if (!((event.type == SDL_KEYDOWN) || (event.type == SDL_KEYUP))) { - SDL_Log ("UDP_DumpPacket:"); - UDP_DumpPacket (packet); + util_UDP_DumpPacket (packet); return; } std::string str = std::string (SDL_GetKeyName (event.key.keysym.sym)); bool down = (event.type == SDL_KEYDOWN); - HostAddress (&packet->address); - - // SDL_Log ("%d \"%s\"", str.length(), str.c_str ()); + // SDL_Log ("%d \"%s\"", str.length (), str.c_str ()); /* XXX ultra gross */ if (down) { @@ -137,14 +149,11 @@ my_ProcessPacket (UDPpacket* packet) if (str == "Return") { server_data.push_back ('\0'); - lua_State* L = luaL_newstate (); - luaL_openlibs (L); std::string buf = std::string ((const char*)server_data.data ()); printf ("\n => "); fflush (stdout); - common_lua_run (L, "line", buf.c_str (), buf.length ()); + server->RunLua (buf); fflush (stdout); - lua_close (L); server_data.clear (); } else if (str == "Left Shift") @@ -164,7 +173,7 @@ my_ProcessPacket (UDPpacket* packet) size = 0; server_data.resize (size); printf ("\x08\e[0K"); - fflush(stdout); + fflush (stdout); } } else @@ -246,3 +255,48 @@ my_GetOpt (int argc, char **argv) } } } + + +static void my_ShowPrompt (void) +{ + printf ("\n%s", prompt_str); + fflush (stdout); +} + +static bool my_StdinThread_Helper (const std::string& buf) +{ + util_HexDump (buf.c_str (), buf.length ()); + if (buf == "quit") + { + return true; + } + SDL_Delay (100); + puts (buf.c_str ()); + return false; +} + +static int my_StdinThread(void* param) +{ + std::string buf; + UNUSED (param); + while (!done) + { + my_ShowPrompt (); + try { + while (!done && getline (std::cin, buf)) + { + buf = trim (buf); + if ((done = my_StdinThread_Helper (buf))) + { + break; + } + my_ShowPrompt (); + } + } + catch (std::ifstream::failure& e) { + done = true; + } + } + + return 0; +} diff --git a/src/shader.cpp b/src/shader.cpp index 7c1cbb9..c595228 100644 --- a/src/shader.cpp +++ b/src/shader.cpp @@ -19,47 +19,10 @@ ShaderProgram::ShaderProgram (void) ShaderProgram::ShaderProgram (const std::string& vertexPath, const std::string& geometryPath, const std::string& fragmentPath) { - GLuint vertex, geometry, fragment; - - ID = glCreateProgram (); - if (ID) + GLuint id = Compile3ShaderBuffers (vertexPath, geometryPath, fragmentPath); + if (id) { - vertex = CompileShaderPath (vertexPath, GL_VERTEX_SHADER); - - geometry = 0; - if (!geometryPath.empty ()) - geometry = CompileShaderPath (geometryPath, GL_GEOMETRY_SHADER); - - FileIO f1 (DEFAULT_FRAGMENT_HEADER, "r"); - FileIO f2 (fragmentPath, "r"); - std::string buf = f1.ReadToString () + "\n" + f2.ReadToString (); - fragment = CompileShaderBuffer (buf.c_str (), GL_FRAGMENT_SHADER); - - if (vertex) - glAttachShader (ID, vertex); - if (geometry) - glAttachShader (ID, geometry); - if (fragment) - glAttachShader (ID, fragment); - - glLinkProgram (ID); - - if (!my_checkCompileSuccess (ID, GL_PROGRAM)) - { - throw "glLinkProgram error"; - ID = 0; - } - - glDeleteShader (vertex); - glDeleteShader (geometry); - glDeleteShader (fragment); - - RefreshUniformLocations (); - } - else - { - ID = 0; - throw "ShaderProgram error"; + ID = id; } } @@ -173,7 +136,7 @@ GLuint ShaderProgram::CompileShaderPath (const std::string& path, const GLenum t if (buf.empty ()) return 0; - return CompileShaderBuffer (buf.c_str (), type); + return CompileShaderBuffer (buf, type); } @@ -200,6 +163,52 @@ GLuint ShaderProgram::CompileShaderBuffer (const std::string& buf, const GLenum } +GLuint ShaderProgram::Compile3ShaderBuffers (const std::string& vertexPath, const std::string& geometryPath, const std::string& fragmentPath) +{ + GLuint vertex, geometry, fragment, id; + + id = glCreateProgram (); + if (!id) + return 0; + + vertex = CompileShaderPath (vertexPath, GL_VERTEX_SHADER); + + geometry = 0; + if (!geometryPath.empty ()) + geometry = CompileShaderPath (geometryPath, GL_GEOMETRY_SHADER); + + FileIO f1 (DEFAULT_FRAGMENT_HEADER, "r"); + FileIO f2 (fragmentPath, "r"); + std::string buf = f1.ReadToString () + "\n" + f2.ReadToString (); + fragment = CompileShaderBuffer (buf, GL_FRAGMENT_SHADER); + + if (vertex) + glAttachShader (id, vertex); + if (geometry) + glAttachShader (id, geometry); + if (fragment) + glAttachShader (id, fragment); + + glLinkProgram (id); + + if (!my_checkCompileSuccess (id, GL_PROGRAM)) + { + throw "glLinkProgram error"; + id = 0; + } + else + { + RefreshUniformLocations (); + } + + glDeleteShader (vertex); + glDeleteShader (geometry); + glDeleteShader (fragment); + + return id; +} + + GLint ShaderProgram::my_checkCompileSuccess (const GLuint id, const GLenum type) { @@ -218,7 +227,7 @@ ShaderProgram::my_checkCompileSuccess (const GLuint id, const GLenum type) goto HANDLE_SHADER; case GL_FRAGMENT_SHADER: typeName = "GL_FRAGMENT_SHADER"; -HANDLE_SHADER: + HANDLE_SHADER: glGetShaderiv (id, GL_COMPILE_STATUS,&success); if (GL_FALSE == success) glGetShaderiv (id, GL_INFO_LOG_LENGTH,&infoLogLength); diff --git a/src/signal_common.cpp b/src/signal_common.cpp index 4e112e9..c64f80b 100644 --- a/src/signal_common.cpp +++ b/src/signal_common.cpp @@ -1,5 +1,3 @@ -#define _POSIX_C_SOURCE - #include "signal_common.h" /* conflict with signal.h probably */ #include "unused.h" @@ -13,17 +11,20 @@ /* #include */ /* sigjmp_buf env; */ +static int signal_requested = 0; + static void my_Signal_Handler (int sig, siginfo_t* si, void* uap) { SDL_Event QUIT_EVENT = {SDL_QUIT}; - UNUSED (sig); UNUSED (uap); UNUSED (si); - SDL_PushEvent (&QUIT_EVENT); - exit (EXIT_FAILURE); + if (signal_requested++ > 0) + { + exit (EXIT_FAILURE); + } /* siglongjmp (env, sig); */ } @@ -35,7 +36,6 @@ common_Signal_Init (void) sa.sa_sigaction = my_Signal_Handler; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; - if (sigaction (SIGINT, &sa, NULL) == -1) { fputs ("Failed to setup SIGINT handler\n", stderr); diff --git a/src/util.cpp b/src/util.cpp index 22698e4..52d0596 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -1,14 +1,26 @@ #include "util.h" -#include - -#include /* printf */ -#include /* uint8_t */ #include /* round */ -#include /* inet_ntop */ +#include /* va_list */ +#include /* uint8_t */ +#include /* printf */ +#include /* exit */ + +void +error (const char* fmt, ...) +{ + va_list argp; + va_start (argp, fmt); + vfprintf (stderr, fmt, argp); + va_end (argp); + fputc ('\n', stderr); + fflush (stderr); + exit (EXIT_FAILURE); +} + int -IsProbablyAscii (const void *buf, const size_t len) +util_IsProbablyAscii (const void* buf, const size_t len) { const uint8_t* bufPtr; const uint8_t* bufPtrEnd; @@ -26,7 +38,7 @@ IsProbablyAscii (const void *buf, const size_t len) void -HexDump (const void *buf, const size_t len) +util_HexDump (const void* buf, const size_t len) { const uint8_t* bufPtr; const uint8_t* bufPtrEnd; @@ -50,32 +62,8 @@ HexDump (const void *buf, const size_t len) } -std::string -HostAddress (IPaddress* ipaddress) -{ - char hostaddress[128]; - char hoststring[256]; - - SDL_assert (NULL != ipaddress); - SDL_zero (hostaddress); - SDL_zero (hoststring); - - if (ipaddress->host) - { - inet_ntop (AF_INET, &ipaddress->host, hostaddress, 128); - snprintf (hoststring, (sizeof hoststring) - 1, "%s:%d", hostaddress, SDLNet_Read16 (&ipaddress->port)); - } - else - { - snprintf (hoststring, (sizeof hoststring) - 1, "0.0.0.0:%d", SDLNet_Read16 (&ipaddress->port)); - } - - return std::string (hoststring); -} - - void -UDP_DumpPacket (UDPpacket* packet) +util_UDP_DumpPacket (UDPpacket* packet) { const char* buf; @@ -84,19 +72,18 @@ UDP_DumpPacket (UDPpacket* packet) buf = (const char*)packet->data; + SDL_Log ("address: %s", SDLNet_ResolveIP (&packet->address)); SDL_Log ("channel: %d", packet->channel); SDL_Log ("len : %d", packet->len); SDL_Log ("maxlen : %d", packet->maxlen); SDL_Log ("status : %d", packet->status); - SDL_Log ("address: %s", HostAddress (&packet->address).c_str ()); - if (packet->len) { - if (IsProbablyAscii (buf, packet->len)) + if (util_IsProbablyAscii (buf, packet->len)) SDL_Log ("data:\n%s", buf); else - HexDump (buf, packet->len); + util_HexDump (buf, packet->len); } else { @@ -105,3 +92,21 @@ UDP_DumpPacket (UDPpacket* packet) //DEBUG_LOG ("%d bytes from %s:%d:\n%s", packet->len, hoststring, ntohs (packet->address.port), str.c_str ()); } + + +/* + * You can get the number of packets in a sorta hacky way if your packet is set up correctly. + * + * UDPpacket** packetV = SDLNet_AllocPacketV (1, n); + * UDP_ApproximatePacketVSize (packetV[0]); + * + * It relies on the maxlen field being set to the total length of the + * data, with the len field being set to the MTU. + */ +int +util_UDP_ApproximatePacketVSize (UDPpacket* src) +{ + SDL_assert (NULL != src); + SDL_assert (src->len > 0); + return (int)ceil ((double) src->maxlen / (double) src->len); +} diff --git a/test/test_Client b/test/test_Client deleted file mode 100755 index 4a9020b..0000000 Binary files a/test/test_Client and /dev/null differ diff --git a/test/test_Client.cpp b/test/test_Client.cpp deleted file mode 100644 index 0138b27..0000000 --- a/test/test_Client.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "debug.h" -#include "Client.h" -#include "UDP_Write.h" - -#include - -int -main (int argc, char **argv) -{ - int numsent; - const char *host = "localhost"; - const Uint16 port = 6666; - const int channel = 1; - const size_t mtu = 1450; - Client c; - UDPsocket udpsock; - c = Client (host, port, channel); - if (!(udpsock = c.First ())) - { - SDL_Log ("Client error"); - return 1; - } - - std::string buf = "Hello, world!\n"; - numsent = Buffer_Write_UDP (udpsock, channel, mtu, buf.c_str (), buf.length ()); - - SDL_Log ("%d", numsent); - c.UDP_CloseAll (); - - return 0; - -#if 0 - IPaddress ipaddress; - UDPsocket udpsock; - UDPpacket *packet; - udpsock = SDLNet_UDP_Open (0); - if (SDLNet_ResolveHost (&ipaddress, host, port) < 0) - { - DEBUG_LOG ("SDLNet_ResolveHost: %s", SDLNet_GetError ()); - return 0; - } - if (SDLNet_UDP_Bind (udpsock, channel, &ipaddress) < 0) - { - DEBUG_LOG ("SDLNet_UDP_Bind: %s", SDLNet_GetError ()); - return 0; - } - - packet = SDLNet_AllocPacket (1024); - if (packet) - { - packet->len = sprintf ((char*)packet->data, "Hello World!"); - packet->address = ipaddress; - numsent = SDLNet_UDP_Send (udpsock, packet->channel, packet); - if (!numsent) - { - DEBUG_LOG ("SDLNet_UDP_Send: %s\n", SDLNet_GetError ()); - } - } - - SDLNet_UDP_Unbind (udpsock, channel); - SDLNet_UDP_Close (udpsock); - udpsock = NULL; -#endif -} diff --git a/test/test_FileIO.cpp b/test/test_FileIO.cpp index 0dc82eb..b924f91 100644 --- a/test/test_FileIO.cpp +++ b/test/test_FileIO.cpp @@ -8,9 +8,6 @@ #include /* errno */ #include /* strerror */ - - - int main (int argc, char **argv) { diff --git a/test/test_File_Write_UDP.cpp b/test/test_File_Write_UDP.cpp deleted file mode 100644 index 0b521c7..0000000 --- a/test/test_File_Write_UDP.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include "FileIO.h" -#include "UDP_Write.h" - -#include - -#include -#include -#include -#include -#include - -#include - -static void usage (const char* argv0) -{ - fprintf (stderr, "Usage: %s [-f path] [-h] [-p port] [-s server]\n", argv0); -} - -int -main (int argc, char** argv) -{ - int opt; - int numsent; - int mtu; - int channel; - const char* path; - const char* server; - Uint16 port; - - path = NULL; - server = "localhost"; - port = 6666; - channel = 1; - mtu = 1450; - numsent = 0; - - while ((opt = getopt (argc, argv, "hs:p:f:")) != -1) - { - switch (opt) - { - case 'h': - usage (argv[0]); - exit (EXIT_FAILURE); - break; - case 's': - server = optarg; - if (!strcmp (server, "NULL")) - server = NULL; - break; - case 'p': - port = strtol (optarg, NULL, 0); - break; - case 'f': - path = optarg; - break; - default: - break; - } - } - -#if 0 - if (optind < argc) { - printf("non-option ARGV-elements: "); - while (optind < argc) - printf("%s ", argv[optind++]); - printf("\n"); - } -#endif - - if ((optind < argc) && (argv[optind][0] == '-')) - { - const size_t size = 8192; - std::vector buf (size); - std::fill (buf.begin(), buf.end(), 0); - size_t nread = fread (buf.data (), sizeof (char), size - 1, stdin); - numsent = SendBuffer_UDP (server, port, channel, mtu, buf.data (), nread); - } - else - { - if (path) - { - numsent = SendFile_UDP (server, port, channel, mtu, path); - } - } - - SDL_Log ("%d", numsent); - - return 0; -} diff --git a/test/test_Object.cpp b/test/test_Object.cpp deleted file mode 100644 index 4df666f..0000000 --- a/test/test_Object.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include "lib_SDL_common.h" -#include "lib_GL_common.h" - -#include "object.h" -#include "cube.h" -#include "quad.h" - -#include - -int main(void) -{ - int Window_Height; - int Window_Width; - SDL_GLContext GLContext; - SDL_Window *Window; - - common_SDL_Init (); - common_SDL_CreateWindow (&Window); - common_GL_Init (Window, &GLContext, 1); - SDL_GetWindowSize (Window, &Window_Width, &Window_Height); - - try { - SDL_Log ("Object o;"); - Object o; - SDL_Log ("Cube c;"); - Cube c; - SDL_Log ("Quad q;"); - Quad q; - } - catch (int e) - { - printf ("%d\n", e); - } - - try { - SDL_Log ("Object (1);"); - Object o = Object (1); - SDL_Log ("Cube (1);"); - Cube c = Cube (1); - SDL_Log ("Quad (1);"); - Quad q = Quad (1); - } - catch (int e) - { - printf ("%d\n", e); - } - - try { - SDL_Log ("Object o;"); - Object o; - SDL_Log ("Cube c;"); - Cube c; - SDL_Log ("Quad q;"); - Quad q; - SDL_Log ("Object (1);"); - o = Object (1); - SDL_Log ("Cube (1);"); - c = Cube (1); - SDL_Log ("Quad (1);"); - q = Quad (1); - } - catch (int e) - { - printf ("%d\n", e); - } - - SDL_GL_DeleteContext (GLContext); - SDL_DestroyWindow (Window); - common_SDL_Quit (); -} diff --git a/test/test_UDP_DumpPacket.cpp b/test/test_UDP_DumpPacket.cpp deleted file mode 100644 index 5401681..0000000 --- a/test/test_UDP_DumpPacket.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include "util.h" - -#include -#include - -int -main (int argc, char **argv) -{ - int channel; - const size_t size = strlen (argv[0]); - UDPpacket *packet; - UDPsocket udpsock; - - if (!(packet = SDLNet_AllocPacket (size))) - { - SDL_Log ("SDLNet_AllocPacket: %s", SDLNet_GetError ()); - return 1; - } - -#if 0 - /* TODO Something with the channel. Keep track of it client side? */ - channel = SDLNet_UDP_Bind (udpsock, -1, address); - if (channel == -1) - { - SDL_Log ("SDLNet_UDP_Bind: %s", SDLNet_GetError ()); - return 1; - } -#endif - packet->channel = -1; - - packet->len = snprintf ((char *) packet->data, size - 1, "%s", argv[0]); - - UDP_DumpPacket (packet); - return 0; -}