Compare commits

..

81 Commits

Author SHA1 Message Date
Kayne Ruse 65135b4b86 Codebase update: Added transparency control to Image 2013-07-19 14:06:10 +10:00
Kayne Ruse 51a0974d25 Updated the graphics a bit 2013-07-19 02:02:26 +10:00
Kayne Ruse a23156c425 Added thinner version of the font 2013-07-18 22:53:21 +10:00
Kayne Ruse c03743ed0c Fixed wrong characters being drawn 2013-07-18 18:16:46 +10:00
Kayne Ruse ee3877b906 Pruning unneeded files 2013-07-15 16:36:02 +10:00
Kayne Ruse c4bcced984 Rearranging files 2013-07-15 16:15:46 +10:00
Kayne Ruse 40a40b4e11 Refactored Image 2013-07-15 15:41:41 +10:00
Kayne Ruse 43dadcdbb8 Rearrenged the directory tree
I just _had_ to get rid of that horrible libs/ directory. Now most of the
graphical stuff is in client/, but I'll create more subdirectories so that
they're not getting in the way.
2013-07-15 14:58:12 +10:00
Kayne Ruse 28b491587c This now builds using an external SDL_net 2013-07-14 22:45:47 +10:00
Kayne Ruse 977c2b24fb Codebase update: Made Vector2 a POD 2013-07-11 18:23:51 +10:00
Kayne Ruse 99bbe4be3a Removed the local editor files
I'll be using Sketch to create the maps

git clone https://github.com/Ratstail91/Sketch.git
2013-07-01 18:26:27 +10:00
Kayne Ruse 4dc05f8daf Removed iostream
This was left in by mistake
2013-07-01 18:19:31 +10:00
Kayne Ruse b7205c278a Merge branch 'master' into dev 2013-07-01 18:14:55 +10:00
Kayne Ruse 6bee9b021d Entire project now builds using the local version of SDL_net 2013-07-01 17:57:11 +10:00
Kayne Ruse a49b0eb1fe Changed the timing system to give the machine a rest only when it's OK to 2013-06-26 23:52:31 +10:00
Kayne Ruse 2089105695 Fixed formatting 2013-06-26 17:59:11 +10:00
Kayne Ruse f667f503e7 Simple Multiplayer is working 2013-06-25 00:12:53 +10:00
Kayne Ruse 50bef9736c Deleting players on logout 2013-06-24 23:34:48 +10:00
Kayne Ruse 6d1ba24404 Simplified the packet system 2013-06-24 22:59:06 +10:00
Kayne Ruse ebd8c5e6fc Synchronization works 2013-06-24 21:46:11 +10:00
Kayne Ruse 42f9c5e1df Fixed for loops using the auto keyword 2013-06-24 16:31:38 +10:00
Kayne Ruse 3f2fcdf9e1 Players are being added in the client
The client sends a debug player to the server, with a constant movement to
show that the new client _is_ connecting. The next thing to add is the
sync system, so that the clients know what the server looks like when they
first join.
2013-06-24 16:15:48 +10:00
Kayne Ruse 2235f307e7 Added some multiplayer code to the server 2013-06-24 13:31:19 +10:00
Kayne Ruse 23782ff4e3 Removed maximum number of clients 2013-06-24 12:41:10 +10:00
Kayne Ruse 2a46f82f84 Updated README.md 2013-06-24 12:39:31 +10:00
Kayne Ruse 6a32599a69 Fixed a derp with the time 2013-06-24 12:18:36 +10:00
Kayne Ruse 0ca84a8653 Branch 'dev-map' is stable, merging into 'dev' 2013-06-24 10:45:51 +10:00
Kayne Ruse 66b2d6566c Branch 'dev-char' is stable, merging into 'dev' 2013-06-24 10:43:49 +10:00
Kayne Ruse 56375d64b6 Moved packets into their own namespace 2013-06-24 10:27:43 +10:00
Kayne Ruse 9608761cd5 Moved the entry structs into their own headers 2013-06-24 10:01:52 +10:00
Kayne Ruse c1d03d1cef Changed the name of the editor's main class 2013-06-24 09:26:25 +10:00
Kayne Ruse 09c88c7232 Merge branch 'dev' into dev-map 2013-06-24 09:23:12 +10:00
Kayne Ruse ddb93cfcf1 Changed the name of the client's main class 2013-06-24 09:22:43 +10:00
Kayne Ruse 42787dcb69 Explicitly deleted copy and move constructors 2013-06-24 09:13:27 +10:00
Kayne Ruse fcb17a8116 Merge branch 'dev' into dev-char 2013-06-24 09:02:36 +10:00
Kayne Ruse 2dc21f64fd Merge branch 'dev' into dev-map 2013-06-24 09:01:20 +10:00
Kayne Ruse f049c96df7 Switched from the service locator pattern to singleton pattern 2013-06-24 09:00:50 +10:00
Kayne Ruse d9ffa22b76 Created the editor shell 2013-06-23 16:19:41 +10:00
Kayne Ruse 24654d9e17 Merged the new frame rate system into dev-char 2013-06-23 15:11:24 +10:00
Kayne Ruse 7ad855348f Implemented a simpler frame rate system 2013-06-23 15:05:52 +10:00
Kayne Ruse d833b76856 PlayerCharacter is moving around smoothly 2013-06-23 13:53:55 +10:00
Kayne Ruse 3232925ccd Codebase update 2013-06-22 18:39:56 +10:00
Kayne Ruse e4ffba80aa Fixed incorrect preprocessor guard 2013-06-22 18:22:21 +10:00
Kayne Ruse a4d184ca75 Moved random code out of defines.* 2013-06-21 21:36:48 +10:00
Kayne Ruse 89179626be Improved Vector2 with floats & non-member operators 2013-06-21 15:23:07 +10:00
Kayne Ruse fc381348a5 Updated the game pitch 2013-06-21 14:50:59 +10:00
Kayne Ruse 5e99192fbf Lose focus on a server after a button is released 2013-06-18 19:38:08 +10:00
Kayne Ruse 33adb4b1a5 Put the license header into all source files 2013-06-18 16:40:51 +10:00
Kayne Ruse 33474cc6c0 Smooth connection and disconnection complete
The clients can connect and disconnect from the server with known no
issues. There is no way to shutdown the server yet, but it might be
possible to kick someone else from the server soon.
2013-06-18 16:21:42 +10:00
Kayne Ruse e833129983 Added guards incase of multiple calls 2013-06-18 14:06:57 +10:00
Kayne Ruse fd65fec5f7 The client is registering with the server 2013-06-17 19:53:22 +10:00
Kayne Ruse 69f03cd250 Working on connection systems 2013-06-17 19:04:05 +10:00
Kayne Ruse 27ed91688a Added the meta field to Packet to support Packet's metadata 2013-06-17 18:37:27 +10:00
Kayne Ruse 68ec7323a3 I can't progress until I add the address information to the Packet struct 2013-06-17 17:51:26 +10:00
Kayne Ruse 7b11bf22cb Specified a minimum Packet size for the DEBUG build 2013-06-17 17:14:10 +10:00
Kayne Ruse d83a536f35 Added debug output 2013-06-17 15:57:12 +10:00
Kayne Ruse ea761fb5bb Fixed the bug
running was false when it was checked in networkQueue(), so the thread was
ending early.
2013-06-17 15:49:57 +10:00
Kayne Ruse 685ca94335 This has the odd quirk related to networkQueue() 2013-06-17 15:15:27 +10:00
Kayne Ruse 5b2fd80a61 Fixed the Packet::type bug
In popNetworkPacket(), a second Packet p was being created, which was
destroyed when it went out of scope, and the original Packet p was being
returned.
2013-06-17 11:01:00 +10:00
Kayne Ruse d1aac9ffd8 Added peekNetworkPacket() 2013-06-17 10:12:20 +10:00
Kayne Ruse 3d92fb77b3 Server is multithreaded, but no connection is visible
UDPNetworkUtility and ConfigUtility are now using the ServiceLocator
pattern in the server, and networkQueue() is running in a separate thread
in the server. However, there seems to be a problem somewhere, since the
broadcast request & response are not producing any visible output.
2013-06-17 10:03:12 +10:00
Kayne Ruse 009e7b845b Fixed network error, leaving try block in place for the time being
It seems that the union type Packet didn't initialize Packet::type to
PacketType::NONE using in class initialization. I've fixed this by moving
the initialization of Packet::type to Packet::Packet().

This might actually be a compiler error, I might need to let someone know.
2013-06-17 09:09:04 +10:00
Kayne Ruse 752dcadfa1 Merge branch 'master' into dev 2013-06-17 08:32:02 +10:00
Kayne Ruse 9599d82db3 Added binary files, since git can't find .gitconfig on my brother's PC 2013-06-17 08:31:35 +10:00
Kayne Ruse 7fef2501a3 Glitch with threading 2013-06-17 07:24:16 +10:00
Kayne Ruse 419c9d8765 Moved the common directory into the libs directory 2013-06-16 13:59:11 +10:00
Kayne Ruse a0fa874a29 The server list is being populated from the network 2013-06-13 12:55:26 +10:00
Kayne Ruse 5110ebc1b2 Changed the escape key & quit event's function slightly 2013-06-13 12:31:29 +10:00
Kayne Ruse 843053d307 Implemented the server list box, still messy 2013-06-13 12:26:27 +10:00
Kayne Ruse 2148c1f13e Menu framework in place 2013-06-12 21:56:17 +10:00
Kayne Ruse f3ec4d4d8e Splash screen loads and displays correctly 2013-06-12 19:48:46 +10:00
Kayne Ruse cbd388f4ed Started using ServiceLocator, experimental 2013-06-12 06:35:43 +10:00
Kayne Ruse 37a9e4268b Imported the rsc directory from prototype-1 2013-06-12 05:23:06 +10:00
Kayne Ruse dfe0b4985a Modified build requirements
SDL_net needs to be _installed_ to the computer, rather than simply linked to.
This source distribution should be enough for that.
2013-06-12 04:37:01 +10:00
Kayne Ruse 7ca7f7f015 Added broadcast handling 2013-06-10 18:06:24 +10:00
Kayne Ruse c21a95f3e9 working on the server's skeleton, still slow going 2013-06-10 17:23:26 +10:00
Kayne Ruse 0a48131de4 Added common and test directories 2013-06-09 17:06:32 +10:00
Kayne Ruse 78326a3bbd Added a note about the project's development stage 2013-06-09 14:16:33 +10:00
Kayne Ruse 253e9ec8fc Created server shell 2013-06-08 01:52:19 +10:00
Kayne Ruse a1b248d1d7 Created the client program's framework
There are six scenes here, each of which representing roughly one part of
the final program's backbone.
2013-06-08 01:36:19 +10:00
Kayne Ruse 2757911399 Libraries are building correctly 2013-06-07 04:10:31 +10:00
174 changed files with 2476 additions and 9645 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
#Editor generated files
*.sln
*.vcproj
#*.sln
#*.vcproj
*.suo
*.ncb
*.user
+11 -20
View File
@@ -1,32 +1,23 @@
## Outline
_This project is currently in it's early prototype stage. You can see other versions in various branches or tagged as prototype-X._
Tortuga is a 2D multiplayer JRPG featuring permadeath, with an emphasis on multiplayer cooperation, exploration and customization. The game runs on customizable public and private servers.
Tortuga is a 2D multiplayer role playing game set in a large archipelago occupied by warring pirate clans. The emphasis of this game is on multiplayer cooperation, competition, and server customization. The game runs on highly customizable server software that can support up to 150 simultaneous players or more. The player characters are tied to the server where they are created and are susceptible to permadeath: deletion of a character upon death.
This game is inspired by classic 2D RPGs (Final Fantasy, The Legend of Zelda), as well as more modern sandboxes amd MMOs (Minecraft, EVE Online). This project is currently independently created and funded, with the goal of creating a game that will engage the players and inspire a large community.
## Dependencies
## Releases
* [SDL](http://www.libsdl.org/) - Simple DirectMedia Layer API
* [SDL_net](http://www.libsdl.org/projects/SDL_net/) - SDL's networking extension
The most recent stable build for Windows can be found [here](https://dl.dropboxusercontent.com/u/46669050/Tortuga.rar).
## Instructions
## Documentation
* [Tortuga Wiki](https://github.com/Ratstail91/Tortuga/wiki) - Full documentation
* [Tortuga Bug Tracker](https://github.com/Ratstail91/Tortuga/issues) - A list of all known bugs and issues
## External Dependencies
* [SDL 1.2](http://www.libsdl.org/) - Simple DirectMedia Layer API
* [SDL_net 1.2](http://www.libsdl.org/projects/SDL_net/) - SDL's networking extension
* [lua 5.2](http://www.lua.org/) - The lua programming language
* [SQLite3](http://www.sqlite.org/) - A lightweight SQL database engine
* This project uses C++11, which is available via GNU (or MinGW) 4.7, or Visual Studio 2012. Personally, I'm using MinGW 4.7.2.
* I'm trying to keep this as IDE agnostic as possible, so if you use an IDE, please add it's files to .gitignore.
* You can read more details on the Tortuga wiki [here](https://github.com/Ratstail91/Tortuga/wiki).
## Copyright
(Future versions (to be determined) may be released under a modified version of the [Uplink Developer's License](http://www.introversion.co.uk/uplink/developer/license.html).)
The current version of Tortuga is released under the [zlib license](http://en.wikipedia.org/wiki/Zlib_License).
Copyright (c) 2013, 2014 Kayne Ruse
Copyright (c) 2013 Kayne Ruse
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
@@ -34,4 +25,4 @@ Permission is granted to anyone to use this software for any purpose, including
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
3. This notice may not be removed or altered from any source distribution.
-34
View File
@@ -1,34 +0,0 @@
This is the README for Tortuga's demo build. The source code is available at:
https://github.com/Ratstail91/Tortuga
The current build may have bugs, missing features, bugs masquerading as
features, etc. You can report a bug/feature here:
https://github.com/Ratstail91/Tortuga/issues
Please note that this game requires a functioning server to operate correctly.
Both a game server and game client are included in this package.
-------------------------
Instructions For Setup
-------------------------
1. To create a server, simply run server.exe.
2. To join that server, run client.exe with config settings not already in use.
(Note: This process will be streamlined later).
3. To change the config settings, open rsc/config.cfg
4. These settings must be unique for each player:
* client.username
* client.handle
5. There are currently two options for 'client.avatar':
* client.avatar = elliot2.bmp #male
* client.avatar = coa2.bmp #female
6. When you've correctly set these values (good luck), select 'Start' from the
main menu; this displays the list of available servers.
7. Select the name of your server (default is 'local') and select 'Join'.
8. Welcome to Tortuga, enjoy your stay.
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -34,7 +34,7 @@ SDL_Surface* BaseScene::screen = nullptr;
//-------------------------
BaseScene::BaseScene() {
//
nextScene = SceneList::CONTINUE;
}
BaseScene::~BaseScene() {
@@ -75,10 +75,10 @@ SceneList BaseScene::GetNextScene() const {
//Frame loop
//-------------------------
void BaseScene::RunFrame() {
void BaseScene::RunFrame(double delta) {
FrameStart();
HandleEvents();
Update();
Update(delta);
FrameEnd();
}
@@ -86,7 +86,6 @@ void BaseScene::RenderFrame() {
SDL_FillRect(screen, 0, 0);
Render(screen);
SDL_Flip(screen);
SDL_Delay(10);
}
//-------------------------
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -28,29 +28,29 @@
class BaseScene {
public:
//Public access members
/* Public access members */
BaseScene();
virtual ~BaseScene();
//Program control
/* Program control */
static SDL_Surface* SetScreen(int w, int h, int bpp = 0, Uint32 flags = SDL_HWSURFACE|SDL_DOUBLEBUF);
static SDL_Surface* GetScreen();
SceneList SetNextScene(SceneList sceneIndex);
SceneList GetNextScene() const;
//Frame loop
virtual void RunFrame();
/* Frame loop */
virtual void RunFrame(double delta);
virtual void RenderFrame();
protected:
virtual void FrameStart() {}
virtual void HandleEvents();
virtual void Update() {}
virtual void Update(double delta) {}
virtual void FrameEnd() {}
virtual void Render(SDL_Surface* const screen) {}
//Event handlers
/* Event handlers */
virtual void QuitEvent() { SetNextScene(SceneList::QUIT); }
virtual void MouseMotion(SDL_MouseMotionEvent const&) {}
virtual void MouseButtonDown(SDL_MouseButtonEvent const&) {}
@@ -68,7 +68,7 @@ protected:
private:
static SDL_Surface* screen;
SceneList nextScene = SceneList::CONTINUE;
SceneList nextScene;
};
#endif
+76 -91
View File
@@ -1,11 +1,11 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial ClientApplications, and to alter it and redistribute it
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
@@ -21,107 +21,84 @@
*/
#include "client_application.hpp"
#include "serial_packet.hpp"
#include "config_utility.hpp"
#include <stdexcept>
#include <chrono>
#include <iostream>
//-------------------------
//Scene headers
//-------------------------
//Add the custom scene headers here
#include "splash_screen.hpp"
#include "main_menu.hpp"
#include "options_menu.hpp"
#include "lobby_menu.hpp"
#include "in_combat.hpp"
#include "in_world.hpp"
#include "disconnected_screen.hpp"
#include "lobby.hpp"
#include "main_menu.hpp"
#include "option_screen.hpp"
#include "splash_screen.hpp"
//-------------------------
//Public access members
//-------------------------
void ClientApplication::Init(int argc, char* argv[]) {
std::cout << "Beginning " << argv[0] << std::endl;
ClientApplication::ClientApplication() {
//
}
//load the prerequisites
ConfigUtility& config = ConfigUtility::GetSingleton();
config.Load("rsc/config.cfg", argc, argv);
ClientApplication::~ClientApplication() {
UnloadScene();
}
//-------------------------
//Initialize the APIs
//-------------------------
/* ClientApplication::Init()
* This function initializes the entire program. There are a number of things
* that could go wrong here, which is why there is such an unusual order of
* operations.
* Important things to note:
* The APIs are initiated here.
* The global objects are initialized here.
* The game's screen is created here, based on information loaded from the config file.
* The ConfigUtility's call to Load() also ensures that the "rsc\" folder is in the directory. It's easy to forget it.
*/
//initialize SDL
void ClientApplication::Init() {
//load the config file
try {
configUtil->Load("rsc/config.cfg");
}
catch(std::runtime_error& e) {
std::string s = e.what();
s += "; Ensure that the \"rsc\" directory is present";
throw(std::runtime_error(s));
}
//initialize the APIs
if (SDL_Init(SDL_INIT_VIDEO)) {
throw(std::runtime_error("Failed to initialize SDL"));
}
std::cout << "Initialized SDL" << std::endl;
//initialize SDL_net
if (SDLNet_Init()) {
throw(std::runtime_error("Failed to initialize SDL_net"));
}
UDPNetworkUtility::GetSingleton().Open(0);
std::cout << "Initialized SDL_net" << std::endl;
//-------------------------
//Setup the screen
//-------------------------
//create the screen
Uint32 flags = SDL_HWSURFACE | SDL_DOUBLEBUF;
flags |= configUtil->Bool("screen.f") ? SDL_FULLSCREEN : 0;
int w = config.Int("client.screen.w");
int h = config.Int("client.screen.h");
int f = config.Bool("client.screen.f") ? SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_FULLSCREEN : SDL_HWSURFACE|SDL_DOUBLEBUF;
BaseScene::SetScreen(
configUtil->Int("screen.w"),
configUtil->Int("screen.h"),
SDL_GetVideoInfo()->vfmt->BitsPerPixel,
flags);
BaseScene::SetScreen(w ? w : 800, h ? h : 600, 0, f);
std::cout << "Initialized the screen" << std::endl;
//-------------------------
//debug output
//-------------------------
//TODO: enable/disable these with a switch
#define DEBUG_OUTPUT_VAR(x) std::cout << "\t" << #x << ": " << x << std::endl;
std::cout << "Internal sizes:" << std::endl;
DEBUG_OUTPUT_VAR(NETWORK_VERSION);
DEBUG_OUTPUT_VAR(sizeof(Region::type_t));
DEBUG_OUTPUT_VAR(sizeof(Region));
DEBUG_OUTPUT_VAR(REGION_WIDTH);
DEBUG_OUTPUT_VAR(REGION_HEIGHT);
DEBUG_OUTPUT_VAR(REGION_DEPTH);
DEBUG_OUTPUT_VAR(REGION_TILE_FOOTPRINT);
DEBUG_OUTPUT_VAR(REGION_SOLID_FOOTPRINT);
DEBUG_OUTPUT_VAR(PACKET_STRING_SIZE);
DEBUG_OUTPUT_VAR(PACKET_BUFFER_SIZE);
DEBUG_OUTPUT_VAR(MAX_PACKET_SIZE);
DEBUG_OUTPUT_VAR(static_cast<int>(SerialPacketType::LAST));
#undef DEBUG_OUTPUT_VAR
//-------------------------
//finalize the startup
//-------------------------
std::cout << "Startup completed successfully" << std::endl;
//-------------------------
//debugging
//-------------------------
//...
//initiate the remaining singletons
netUtil->Open(0, sizeof(Packet));
}
void ClientApplication::Proc() {
LoadScene(SceneList::FIRST);
//prepare the time system
typedef std::chrono::steady_clock Clock;
typedef std::chrono::high_resolution_clock Clock;
Clock::duration delta(5 * Clock::duration::period::den / std::milli::den);
Clock::time_point simTime = Clock::now();
Clock::time_point realTime;
@@ -133,15 +110,16 @@ void ClientApplication::Proc() {
continue;
}
//update the current time
realTime = Clock::now();
//update the current time & give the computer as much of a break as possible
while ((realTime = Clock::now()) < simTime) {
SDL_Delay(1);
}
//simulate game time
while (simTime < realTime) {
//call each user defined function
activeScene->RunFrame();
//~60 FPS
simTime += std::chrono::duration<int, std::milli>(16);
activeScene->RunFrame(double(delta.count()) / Clock::duration::period::den);
simTime += delta;
}
//draw the game to the screen
@@ -152,11 +130,16 @@ void ClientApplication::Proc() {
}
void ClientApplication::Quit() {
std::cout << "Shutting down" << std::endl;
UDPNetworkUtility::GetSingleton().Close();
//clean up the singletons
netUtil->Close();
surfaceMgr->FreeAll();
//clean up the scene
UnloadScene();
//deinitialize the APIs
SDLNet_Quit();
SDL_Quit();
std::cout << "Clean exit" << std::endl;
}
//-------------------------
@@ -165,27 +148,29 @@ void ClientApplication::Quit() {
void ClientApplication::LoadScene(SceneList sceneIndex) {
UnloadScene();
switch(sceneIndex) {
//add scene creation calls here
case SceneList::FIRST:
case SceneList::SPLASHSCREEN:
activeScene = new SplashScreen();
case SceneList::INCOMBAT:
activeScene = new InCombat();
break;
case SceneList::INWORLD:
activeScene = new InWorld();
break;
case SceneList::LOBBY:
activeScene = new Lobby();
break;
case SceneList::MAINMENU:
activeScene = new MainMenu();
break;
case SceneList::OPTIONSMENU:
activeScene = new OptionsMenu();
case SceneList::OPTIONSCREEN:
activeScene = new OptionScreen();
break;
case SceneList::LOBBYMENU:
activeScene = new LobbyMenu(&clientIndex, &accountIndex); //TODO: can I use the ConfigUtility for these parameters?
break;
case SceneList::INWORLD:
activeScene = new InWorld(&clientIndex, &accountIndex);
break;
case SceneList::DISCONNECTEDSCREEN:
activeScene = new DisconnectedScreen();
case SceneList::FIRST:
case SceneList::SPLASHSCREEN:
activeScene = new SplashScreen();
break;
default:
throw(std::logic_error("Failed to recognize the scene index"));
}
+20 -16
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -24,35 +24,39 @@
#include "scene_list.hpp"
#include "base_scene.hpp"
#include "singleton.hpp"
#include "packet.hpp"
#include "information_manager.hpp"
#include "config_utility.hpp"
#include "surface_manager.hpp"
#include "udp_network_utility.hpp"
#include "singleton.hpp"
#include "SDL/SDL.h"
#include <map>
class ClientApplication: public Singleton<ClientApplication> {
class ClientApplication {
public:
//public methods
void Init(int argc, char* argv[]);
/* Public access members */
ClientApplication();
~ClientApplication();
void Init();
void Proc();
void Quit();
ClientApplication(ClientApplication const&) = delete;
ClientApplication(ClientApplication const&&) = delete;
private:
friend Singleton<ClientApplication>;
ClientApplication() = default;
~ClientApplication() = default;
//Private access members
/* Private access members */
void LoadScene(SceneList sceneIndex);
void UnloadScene();
BaseScene* activeScene = nullptr;
//shared parameters
int clientIndex = -1;
int accountIndex = -1;
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
InformationManager* infoMgr = Singleton<InformationManager>::Get();
};
#endif
-47
View File
@@ -1,47 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "base_character.hpp"
void BaseCharacter::CorrectSprite() {
//NOTE: These must correspond to the sprite sheet in use
if (motion.y > 0) {
sprite.SetYIndex(0);
}
else if (motion.y < 0) {
sprite.SetYIndex(1);
}
else if (motion.x > 0) {
sprite.SetYIndex(3);
}
else if (motion.x < 0) {
sprite.SetYIndex(2);
}
//animation
if (motion != 0) {
sprite.SetDelay(0.1);
}
else {
sprite.SetDelay(0);
sprite.SetXIndex(0);
}
}
-55
View File
@@ -1,55 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef BASECHARACTER_HPP_
#define BASECHARACTER_HPP_
//components
#include "character_defines.hpp"
#include "entity.hpp"
//std namespace
#include <string>
class BaseCharacter : public Entity {
public:
BaseCharacter() = default;
virtual ~BaseCharacter() = default;
//graphics
void CorrectSprite();
//metadata
int SetOwner(int i) { return owner = i; }
int GetOwner() { return owner; }
std::string SetHandle(std::string s) { return handle = s; }
std::string GetHandle() const { return handle; }
std::string SetAvatar(std::string s) { return avatar = s; }
std::string GetAvatar() const { return avatar; }
private:
//metadata
int owner;
std::string handle;
std::string avatar;
};
#endif
-62
View File
@@ -1,62 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "entity.hpp"
void Entity::Update() {
origin += motion;
sprite.Update(0.016);
}
void Entity::DrawTo(SDL_Surface* const dest, int camX, int camY) {
sprite.DrawTo(dest, origin.x - camX, origin.y - camY);
}
int Entity::SetEntityIndex(int i) {
return entityIndex = i;
}
int Entity::SetRoomIndex(int i) {
return roomIndex = i;
}
Vector2 Entity::SetOrigin(Vector2 v) {
return origin = v;
}
Vector2 Entity::SetMotion(Vector2 v) {
return motion = v;
}
int Entity::GetEntityIndex() {
return entityIndex;
}
int Entity::GetRoomIndex() {
return roomIndex;
}
Vector2 Entity::GetOrigin() {
return origin;
}
Vector2 Entity::GetMotion() {
return motion;
}
-37
View File
@@ -1,37 +0,0 @@
#config
INCLUDES+=. .. ../../common/gameplay ../../common/graphics ../../common/utilities
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=..
OUT=$(addprefix $(OUTDIR)/,client.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,33 +19,72 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "splash_screen.hpp"
#include "in_combat.hpp"
#include "config_utility.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
SplashScreen::SplashScreen() {
logo.LoadSurface(ConfigUtility::GetSingleton()["dir.logos"] + "krstudios.bmp");
startTick = std::chrono::steady_clock::now();
InCombat::InCombat() {
#ifdef DEBUG
cout << "entering InCombat" << endl;
#endif
}
SplashScreen::~SplashScreen() {
//
InCombat::~InCombat() {
#ifdef DEBUG
cout << "leaving InCombat" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void SplashScreen::Update() {
if (std::chrono::steady_clock::now() - startTick > std::chrono::duration<int>(1)) {
SetNextScene(SceneList::MAINMENU);
void InCombat::FrameStart() {
//
}
void InCombat::Update(double delta) {
//
}
void InCombat::FrameEnd() {
//
}
void InCombat::Render(SDL_Surface* const screen) {
//
}
//-------------------------
//Event handlers
//-------------------------
void InCombat::MouseMotion(SDL_MouseMotionEvent const& motion) {
//
}
void InCombat::MouseButtonDown(SDL_MouseButtonEvent const& button) {
//
}
void InCombat::MouseButtonUp(SDL_MouseButtonEvent const& button) {
//
}
void InCombat::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
QuitEvent();
break;
}
}
void SplashScreen::Render(SDL_Surface* const screen) {
logo.DrawTo(screen, (screen->w - logo.GetClipW()) / 2, (screen->h - logo.GetClipH()) / 2);
void InCombat::KeyUp(SDL_KeyboardEvent const& key) {
//
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,40 +19,30 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef OPTIONSMENU_HPP_
#define OPTIONSMENU_HPP_
#ifndef INCOMBAT_HPP_
#define INCOMBAT_HPP_
#include "base_scene.hpp"
#include "image.hpp"
#include "raster_font.hpp"
#include "button.hpp"
//TODO: The options screen needs to be USED
class OptionsMenu : public BaseScene {
class InCombat : public BaseScene {
public:
//Public access members
OptionsMenu();
~OptionsMenu();
/* Public access members */
InCombat();
~InCombat();
protected:
//Frame loop
/* Frame loop */
void FrameStart();
void Update();
void Update(double delta);
void FrameEnd();
void Render(SDL_Surface* const);
//Event handlers
/* Event handlers */
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//members
Image image;
RasterFont font;
Button backButton;
};
#endif
+326
View File
@@ -0,0 +1,326 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "in_world.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Quick and dirty
//-------------------------
static std::string itos(int i) {
char buffer[20];
snprintf(buffer, 20, "%d", i);
return std::string(buffer);
}
//-------------------------
//Public access members
//-------------------------
InWorld::InWorld() {
#ifdef DEBUG
cout << "entering InWorld" << endl;
#endif
cout << "Client Index: " << infoMgr->GetClientIndex() << endl;
font.SetSurface(surfaceMgr->Get("font"));
//debugging
Packet p;
p.meta.type = Packet::Type::PLAYER_NEW;
p.meta.clientIndex = infoMgr->GetClientIndex();
snprintf(p.playerInfo.handle, PACKET_STRING_SIZE, "%s", configUtil->CString("handle"));
snprintf(p.playerInfo.avatar, PACKET_STRING_SIZE, "%s", configUtil->CString("avatar"));
p.playerInfo.position.x = 50;
p.playerInfo.position.y = 50;
p.playerInfo.motion.x = 0;
p.playerInfo.motion.y = 0;
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
//request a sync
p.meta.type = Packet::Type::SYNCHRONIZE;
p.meta.clientIndex = infoMgr->GetClientIndex();
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
}
InWorld::~InWorld() {
#ifdef DEBUG
cout << "leaving InWorld" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void InWorld::FrameStart() {
//
}
void InWorld::Update(double delta) {
while(HandlePacket(popNetworkPacket()));
for (auto& it : playerCharacters) {
it.second.Update(delta);
}
}
void InWorld::FrameEnd() {
//
}
void InWorld::Render(SDL_Surface* const screen) {
clockFrameRate();
for (auto& it : playerCharacters) {
it.second.DrawTo(screen);
}
//since we're using this twice, make a tmp var
string fps = itos(getFrameRate());
font.DrawStringTo(fps, screen, screen->w - fps.size() * font.GetCharW(), 0);
}
//-------------------------
//Event handlers
//-------------------------
void InWorld::QuitEvent() {
//ensure that the client is disconnected properly
ExitGame();
SetNextScene(SceneList::QUIT);
}
void InWorld::MouseMotion(SDL_MouseMotionEvent const& motion) {
//
}
void InWorld::MouseButtonDown(SDL_MouseButtonEvent const& button) {
//
}
void InWorld::MouseButtonUp(SDL_MouseButtonEvent const& button) {
//
}
void InWorld::KeyDown(SDL_KeyboardEvent const& key) {
//general
switch(key.keysym.sym) {
case SDLK_ESCAPE:
ExitGame();
break;
}
//player movement
if (infoMgr->GetPlayerIndex() == -1) {
return;
}
switch(key.keysym.sym) {
case SDLK_w:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::NORTH);
SendState();
break;
case SDLK_s:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::SOUTH);
SendState();
break;
case SDLK_a:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::WEST);
SendState();
break;
case SDLK_d:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::EAST);
SendState();
break;
}
}
void InWorld::KeyUp(SDL_KeyboardEvent const& key) {
//player movement reversed
switch(key.keysym.sym) {
case SDLK_w:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::SOUTH);
SendState();
break;
case SDLK_s:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::NORTH);
SendState();
break;
case SDLK_a:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::EAST);
SendState();
break;
case SDLK_d:
playerCharacters[infoMgr->GetPlayerIndex()].MoveDirection(CardinalDirection::WEST);
SendState();
break;
}
}
//-------------------------
//Utilities
//-------------------------
int InWorld::HandlePacket(Packet p) {
switch(p.meta.type) {
case Packet::Type::NONE:
//DO NOTHING
return 0;
break;
case Packet::Type::PING:
//quick pong
p.meta.type = Packet::Type::PONG;
p.meta.clientIndex = infoMgr->GetClientIndex();
netUtil->Send(&p.meta.address, &p, sizeof(Packet));
break;
case Packet::Type::PONG:
//
break;
// case Packet::Type::BROADCAST_REQUEST:
// //
// break;
// case Packet::Type::BROADCAST_RESPONSE:
// //
// break;
// case Packet::Type::JOIN_REQUEST:
// //
// break;
// case Packet::Type::JOIN_RESPONSE:
// //
// break;
case Packet::Type::DISCONNECT:
HandleDisconnection(p);
break;
// case Packet::Type::SYNCHRONIZE:
// //
// break;
case Packet::Type::PLAYER_NEW:
AddPlayer(p);
break;
case Packet::Type::PLAYER_DELETE:
RemovePlayer(p);
break;
case Packet::Type::PLAYER_UPDATE:
UpdatePlayer(p);
break;
default:
throw(runtime_error("Failed to recognize the packet type: " + itos(int(p.meta.type))));
}
return 1;
}
void InWorld::Disconnect() {
Packet p;
//delete the player
p.meta.type = Packet::Type::PLAYER_DELETE;
p.meta.clientIndex = infoMgr->GetClientIndex();
p.playerInfo.index = infoMgr->GetPlayerIndex();
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
//disconnect
p.meta.type = Packet::Type::DISCONNECT;
p.meta.clientIndex = infoMgr->GetClientIndex();
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
netUtil->Unbind(GAME_CHANNEL);
//reset the client
infoMgr->ResetClientIndex();
infoMgr->ResetPlayerIndex();
}
void InWorld::ExitGame() {
Disconnect();
SetNextScene(SceneList::MAINMENU);
endQueueThread();
cout << "The game session has ended" << endl;
}
void InWorld::HandleDisconnection(Packet& disconnect) {
Disconnect();
SetNextScene(SceneList::MAINMENU);
endQueueThread();
cout << "You have been disconnected" << endl;
}
void InWorld::AddPlayer(Packet& p) {
if (playerCharacters.find(p.playerInfo.index) != playerCharacters.end()) {
throw(runtime_error("Duplicate players detected"));
}
//position
playerCharacters[p.playerInfo.index].SetPosition(p.playerInfo.position);
playerCharacters[p.playerInfo.index].SetMotion(p.playerInfo.motion);
//sprite
playerCharacters[p.playerInfo.index].GetSprite()->SetSurface(surfaceMgr->Get(p.playerInfo.avatar), 32, 48);
playerCharacters[p.playerInfo.index].FaceDirection();
//is it this player?
if (p.meta.clientIndex == infoMgr->GetClientIndex()) {
infoMgr->SetPlayerIndex(p.playerInfo.index);
}
//debugging
cout << "New player, index " << p.playerInfo.index << endl;
}
void InWorld::RemovePlayer(Packet& p) {
if (playerCharacters.find(p.playerInfo.index) == playerCharacters.end()) {
throw(runtime_error("Player to delete not found"));
}
playerCharacters.erase(p.playerInfo.index);
}
void InWorld::UpdatePlayer(Packet& p) {
if (playerCharacters.find(p.playerInfo.index) == playerCharacters.end()) {
AddPlayer(p);
return;
}
playerCharacters[p.playerInfo.index].SetPosition(p.playerInfo.position);
playerCharacters[p.playerInfo.index].SetMotion(p.playerInfo.motion);
playerCharacters[p.playerInfo.index].FaceDirection();
}
void InWorld::SendState() {
//send the state of this player's character
if (infoMgr->GetPlayerIndex() == -1) {
return;
}
Packet p;
p.meta.type = Packet::Type::PLAYER_UPDATE;
p.meta.clientIndex = infoMgr->GetClientIndex();
p.playerInfo.index = infoMgr->GetPlayerIndex();
p.playerInfo.position = playerCharacters[infoMgr->GetPlayerIndex()].GetPosition();
p.playerInfo.motion = playerCharacters[infoMgr->GetPlayerIndex()].GetMotion();
netUtil->Send(GAME_CHANNEL, &p, sizeof(Packet));
}
+88
View File
@@ -0,0 +1,88 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef INWORLD_HPP_
#define INWORLD_HPP_
#include "base_scene.hpp"
#include "defines.hpp"
#include "singleton.hpp"
#include "packet.hpp"
#include "network_queue.hpp"
#include "information_manager.hpp"
#include "player_character.hpp"
#include "config_utility.hpp"
#include "surface_manager.hpp"
#include "udp_network_utility.hpp"
#include "button.hpp"
#include "raster_font.hpp"
#include "frame_rate.hpp"
#include <map>
class InWorld : public BaseScene {
public:
//Public access members
InWorld();
~InWorld();
protected:
//Frame loop
void FrameStart();
void Update(double delta);
void FrameEnd();
void Render(SDL_Surface* const);
//Event handlers
void QuitEvent();
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//Utilities
int HandlePacket(Packet);
void Disconnect();
void ExitGame();
void HandleDisconnection(Packet&);
void AddPlayer(Packet&);
void RemovePlayer(Packet&);
void UpdatePlayer(Packet&);
void SendState();
//services
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
InformationManager* infoMgr = Singleton<InformationManager>::Get();
//members
RasterFont font;
std::map<int, PlayerCharacter> playerCharacters;
};
#endif
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,29 +19,22 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef MONSTERDATA_HPP_
#define MONSTERDATA_HPP_
#ifndef INFORMATIONMANAGER_HPP_
#define INFORMATIONMANAGER_HPP_
#include "entity.hpp"
#include <string>
class MonsterData: public Entity {
class InformationManager {
public:
MonsterData() = default;
~MonsterData() = default;
std::string SetAvatar(std::string);
int SetScriptReference(int);
std::string GetAvatar();
int GetScriptReference();
int SetClientIndex(int i) { return clientIndex = i; }
int GetClientIndex() { return clientIndex; }
void ResetClientIndex() { clientIndex = -1; }
//one player at a time
int SetPlayerIndex(int i) { return playerIndex = i; }
int GetPlayerIndex() { return playerIndex; }
void ResetPlayerIndex() { playerIndex = -1; }
private:
friend class MonsterManager;
std::string avatar;
int scriptRef;
int clientIndex = -1;
int playerIndex = -1;
};
#endif
#endif
+244
View File
@@ -0,0 +1,244 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "lobby.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Quick and dirty
//-------------------------
static std::string itos(int i) {
char buffer[20];
snprintf(buffer, 20, "%d", i);
return std::string(buffer);
}
//-------------------------
//Public access members
//-------------------------
Lobby::Lobby() {
#ifdef DEBUG
cout << "entering Lobby" << endl;
#endif
refreshButton.Setup(50, 50, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Refresh");
joinButton.Setup(50, 50 + surfaceMgr->Get("button")->h/3, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Join");
backButton.Setup(50, 50 + surfaceMgr->Get("button")->h/3 * 2, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Back");
font.SetSurface(surfaceMgr->Get("font"));
listBox.x = 280;
listBox.y = 50;
listBox.w = GetScreen()->w - listBox.x - 50;
listBox.h = font.GetCharH();
serverList.push_back({"foo",{0,0}});
serverList.push_back({"bar",{0,0}});
serverList.push_back({"foobar",{0,0}});
flushNetworkQueue();
beginQueueThread();
BroadcastNetwork();
}
Lobby::~Lobby() {
#ifdef DEBUG
cout << "leaving Lobby" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void Lobby::FrameStart() {
//
}
void Lobby::Update(double delta) {
while(HandlePacket(popNetworkPacket()));
}
void Lobby::FrameEnd() {
//
}
void Lobby::Render(SDL_Surface* const screen) {
refreshButton.DrawTo(screen);
joinButton.DrawTo(screen);
backButton.DrawTo(screen);
for (int i = 0; i < serverList.size(); i++) {
if (selectedServer == &serverList[i]) {
//draw the highlight box
SDL_Rect r = listBox;
r.y += i * font.GetCharH();
SDL_FillRect(screen, &r, SDL_MapRGB(screen->format, 255, 127, 39));
}
font.DrawStringTo(serverList[i].name, screen, listBox.x, listBox.y + i * font.GetCharH());
}
}
//-------------------------
//Event handlers
//-------------------------
void Lobby::MouseMotion(SDL_MouseMotionEvent const& motion) {
refreshButton.MouseMotion(motion);
joinButton.MouseMotion(motion);
backButton.MouseMotion(motion);
}
void Lobby::MouseButtonDown(SDL_MouseButtonEvent const& button) {
refreshButton.MouseButtonDown(button);
joinButton.MouseButtonDown(button);
backButton.MouseButtonDown(button);
}
void Lobby::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (refreshButton.MouseButtonUp(button) == Button::State::HOVER) {
BroadcastNetwork();
selectedServer = nullptr;
}
else if (joinButton.MouseButtonUp(button) == Button::State::HOVER) {
if (selectedServer) {
ConnectToServer(selectedServer);
selectedServer = nullptr;
}
}
else if (backButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::MAINMENU);
endQueueThread();
selectedServer = nullptr;
}
else if (
//clicked within bounds TODO: make the damn collision system
button.x > listBox.x &&
button.y > listBox.y &&
button.x < listBox.x + listBox.w &&
button.y < listBox.y + (listBox.h * serverList.size())
)
{
//selecting a server
selectedServer = &serverList[(button.y - listBox.y) / listBox.h];
}
else {
//lose focus on a server
selectedServer = nullptr;
}
}
void Lobby::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
SetNextScene(SceneList::MAINMENU);
break;
}
}
void Lobby::KeyUp(SDL_KeyboardEvent const& key) {
//
}
//-------------------------
//Utilities
//-------------------------
int Lobby::HandlePacket(Packet p) {
switch(p.meta.type) {
case Packet::Type::NONE:
//DO NOTHING
return 0;
break;
case Packet::Type::PING:
//quick pong
p.meta.type = Packet::Type::PONG;
netUtil->Send(&p.meta.address, &p, sizeof(Packet));
break;
case Packet::Type::PONG:
//
break;
// case Packet::Type::BROADCAST_REQUEST:
// //
// break;
case Packet::Type::BROADCAST_RESPONSE:
PushServer(p);
break;
// case Packet::Type::JOIN_REQUEST:
// //
// break;
case Packet::Type::JOIN_RESPONSE:
BeginGame(p);
break;
// case Packet::Type::DISCONNECT:
// //
// break;
// case Packet::Type::SYNCHRONIZE:
// //
// break;
// case Packet::Type::PLAYER_NEW:
// //
// break;
// case Packet::Type::PLAYER_DELETE:
// //
// break;
// case Packet::Type::PLAYER_UPDATE:
// //
// break;
default:
throw(runtime_error("Failed to recognize the packet type: " + itos(int(p.meta.type))));
}
return 1;
}
void Lobby::BroadcastNetwork() {
Packet p;
p.meta.type = Packet::Type::BROADCAST_REQUEST;
netUtil->Send("255.255.255.255", configUtil->Int("server.port"), &p, sizeof(Packet));
serverList.clear();
}
void Lobby::PushServer(Packet& bcast) {
ServerEntry entry;
entry.name = bcast.serverInfo.name;
entry.address = bcast.meta.address;
serverList.push_back(entry);
}
void Lobby::ConnectToServer(ServerEntry* server) {
//_attempt_ to connect to a server
if (!server) {
throw(runtime_error("No server received"));
}
Packet p;
p.meta.type = Packet::Type::JOIN_REQUEST;
netUtil->Send(&server->address, reinterpret_cast<void*>(&p), sizeof(Packet));
}
void Lobby::BeginGame(Packet& response) {
//should be downloading the resources here as well
infoMgr->SetClientIndex(response.meta.clientIndex);
netUtil->Bind(&response.meta.address, GAME_CHANNEL);
SetNextScene(SceneList::INWORLD);
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,36 +19,43 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef LOBBYMENU_HPP_
#define LOBBYMENU_HPP_
#ifndef LOBBY_HPP_
#define LOBBY_HPP_
//graphics & ui
#include "image.hpp"
#include "raster_font.hpp"
#include "button.hpp"
#include "bounding_box.hpp"
//utilities
#include "config_utility.hpp"
#include "udp_network_utility.hpp"
#include "serial_packet.hpp"
//client
#include "base_scene.hpp"
//STL
#include <vector>
#include "defines.hpp"
#include "singleton.hpp"
class LobbyMenu : public BaseScene {
#include "packet.hpp"
#include "network_queue.hpp"
#include "information_manager.hpp"
#include "config_utility.hpp"
#include "surface_manager.hpp"
#include "udp_network_utility.hpp"
#include "button.hpp"
#include "raster_font.hpp"
#include <vector>
#include <string>
struct ServerEntry {
std::string name;
IPaddress address;
//TODO: player count
};
class Lobby : public BaseScene {
public:
//Public access members
LobbyMenu(int* const argClientIndex, int* const argAccountIndex);
~LobbyMenu();
Lobby();
~Lobby();
protected:
//Frame loop
void FrameStart();
void Update();
void Update(double delta);
void FrameEnd();
void Render(SDL_Surface* const);
@@ -59,47 +66,28 @@ protected:
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//Network handlers
void HandlePacket(SerialPacket* const);
void HandleBroadcastResponse(ServerPacket* const);
void HandleJoinResponse(ClientPacket* const);
void HandleLoginResponse(ClientPacket* const);
void HandleJoinRejection(TextPacket* const);
void HandleLoginRejection(TextPacket* const);
//utilities
int HandlePacket(Packet);
void BroadcastNetwork();
void PushServer(Packet&);
void ConnectToServer(ServerEntry*);
void BeginGame(Packet&);
//server control
void SendBroadcastRequest();
void SendJoinRequest();
void SendLoginRequest();
//shared parameters
ConfigUtility& config = ConfigUtility::GetSingleton();
UDPNetworkUtility& network = UDPNetworkUtility::GetSingleton();
int& clientIndex;
int& accountIndex;
//services
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
InformationManager* infoMgr = Singleton<InformationManager>::Get();
//members
Image image;
Button refreshButton;
Button joinButton;
Button backButton;
RasterFont font;
Button search;
Button join;
Button back;
//server list
struct ServerInformation {
IPaddress address;
std::string name;
int playerCount;
int version;
bool compatible;
};
std::vector<ServerInformation> serverInfo;
//NOTE: a terrible hack
//I'd love a proper gui system for this
BoundingBox listBox;
ServerInformation* selection = nullptr;
SDL_Rect listBox;
std::vector<ServerEntry> serverList;
ServerEntry* selectedServer = nullptr;
};
#endif
+12 -23
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -21,38 +21,27 @@
*/
#include "client_application.hpp"
//singletons
#include "config_utility.hpp"
#include "udp_network_utility.hpp"
#include <stdexcept>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
int main(int, char**) {
#ifdef DEBUG
cout << "Beginning program" << endl;
#endif
try {
//create the singletons
ConfigUtility::CreateSingleton();
UDPNetworkUtility::CreateSingleton();
//call the server's routines
ClientApplication::CreateSingleton();
ClientApplication& app = ClientApplication::GetSingleton();
app.Init(argc, argv);
ClientApplication app;
app.Init();
app.Proc();
app.Quit();
ClientApplication::DeleteSingleton();
//delete the singletons
ConfigUtility::DeleteSingleton();
UDPNetworkUtility::DeleteSingleton();
}
catch(exception& e) {
cerr << "Fatal exception thrown: " << e.what() << endl;
cerr << "Fatal error: " << e.what() << endl;
return 1;
}
#ifdef DEBUG
cout << "Clean exit" << endl;
#endif
return 0;
}
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -21,47 +21,27 @@
*/
#include "main_menu.hpp"
#include "config_utility.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
MainMenu::MainMenu() {
ConfigUtility& config = ConfigUtility::GetSingleton();
//setup the utility objects
image.LoadSurface(config["dir.interface"] + "button_menu.bmp");
image.SetClipH(image.GetClipH()/3);
font.LoadSurface(config["dir.fonts"] + "pk_white_8.bmp");
//pass the utility objects
startButton.SetImage(&image);
startButton.SetFont(&font);
optionsButton.SetImage(&image);
optionsButton.SetFont(&font);
quitButton.SetImage(&image);
quitButton.SetFont(&font);
//set the button positions
startButton.SetX(50);
startButton.SetY(50 + image.GetClipH() * 0);
optionsButton.SetX(50);
optionsButton.SetY(50 + image.GetClipH() * 1);
quitButton.SetX(50);
quitButton.SetY(50 + image.GetClipH() * 2);
//set the button texts
startButton.SetText("Start");
optionsButton.SetText("Options");
quitButton.SetText("Quit");
//debug
//
#ifdef DEBUG
cout << "entering MainMenu" << endl;
#endif
startButton.Setup(50, 50, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Start");
optionsButton.Setup(50, 50 + surfaceMgr->Get("button")->h/3, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Options");
quitButton.Setup(50, 50 + surfaceMgr->Get("button")->h/3 * 2, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Quit");
}
MainMenu::~MainMenu() {
//
#ifdef DEBUG
cout << "leaving MainMenu" << endl;
#endif
}
//-------------------------
@@ -72,7 +52,7 @@ void MainMenu::FrameStart() {
//
}
void MainMenu::Update() {
void MainMenu::Update(double delta) {
//
}
@@ -103,12 +83,11 @@ void MainMenu::MouseButtonDown(SDL_MouseButtonEvent const& button) {
}
void MainMenu::MouseButtonUp(SDL_MouseButtonEvent const& button) {
//TODO: Buttons should only register as "selected" when the left button is used
if (startButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::LOBBYMENU);
SetNextScene(SceneList::LOBBY);
}
if (optionsButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::OPTIONSMENU);
SetNextScene(SceneList::OPTIONSCREEN);
}
if (quitButton.MouseButtonUp(button) == Button::State::HOVER) {
QuitEvent();
@@ -116,9 +95,9 @@ void MainMenu::MouseButtonUp(SDL_MouseButtonEvent const& button) {
}
void MainMenu::KeyDown(SDL_KeyboardEvent const& key) {
//
}
void MainMenu::KeyUp(SDL_KeyboardEvent const& key) {
//
switch(key.keysym.sym) {
case SDLK_ESCAPE:
QuitEvent();
break;
}
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -23,34 +23,32 @@
#define MAINMENU_HPP_
#include "base_scene.hpp"
#include "singleton.hpp"
#include "image.hpp"
#include "raster_font.hpp"
#include "surface_manager.hpp"
#include "button.hpp"
class MainMenu : public BaseScene {
public:
//Public access members
/* Public access members */
MainMenu();
~MainMenu();
protected:
//Frame loop
/* Frame loop */
void FrameStart();
void Update();
void Update(double delta);
void FrameEnd();
void Render(SDL_Surface* const);
//Event handlers
/* Event handlers */
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//members
Image image;
RasterFont font;
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
Button startButton;
Button optionsButton;
Button quitButton;
+8 -18
View File
@@ -1,23 +1,15 @@
#include directories
INCLUDES+=. entities scenes ../common/debugging ../common/gameplay ../common/graphics ../common/map ../common/network ../common/network/packet_types ../common/ui ../common/utilities
#libraries
#the order of the $(LIBS) is important, at least for MinGW
LIBS+=client.a ../libcommon.a -lSDL_net
ifeq ($(OS),Windows_NT)
LIBS+=-lwsock32 -liphlpapi -lmingw32
endif
LIBS+=-lSDLmain -lSDL
#flags
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#config
LOCALLIBS=../lib/libCommon.a
LIB=$(LOCALLIBS) -lSDL_net -lwsock32 -liphlpapi -lmingw32 -lSDLmain -lSDL
INCLUDES=../common
CXXFLAGS+=-std=c++11 -DDEBUG $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
SRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.cpp=.o))
#output
OUTDIR=../out
@@ -25,9 +17,7 @@ OUT=$(addprefix $(OUTDIR)/,client)
#targets
all: $(OBJ) $(OUT)
$(MAKE) -C entities
$(MAKE) -C scenes
$(CXX) $(CXXFLAGS) -o $(OUT) $(OBJ) $(LIBS)
$(CXX) $(CXXFLAGS) -o $(OUT) $(OBJ) $(LIB)
$(OBJ): | $(OBJDIR)
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,86 +19,59 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "options_menu.hpp"
#include "option_screen.hpp"
#include "config_utility.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
OptionsMenu::OptionsMenu() {
ConfigUtility& config = ConfigUtility::GetSingleton();
//setup the utility objects
image.LoadSurface(config["dir.interface"] + "button_menu.bmp");
image.SetClipH(image.GetClipH()/3);
font.LoadSurface(config["dir.fonts"] + "pk_white_8.bmp");
//pass the utility objects
backButton.SetImage(&image);
backButton.SetFont(&font);
//set the button positions
backButton.SetX(50);
backButton.SetY(50 + image.GetClipH() * 0);
//set the button texts
backButton.SetText("Back");
OptionScreen::OptionScreen() {
#ifdef DEBUG
cout << "entering OptionScreen" << endl;
#endif
backButton.Setup(50, 50, surfaceMgr->Get("button"), surfaceMgr->Get("font"), "Back");
}
OptionsMenu::~OptionsMenu() {
//
OptionScreen::~OptionScreen() {
#ifdef DEBUG
cout << "leaving OptionScreen" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void OptionsMenu::FrameStart() {
//
}
void OptionsMenu::Update() {
//
}
void OptionsMenu::FrameEnd() {
//
}
void OptionsMenu::Render(SDL_Surface* const screen) {
void OptionScreen::Render(SDL_Surface* const screen) {
backButton.DrawTo(screen);
font.DrawStringTo("Oh, were you looking for the options screen?", screen, 50, 30);
}
//-------------------------
//Event handlers
//-------------------------
void OptionsMenu::MouseMotion(SDL_MouseMotionEvent const& motion) {
void OptionScreen::MouseMotion(SDL_MouseMotionEvent const& motion) {
backButton.MouseMotion(motion);
}
void OptionsMenu::MouseButtonDown(SDL_MouseButtonEvent const& button) {
void OptionScreen::MouseButtonDown(SDL_MouseButtonEvent const& button) {
backButton.MouseButtonDown(button);
}
void OptionsMenu::MouseButtonUp(SDL_MouseButtonEvent const& button) {
void OptionScreen::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (backButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::MAINMENU);
}
}
void OptionsMenu::KeyDown(SDL_KeyboardEvent const& key) {
void OptionScreen::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
SetNextScene(SceneList::MAINMENU);
break;
break;
}
}
void OptionsMenu::KeyUp(SDL_KeyboardEvent const& key) {
//
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,48 +19,33 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef DISCONNECTEDSCREEN_HPP_
#define DISCONNECTEDSCREEN_HPP_
#ifndef OPTIONSCREEN_HPP_
#define OPTIONSCREEN_HPP_
//graphics
#include "image.hpp"
#include "raster_font.hpp"
#include "base_scene.hpp"
#include "singleton.hpp"
#include "surface_manager.hpp"
#include "button.hpp"
//client
#include "base_scene.hpp"
//std namespace
#include <chrono>
class DisconnectedScreen : public BaseScene {
class OptionScreen : public BaseScene {
public:
//Public access members
DisconnectedScreen();
~DisconnectedScreen();
/* Public access members */
OptionScreen();
~OptionScreen();
protected:
//Frame loop
void Update();
/* Frame loop */
void Render(SDL_Surface* const);
//Event handlers
void QuitEvent();
/* Event handlers */
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//graphics
Image image;
RasterFont font;
//UI
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
Button backButton;
//auto return
std::chrono::steady_clock::time_point startTick;
};
#endif
+114
View File
@@ -0,0 +1,114 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "player_character.hpp"
void PlayerCharacter::Update(double delta) {
if (limitSpeed) {
constexpr double d = 1.0/sqrt(2);
position += motion * delta * d;
}
else {
position += motion * delta;
}
sprite.Update(delta);
}
void PlayerCharacter::MoveDirection(CardinalDirection cd) {
//shift the movement in this direction
switch(cd) {
case CardinalDirection::NORTH:
if (motion.y >= 0) {
motion.y -= WALKING_SPEED;
}
break;
case CardinalDirection::SOUTH:
if (motion.y <= 0) {
motion.y += WALKING_SPEED;
}
break;
case CardinalDirection::WEST:
if (motion.x >= 0) {
motion.x -= WALKING_SPEED;
}
break;
case CardinalDirection::EAST:
if (motion.x <= 0) {
motion.x += WALKING_SPEED;
}
break;
}
//face the correct direction
FaceDirection();
}
void PlayerCharacter::FaceDirection(CardinalDirection cd) {
switch(cd) {
case CardinalDirection::NORTH:
sprite.SetCurrentStrip(1);
break;
case CardinalDirection::SOUTH:
sprite.SetCurrentStrip(0);
break;
case CardinalDirection::WEST:
sprite.SetCurrentStrip(2);
break;
case CardinalDirection::EAST:
sprite.SetCurrentStrip(3);
break;
}
}
void PlayerCharacter::FaceDirection() {
//base the direction on the character's movement
if (motion.y < 0) {
FaceDirection(CardinalDirection::NORTH);
}
if (motion.y > 0) {
FaceDirection(CardinalDirection::SOUTH);
}
if (motion.x < 0) {
FaceDirection(CardinalDirection::WEST);
}
if (motion.x > 0) {
FaceDirection(CardinalDirection::EAST);
}
CheckSpeed();
}
void PlayerCharacter::CheckSpeed() {
//diagonal
if (motion.x != 0 && motion.y != 0) {
sprite.SetDelay(0.1);
limitSpeed = true;
}
//cardinal
else if (motion != 0) {
sprite.SetDelay(0.1);
limitSpeed = false;
}
//not moving
else {
sprite.SetDelay(0);
sprite.SetCurrentFrame(0);
limitSpeed = false;
}
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,44 +19,45 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef ENTITY_HPP_
#define ENTITY_HPP_
#ifndef PLAYERCHARACTER_HPP_
#define PLAYERCHARACTER_HPP_
#include "bounding_box.hpp"
#include "sprite_sheet.hpp"
#include "vector2.hpp"
#include "sprite_sheet.hpp"
#include "defines.hpp"
//The base class for all objects in the world
class Entity {
class PlayerCharacter {
public:
virtual void Update();
virtual void DrawTo(SDL_Surface* const, int camX, int camY);
PlayerCharacter() = default;
~PlayerCharacter() = default;
void Update(double delta);
void MoveDirection(CardinalDirection);
void FaceDirection(CardinalDirection);
void FaceDirection();
void DrawTo(SDL_Surface* const dest) { sprite.DrawTo(dest, position.x, position.y); }
//accessors and mutators
Vector2 SetPosition(Vector2 v) { return position = v; }
Vector2 ShiftPosition(Vector2 v) { return position += v; }
Vector2 GetPosition() { return position; }
Vector2 SetMotion(Vector2 v) { return motion = v; }
Vector2 ShiftMotion(Vector2 v) { return motion += v; }
Vector2 GetMotion() { return motion; }
SpriteSheet* GetSprite() { return &sprite; }
private:
void CheckSpeed();
//accessors & mutators
int SetEntityIndex(int i);
int SetRoomIndex(int i);
Vector2 SetOrigin(Vector2 v);
Vector2 SetMotion(Vector2 v);
BoundingBox SetBounds(BoundingBox b) { return bounds = b; }
int GetEntityIndex();
int GetRoomIndex();
Vector2 GetOrigin();
Vector2 GetMotion();
BoundingBox GetBounds() { return bounds; }
protected:
Entity() = default;
~Entity() = default;
SpriteSheet sprite;
int entityIndex = -1;
int roomIndex = -1;
Vector2 origin;
Vector2 position;
Vector2 motion;
BoundingBox bounds;
SpriteSheet sprite;
//for moving diagonal
bool limitSpeed = false;
};
#endif
#endif
+6 -6
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -29,12 +29,12 @@ enum class SceneList {
FIRST,
//custom indexes
SPLASHSCREEN,
MAINMENU,
OPTIONSMENU,
LOBBYMENU,
INCOMBAT,
INWORLD,
DISCONNECTEDSCREEN,
LOBBY,
MAINMENU,
OPTIONSCREEN,
SPLASHSCREEN,
};
#endif
-116
View File
@@ -1,116 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "disconnected_screen.hpp"
#include "channels.hpp"
#include "config_utility.hpp"
#include "udp_network_utility.hpp"
#include <stdexcept>
//-------------------------
//Public access members
//-------------------------
DisconnectedScreen::DisconnectedScreen() {
ConfigUtility& config = ConfigUtility::GetSingleton();
//setup the utility objects
image.LoadSurface(config["dir.interface"] + "button_menu.bmp");
image.SetClipH(image.GetClipH()/3);
font.LoadSurface(config["dir.fonts"] + "pk_white_8.bmp");
//pass the utility objects
backButton.SetImage(&image);
backButton.SetFont(&font);
//set the button positions
backButton.SetX(50);
backButton.SetY(50 + image.GetClipH() * 0);
//set the button texts
backButton.SetText("Back");
//full reset
UDPNetworkUtility::GetSingleton().Unbind(Channels::SERVER);
//auto return
startTick = std::chrono::steady_clock::now();
}
DisconnectedScreen::~DisconnectedScreen() {
//
}
//-------------------------
//Frame loop
//-------------------------
void DisconnectedScreen::Update() {
if (std::chrono::steady_clock::now() - startTick > std::chrono::duration<int>(10)) {
SetNextScene(SceneList::MAINMENU);
}
//Eat incoming packets
while(UDPNetworkUtility::GetSingleton().Receive());
}
void DisconnectedScreen::Render(SDL_Surface* const screen) {
ConfigUtility& config = ConfigUtility::GetSingleton();
backButton.DrawTo(screen);
font.DrawStringTo(config["client.disconnectMessage"], screen, 50, 30);
}
//-------------------------
//Event handlers
//-------------------------
void DisconnectedScreen::QuitEvent() {
SetNextScene(SceneList::QUIT);
}
void DisconnectedScreen::MouseMotion(SDL_MouseMotionEvent const& motion) {
backButton.MouseMotion(motion);
}
void DisconnectedScreen::MouseButtonDown(SDL_MouseButtonEvent const& button) {
backButton.MouseButtonDown(button);
}
void DisconnectedScreen::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (backButton.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::MAINMENU);
}
}
void DisconnectedScreen::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
SetNextScene(SceneList::MAINMENU);
break;
}
}
void DisconnectedScreen::KeyUp(SDL_KeyboardEvent const& key) {
//
}
-558
View File
@@ -1,558 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "in_world.hpp"
#include "channels.hpp"
#include "utility.hpp"
#include "config_utility.hpp"
#include <stdexcept>
#include <algorithm>
#include <cmath>
#include <iostream>
//-------------------------
//Public access members
//-------------------------
InWorld::InWorld(int* const argClientIndex, int* const argAccountIndex):
clientIndex(*argClientIndex),
accountIndex(*argAccountIndex)
{
ConfigUtility& config = ConfigUtility::GetSingleton();
//setup the utility objects
buttonImage.LoadSurface(config["dir.interface"] + "button_menu.bmp");
buttonImage.SetClipH(buttonImage.GetClipH()/3);
font.LoadSurface(config["dir.fonts"] + "pk_white_8.bmp");
//pass the utility objects
disconnectButton.SetImage(&buttonImage);
disconnectButton.SetFont(&font);
shutDownButton.SetImage(&buttonImage);
shutDownButton.SetFont(&font);
//set the button positions
disconnectButton.SetX(50);
disconnectButton.SetY(50 + buttonImage.GetClipH() * 0);
shutDownButton.SetX(50);
shutDownButton.SetY(50 + buttonImage.GetClipH() * 1);
//set the button texts
disconnectButton.SetText("Disconnect");
shutDownButton.SetText("Shut Down");
//load the tilesheet
//TODO: add the tilesheet to the map system?
//TODO: Tile size and tile sheet should be loaded elsewhere
tileSheet.Load(config["dir.tilesets"] + "overworld.bmp", 32, 32);
//send this player's character info
// CharacterPacket newPacket;
// newPacket.type = SerialPacketType::CHARACTER_NEW;
// strncpy(newPacket.handle, config["client.handle"].c_str(), PACKET_STRING_SIZE);
// strncpy(newPacket.avatar, config["client.avatar"].c_str(), PACKET_STRING_SIZE);
// newPacket.accountIndex = accountIndex;
// network.SendTo(Channels::SERVER, &newPacket);
//request a sync
// RequestSynchronize();
//debug
//
}
InWorld::~InWorld() {
//
}
//-------------------------
//Frame loop
//-------------------------
void InWorld::FrameStart() {
//
}
void InWorld::Update() {
//suck in and process all waiting packets
SerialPacket* packetBuffer = reinterpret_cast<SerialPacket*>(new char[MAX_PACKET_SIZE]);
while(network.Receive(packetBuffer)) {
HandlePacket(packetBuffer);
}
delete reinterpret_cast<char*>(packetBuffer);
//update the characters
for (auto& it : characterMap) {
it.second.Update();
}
//check the map
UpdateMap();
//skip the rest
if (!localCharacter) {
return;
}
//check for collisions with the map
BoundingBox wallBounds = {0, 0, tileSheet.GetTileW(), tileSheet.GetTileH()};
const int xCount = localCharacter->GetBounds().w / wallBounds.w + 1;
const int yCount = localCharacter->GetBounds().h / wallBounds.h + 1;
for (int i = -1; i <= xCount; ++i) {
for (int j = -1; j <= yCount; ++j) {
//set the wall's position
wallBounds.x = wallBounds.w * i + snapToBase((double)wallBounds.w, localCharacter->GetOrigin().x);
wallBounds.y = wallBounds.h * j + snapToBase((double)wallBounds.h, localCharacter->GetOrigin().y);
if (!regionPager.GetSolid(wallBounds.x / wallBounds.w, wallBounds.y / wallBounds.h)) {
continue;
}
if ((localCharacter->GetOrigin() + localCharacter->GetBounds()).CheckOverlap(wallBounds)) {
localCharacter->SetOrigin(localCharacter->GetOrigin() - (localCharacter->GetMotion()));
localCharacter->SetMotion({0,0});
localCharacter->CorrectSprite();
SendPlayerUpdate();
}
}
}
//update the camera (following the player)
camera.x = localCharacter->GetOrigin().x - camera.marginX;
camera.y = localCharacter->GetOrigin().y - camera.marginY;
//check the connection
if (Clock::now() - lastBeat > std::chrono::seconds(3)) {
if (attemptedBeats > 2) {
RequestDisconnect();
SetNextScene(SceneList::DISCONNECTEDSCREEN);
ConfigUtility::GetSingleton()["client.disconnectMessage"] = "Error: Lost connection to the server";
}
ServerPacket newPacket;
newPacket.type = SerialPacketType::PING;
network.SendTo(Channels::SERVER, &newPacket);
attemptedBeats++;
lastBeat = Clock::now();
}
}
void InWorld::FrameEnd() {
//
}
void InWorld::RenderFrame() {
// SDL_FillRect(GetScreen(), 0, 0);
Render(GetScreen());
SDL_Flip(GetScreen());
fps.Calculate();
}
void InWorld::Render(SDL_Surface* const screen) {
//draw the map
for (std::list<Region>::iterator it = regionPager.GetContainer()->begin(); it != regionPager.GetContainer()->end(); it++) {
tileSheet.DrawRegionTo(screen, &(*it), camera.x, camera.y);
}
//draw characters
for (auto& it : characterMap) {
//BUG: #29 drawing order according to Y origin
//TODO: use a list of renderable objects
it.second.DrawTo(screen, camera.x, camera.y);
}
//draw UI
disconnectButton.DrawTo(screen);
shutDownButton.DrawTo(screen);
font.DrawStringTo(to_string_custom(fps.GetFrameRate()), screen, 0, 0);
}
//-------------------------
//Event handlers
//-------------------------
void InWorld::QuitEvent() {
//exit the game AND the server
RequestDisconnect();
SetNextScene(SceneList::QUIT);
}
void InWorld::MouseMotion(SDL_MouseMotionEvent const& motion) {
disconnectButton.MouseMotion(motion);
shutDownButton.MouseMotion(motion);
}
void InWorld::MouseButtonDown(SDL_MouseButtonEvent const& button) {
disconnectButton.MouseButtonDown(button);
shutDownButton.MouseButtonDown(button);
}
void InWorld::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (disconnectButton.MouseButtonUp(button) == Button::State::HOVER && button.button == SDL_BUTTON_LEFT) {
RequestDisconnect();
}
if (shutDownButton.MouseButtonUp(button) == Button::State::HOVER && button.button == SDL_BUTTON_LEFT) {
RequestShutDown();
}
}
void InWorld::KeyDown(SDL_KeyboardEvent const& key) {
if (!localCharacter) {
return;
}
//hotkeys
switch(key.keysym.sym) {
case SDLK_ESCAPE:
RequestDisconnect();
break;
}
//player movement
Vector2 motion = localCharacter->GetMotion();
switch(key.keysym.sym) {
case SDLK_LEFT:
motion.x -= CHARACTER_WALKING_SPEED;
break;
case SDLK_RIGHT:
motion.x += CHARACTER_WALKING_SPEED;
break;
case SDLK_UP:
motion.y -= CHARACTER_WALKING_SPEED;
break;
case SDLK_DOWN:
motion.y += CHARACTER_WALKING_SPEED;
break;
default:
return;
}
localCharacter->SetMotion(motion);
localCharacter->CorrectSprite();
SendPlayerUpdate();
}
void InWorld::KeyUp(SDL_KeyboardEvent const& key) {
if (!localCharacter) {
return;
}
//player movement
Vector2 motion = localCharacter->GetMotion();
switch(key.keysym.sym) {
//NOTE: The use of min/max here are to prevent awkward movements
case SDLK_LEFT:
motion.x = std::min(motion.x + CHARACTER_WALKING_SPEED, 0.0);
break;
case SDLK_RIGHT:
motion.x = std::max(motion.x - CHARACTER_WALKING_SPEED, 0.0);
break;
case SDLK_UP:
motion.y = std::min(motion.y + CHARACTER_WALKING_SPEED, 0.0);
break;
case SDLK_DOWN:
motion.y = std::max(motion.y - CHARACTER_WALKING_SPEED, 0.0);
break;
default:
return;
}
localCharacter->SetMotion(motion);
localCharacter->CorrectSprite();
SendPlayerUpdate();
}
//-------------------------
//Network handlers
//-------------------------
void InWorld::HandlePacket(SerialPacket* const argPacket) {
switch(argPacket->type) {
//heartbeat system
case SerialPacketType::PING: {
ServerPacket newPacket;
newPacket.type = SerialPacketType::PONG;
network.SendTo(argPacket->srcAddress, &newPacket);
}
break;
case SerialPacketType::PONG:
// HandlePong(static_cast<ServerPacket*>(argPacket));
break;
//game server connections
case SerialPacketType::LOGOUT_RESPONSE:
// HandleLogoutResponse(static_cast<ClientPacket*>(argPacket));
break;
case SerialPacketType::DISCONNECT_REQUEST:
// HandleDisconnectRequest(static_cast<ClientPacket*>(argPacket));
break;
case SerialPacketType::DISCONNECT_FORCED:
// HandleDisconnectForced(static_cast<ClientPacket*>(argPacket));
break;
//data management
case SerialPacketType::REGION_CONTENT:
// HandleRegionContent(static_cast<RegionPacket*>(argPacket));
break;
// case SerialPacketType::QUERY_CHARACTER_EXISTS:
// case SerialPacketType::QUERY_CHARACTER_STATS:
// case SerialPacketType::QUERY_CHARACTER_LOCATION:
//character management
// case SerialPacketType::CHARACTER_NEW:
// HandleCharacterNew(static_cast<CharacterPacket*>(argPacket));
// break;
// case SerialPacketType::CHARACTER_DELETE:
// HandleCharacterDelete(static_cast<CharacterPacket*>(argPacket));
// break;
// case SerialPacketType::CHARACTER_UPDATE:
// HandleCharacterUpdate(static_cast<CharacterPacket*>(argPacket));
// break;
// case SerialPacketType::CHARACTER_REJECTION:
// HandleCharacterRejection(static_cast<TextPacket*>(argPacket));
// break;
//enemy management
//TODO: enemy management
//TODO: text
//handle errors
default:
throw(std::runtime_error(std::string() + "Unknown SerialPacketType encountered in InWorld: " + to_string_custom(static_cast<int>(argPacket->type)) ));
break;
}
}
void InWorld::HandlePong(ServerPacket* const argPacket) {
if (network.GetIPAddress(Channels::SERVER)->host != argPacket->srcAddress.host) {
throw(std::runtime_error("Heartbeat message received from an unknown source"));
}
attemptedBeats = 0;
lastBeat = Clock::now();
}
void InWorld::HandleDisconnect(ClientPacket* const argPacket) {
//TODO: More needed in the disconnection
SetNextScene(SceneList::DISCONNECTEDSCREEN);
ConfigUtility::GetSingleton()["client.disconnectMessage"] = "You have been disconnected";
}
void InWorld::HandleCharacterNew(CharacterPacket* const argPacket) {
if (characterMap.find(argPacket->characterIndex) != characterMap.end()) {
throw(std::runtime_error("Cannot create duplicate characters"));
}
//create the character object
BaseCharacter& newCharacter = characterMap[argPacket->characterIndex];
//fill out the character's members
newCharacter.SetHandle(argPacket->handle);
newCharacter.SetAvatar(argPacket->avatar);
newCharacter.GetSprite()->LoadSurface(ConfigUtility::GetSingleton()["dir.sprites"] + newCharacter.GetAvatar(), 4, 4);
newCharacter.SetOrigin(argPacket->origin);
newCharacter.SetMotion(argPacket->motion);
newCharacter.SetBounds({
CHARACTER_BOUNDS_X,
CHARACTER_BOUNDS_Y,
CHARACTER_BOUNDS_WIDTH,
CHARACTER_BOUNDS_HEIGHT
});
// (*newCharacter.GetBaseStats()) = argPacket->stats;
//bookkeeping code
newCharacter.CorrectSprite();
//catch this client's player object
if (argPacket->accountIndex == accountIndex && !localCharacter) {
characterIndex = argPacket->characterIndex;
localCharacter = &newCharacter;
//setup the camera
camera.width = GetScreen()->w;
camera.height = GetScreen()->h;
//center on the player's character
camera.marginX = (GetScreen()->w / 2 - localCharacter->GetSprite()->GetImage()->GetClipW() / 2);
camera.marginY = (GetScreen()->h / 2 - localCharacter->GetSprite()->GetImage()->GetClipH() / 2);
}
}
void InWorld::HandleCharacterDelete(CharacterPacket* const argPacket) {
//TODO: authenticate when own character is being deleted (linked to a TODO in the server)
//catch this client's player object
if (argPacket->characterIndex == characterIndex) {
characterIndex = -1;
localCharacter = nullptr;
}
characterMap.erase(argPacket->characterIndex);
}
void InWorld::HandleCharacterUpdate(CharacterPacket* const argPacket) {
if (characterMap.find(argPacket->characterIndex) == characterMap.end()) {
HandleCharacterNew(argPacket);
return;
}
BaseCharacter& character = characterMap[argPacket->characterIndex];
//other characters moving
if (argPacket->characterIndex != characterIndex) {
character.SetOrigin(argPacket->origin);
character.SetMotion(argPacket->motion);
character.CorrectSprite();
}
}
void InWorld::HandleCharacterRejection(TextPacket* const argPacket) {
RequestDisconnect();
SetNextScene(SceneList::DISCONNECTEDSCREEN);
ConfigUtility& config = ConfigUtility::GetSingleton();
config["client.disconnectMessage"] = "Error: ";
config["client.disconnectMessage"] += argPacket->text;
}
void InWorld::HandleRegionContent(RegionPacket* const argPacket) {
//replace existing regions
regionPager.UnloadRegion(argPacket->x, argPacket->y);
regionPager.PushRegion(argPacket->region);
//clean up after the serial code
delete argPacket->region;
argPacket->region = nullptr;
}
//-------------------------
//Server control
//-------------------------
void InWorld::RequestSynchronize() {
// ClientPacket newPacket;
//request a sync
// newPacket.type = SerialPacketType::SYNCHRONIZE;
// newPacket.clientIndex = clientIndex;
// newPacket.accountIndex = accountIndex;
//TODO: location, range for sync request
// network.SendTo(Channels::SERVER, &newPacket);
}
void InWorld::SendPlayerUpdate() {
CharacterPacket newPacket;
//pack the packet
// newPacket.type = SerialPacketType::CHARACTER_UPDATE;
newPacket.characterIndex = characterIndex;
//NOTE: omitting the handle and avatar here
newPacket.accountIndex = accountIndex;
newPacket.roomIndex = 0; //TODO: room index
newPacket.origin = localCharacter->GetOrigin();
newPacket.motion = localCharacter->GetMotion();
// newPacket.stats = *localCharacter->GetBaseStats();
//TODO: gameplay components: equipment, items, buffs, debuffs
network.SendTo(Channels::SERVER, &newPacket);
}
void InWorld::RequestDisconnect() {
ClientPacket newPacket;
//send a disconnect request
newPacket.type = SerialPacketType::DISCONNECT_REQUEST;
newPacket.clientIndex = clientIndex;
newPacket.accountIndex = accountIndex;
network.SendTo(Channels::SERVER, &newPacket);
}
void InWorld::RequestShutDown() {
ClientPacket newPacket;
//send a shutdown request
newPacket.type = SerialPacketType::SHUTDOWN_REQUEST;
newPacket.clientIndex = clientIndex;
newPacket.accountIndex = accountIndex;
network.SendTo(Channels::SERVER, &newPacket);
}
void InWorld::RequestRegion(int roomIndex, int x, int y) {
RegionPacket packet;
//pack the region's data
packet.type = SerialPacketType::REGION_REQUEST;
packet.roomIndex = roomIndex;
packet.x = x;
packet.y = y;
network.SendTo(Channels::SERVER, &packet);
}
//-------------------------
//Utilities
//-------------------------
//TODO: convert this into a more generic function?; using parameters for the bounds
void InWorld::UpdateMap() {
//these represent the zone of regions that the client needs loaded, including the mandatory buffers (+1/-1)
int xStart = snapToBase(REGION_WIDTH, camera.x/tileSheet.GetTileW()) - REGION_WIDTH;
int xEnd = snapToBase(REGION_WIDTH, (camera.x+camera.width)/tileSheet.GetTileW()) + REGION_WIDTH;
int yStart = snapToBase(REGION_HEIGHT, camera.y/tileSheet.GetTileH()) - REGION_HEIGHT;
int yEnd = snapToBase(REGION_HEIGHT, (camera.y+camera.height)/tileSheet.GetTileH()) + REGION_HEIGHT;
//prune distant regions
for (std::list<Region>::iterator it = regionPager.GetContainer()->begin(); it != regionPager.GetContainer()->end(); /* EMPTY */) {
//check if the region is outside of this area
if (it->GetX() < xStart || it->GetX() > xEnd || it->GetY() < yStart || it->GetY() > yEnd) {
//clunky, but the alternative was time consuming
int tmpX = it->GetX();
int tmpY = it->GetY();
++it;
regionPager.UnloadRegion(tmpX, tmpY);
continue;
}
++it;
}
//request empty regions within this zone
for (int i = xStart; i <= xEnd; i += REGION_WIDTH) {
for (int j = yStart; j <= yEnd; j += REGION_HEIGHT) {
if (!regionPager.FindRegion(i, j)) {
RequestRegion(0, i, j);
}
}
}
}
-134
View File
@@ -1,134 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef INWORLD_HPP_
#define INWORLD_HPP_
//maps
#include "region_pager_base.hpp"
//networking
#include "udp_network_utility.hpp"
#include "serial_packet.hpp"
//graphics
#include "image.hpp"
#include "raster_font.hpp"
#include "button.hpp"
#include "tile_sheet.hpp"
//common
#include "frame_rate.hpp"
#include "base_character.hpp"
#include "base_monster.hpp"
//client
#include "base_scene.hpp"
//STL
#include <map>
#include <chrono>
class InWorld : public BaseScene {
public:
//Public access members
InWorld(int* const argClientIndex, int* const argAccountIndex);
~InWorld();
protected:
//Frame loop
void FrameStart();
void Update();
void FrameEnd();
void RenderFrame();
void Render(SDL_Surface* const);
//Event handlers
void QuitEvent();
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&);
void KeyDown(SDL_KeyboardEvent const&);
void KeyUp(SDL_KeyboardEvent const&);
//Network handlers
void HandlePacket(SerialPacket* const);
void HandlePong(ServerPacket* const);
void HandleDisconnect(ClientPacket* const);
void HandleCharacterNew(CharacterPacket* const);
void HandleCharacterDelete(CharacterPacket* const);
void HandleCharacterUpdate(CharacterPacket* const);
void HandleCharacterRejection(TextPacket* const);
void HandleRegionContent(RegionPacket* const);
//Server control
void RequestSynchronize();
void SendPlayerUpdate();
void RequestDisconnect();
void RequestShutDown();
void RequestRegion(int roomIndex, int x, int y);
//utilities
void UpdateMap();
//singleton shortcut
UDPNetworkUtility& network = UDPNetworkUtility::GetSingleton();
//indexes
int& clientIndex;
int& accountIndex;
int characterIndex = -1;
//graphics
Image buttonImage;
RasterFont font;
TileSheet tileSheet;
//map
RegionPagerBase regionPager;
//UI
Button disconnectButton;
Button shutDownButton;
FrameRate fps;
//the camera structure
struct {
int x = 0, y = 0;
int width = 0, height = 0;
int marginX = 0, marginY = 0;
} camera;
//game components
BaseCharacter* localCharacter = nullptr;
std::map<int, BaseCharacter> characterMap;
std::map<int, BaseMonster> monsterMap;
//heartbeat
//TODO: This needs it's own utility, for both InWorld and InCombat
typedef std::chrono::steady_clock Clock;
Clock::time_point lastBeat = Clock::now();
int attemptedBeats = 0;
};
#endif
-292
View File
@@ -1,292 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "lobby_menu.hpp"
#include "channels.hpp"
#include "utility.hpp"
#include <stdexcept>
//-------------------------
//Public access members
//-------------------------
LobbyMenu::LobbyMenu(int* const argClientIndex, int* const argAccountIndex):
clientIndex(*argClientIndex),
accountIndex(*argAccountIndex)
{
//preemptive reset
clientIndex = -1;
accountIndex = -1;
//setup the utility objects
image.LoadSurface(config["dir.interface"] + "button_menu.bmp");
image.SetClipH(image.GetClipH()/3);
font.LoadSurface(config["dir.fonts"] + "pk_white_8.bmp");
//pass the utility objects
search.SetImage(&image);
search.SetFont(&font);
join.SetImage(&image);
join.SetFont(&font);
back.SetImage(&image);
back.SetFont(&font);
//set the button positions
search.SetX(50);
search.SetY(50 + image.GetClipH() * 0);
join.SetX(50);
join.SetY(50 + image.GetClipH() * 1);
back.SetX(50);
back.SetY(50 + image.GetClipH() * 2);
//set the button texts
search.SetText("Search");
join.SetText("Join");
back.SetText("Back");
//set the server list's position
listBox = {300, 50, 200, font.GetCharH()};
//Eat incoming packets
while(network.Receive());
//Initial broadcast
SendBroadcastRequest();
}
LobbyMenu::~LobbyMenu() {
//
}
//-------------------------
//Frame loop
//-------------------------
void LobbyMenu::FrameStart() {
//
}
void LobbyMenu::Update() {
//suck in and process all waiting packets
SerialPacket* packetBuffer = reinterpret_cast<SerialPacket*>(new char[MAX_PACKET_SIZE]);
while(network.Receive(packetBuffer)) {
HandlePacket(packetBuffer);
}
delete reinterpret_cast<char*>(packetBuffer);
}
void LobbyMenu::FrameEnd() {
//
}
void LobbyMenu::Render(SDL_Surface* const screen) {
//TODO: I need a proper UI system for the entire client and the editor
//UI
search.DrawTo(screen);
join.DrawTo(screen);
back.DrawTo(screen);
//TODO: draw headers for the server list
for (int i = 0; i < serverInfo.size(); i++) {
//draw the selected server's highlight
if (selection == &serverInfo[i]) {
SDL_Rect r = {
(Sint16)listBox.x, (Sint16)listBox.y,
(Uint16)listBox.w, (Uint16)listBox.h
};
r.y += i * listBox.h;
SDL_FillRect(screen, &r, SDL_MapRGB(screen->format, 49, 150, 5));
}
//draw the server name
font.DrawStringTo(serverInfo[i].name, screen, listBox.x, listBox.y + i*listBox.h);
//draw the player count
font.DrawStringTo(to_string_custom(serverInfo[i].playerCount), screen, listBox.x + listBox.w, listBox.y + i*listBox.h);
//compatible?
if (!serverInfo[i].compatible) {
font.DrawStringTo("?", screen, listBox.x - font.GetCharW(), listBox.y + i*listBox.h);
}
//TODO: ping/delay?
}
}
//-------------------------
//Event handlers
//-------------------------
void LobbyMenu::MouseMotion(SDL_MouseMotionEvent const& motion) {
search.MouseMotion(motion);
join.MouseMotion(motion);
back.MouseMotion(motion);
}
void LobbyMenu::MouseButtonDown(SDL_MouseButtonEvent const& button) {
search.MouseButtonDown(button);
join.MouseButtonDown(button);
back.MouseButtonDown(button);
}
void LobbyMenu::MouseButtonUp(SDL_MouseButtonEvent const& button) {
if (search.MouseButtonUp(button) == Button::State::HOVER) {
SendBroadcastRequest();
}
else if (join.MouseButtonUp(button) == Button::State::HOVER && selection != nullptr && selection->compatible) {
SendJoinRequest();
}
else if (back.MouseButtonUp(button) == Button::State::HOVER) {
SetNextScene(SceneList::MAINMENU);
}
//has the user selected a server on the list?
BoundingBox tmpBox = listBox;
tmpBox.h *= serverInfo.size();
if (tmpBox.CheckOverlap({button.x, button.y})) {
selection = &serverInfo[(button.y - listBox.y)/listBox.h];
}
else {
selection = nullptr;
}
}
void LobbyMenu::KeyDown(SDL_KeyboardEvent const& key) {
switch(key.keysym.sym) {
case SDLK_ESCAPE:
SetNextScene(SceneList::MAINMENU);
break;
}
}
void LobbyMenu::KeyUp(SDL_KeyboardEvent const& key) {
//
}
//-------------------------
//Network handlers
//-------------------------
void LobbyMenu::HandlePacket(SerialPacket* const argPacket) {
switch(argPacket->type) {
//responses
case SerialPacketType::BROADCAST_RESPONSE:
HandleBroadcastResponse(static_cast<ServerPacket*>(argPacket));
break;
case SerialPacketType::JOIN_RESPONSE:
HandleJoinResponse(static_cast<ClientPacket*>(argPacket));
break;
case SerialPacketType::LOGIN_RESPONSE:
HandleLoginResponse(static_cast<ClientPacket*>(argPacket));
break;
//rejections
case SerialPacketType::JOIN_REJECTION:
HandleJoinRejection(static_cast<TextPacket*>(argPacket));
break;
case SerialPacketType::LOGIN_REJECTION:
HandleLoginRejection(static_cast<TextPacket*>(argPacket));
break;
//handle errors
default:
throw(std::runtime_error(std::string() + "Unknown SerialPacketType encountered in LobbyMenu: " + to_string_custom(static_cast<int>(argPacket->type)) ));
break;
}
}
void LobbyMenu::HandleBroadcastResponse(ServerPacket* const argPacket) {
//extract the data
ServerInformation server;
server.address = argPacket->srcAddress;
server.name = argPacket->name;
server.playerCount = argPacket->playerCount;
server.version = argPacket->version;
//Checking compatibility
server.compatible = server.version == NETWORK_VERSION;
//push
serverInfo.push_back(server);
}
void LobbyMenu::HandleJoinResponse(ClientPacket* const argPacket) {
//save the server's data
clientIndex = argPacket->clientIndex;
network.Bind(argPacket->srcAddress, Channels::SERVER);
//request login data
SendLoginRequest();
}
void LobbyMenu::HandleLoginResponse(ClientPacket* const argPacket) {
if (argPacket->clientIndex != clientIndex) {
throw(std::runtime_error("Client index invalid during login"));
}
accountIndex = argPacket->accountIndex;
SetNextScene(SceneList::INWORLD);
}
void LobbyMenu::HandleJoinRejection(TextPacket* const argPacket) {
//TODO: Better output for join rejection
}
void LobbyMenu::HandleLoginRejection(TextPacket* const argPacket) {
//TODO: Better output for login rejection
}
//-------------------------
//server control
//-------------------------
void LobbyMenu::SendBroadcastRequest() {
//broadcast to the network, or a specific server
ClientPacket packet;
packet.type = SerialPacketType::BROADCAST_REQUEST;
network.SendTo(config["server.host"].c_str(), config.Int("server.port"), &packet);
//reset the server list
serverInfo.clear();
selection = nullptr;
}
void LobbyMenu::SendJoinRequest() {
//pack the packet
ClientPacket packet;
packet.type = SerialPacketType::JOIN_REQUEST;
//join the selected server
network.SendTo(selection->address, &packet);
selection = nullptr;
}
void LobbyMenu::SendLoginRequest() {
//NOTE: high cohesion
ClientPacket packet;
packet.type = SerialPacketType::LOGIN_REQUEST;
packet.clientIndex = clientIndex;
strncpy(packet.username, config["client.username"].c_str(), PACKET_STRING_SIZE);
network.SendTo(Channels::SERVER, &packet);
}
-37
View File
@@ -1,37 +0,0 @@
#config
INCLUDES+=. .. ../entities ../../common/gameplay ../../common/graphics ../../common/map ../../common/network ../../common/network/packet_types ../../common/ui ../../common/utilities
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=..
OUT=$(addprefix $(OUTDIR)/,client.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
+86
View File
@@ -0,0 +1,86 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "splash_screen.hpp"
#include <iostream>
using namespace std;
//-------------------------
//Public access members
//-------------------------
SplashScreen::SplashScreen() {
#ifdef DEBUG
cout << "entering SplashScreen" << endl;
#endif
logo.SetSurface(surfaceMgr->Load("splash-logo", configUtil->String("logos") + "/krstudios.bmp"));
}
SplashScreen::~SplashScreen() {
surfaceMgr->Free("splash-logo");
#ifdef DEBUG
cout << "leaving SplashScreen" << endl;
#endif
}
//-------------------------
//Frame loop
//-------------------------
void SplashScreen::RunFrame(double delta) {
HandleEvents();
if (!loaded) {
//never repeat this
loaded = true;
//quick draw
RenderFrame();
LoadResources();
}
if (std::chrono::steady_clock::now() - start > std::chrono::duration<int>(1)) {
SetNextScene(SceneList::MAINMENU);
}
}
void SplashScreen::RenderFrame() {
SDL_FillRect(GetScreen(), 0, 0);
int x = (GetScreen()->w - logo.GetClipW()) / 2;
int y = (GetScreen()->h - logo.GetClipH()) / 2;
logo.DrawTo(GetScreen(), x, y);
SDL_Flip(GetScreen());
}
void SplashScreen::LoadResources() {
//standard
surfaceMgr->Load("font", configUtil->String("fonts") + "/pk_white_8.bmp");
surfaceMgr->Load("button", configUtil->String("interface") + "/button_menu.bmp");
//debugging
surfaceMgr->Load("elliot", configUtil->String("sprites") + "/elliot2.bmp");
surfaceMgr->Load("coa", configUtil->String("sprites") + "/coa2.bmp");
surfaceMgr->Load("flower", configUtil->String("sprites") + "/aniflower.bmp");
surfaceMgr->Load("terrain", configUtil->String("tilesets") + "/terrain.bmp");
//TODO
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -23,25 +23,31 @@
#define SPLASHSCREEN_HPP_
#include "base_scene.hpp"
#include "singleton.hpp"
#include "config_utility.hpp"
#include "surface_manager.hpp"
#include "image.hpp"
#include <chrono>
class SplashScreen : public BaseScene {
public:
//Public access members
/* Public access members */
SplashScreen();
~SplashScreen();
protected:
//Frame loop
void Update();
void Render(SDL_Surface* const);
/* Frame loop */
void RunFrame(double delta);
void RenderFrame();
void LoadResources();
//members
std::chrono::steady_clock::time_point startTick;
bool loaded = false;
ConfigUtility* configUtil = Singleton<ConfigUtility>::Get();
SurfaceManager* surfaceMgr = Singleton<SurfaceManager>::Get();
Image logo;
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
};
#endif
+27 -19
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -23,6 +23,13 @@
#include <stdexcept>
void Button::Setup(Sint16 i, Sint16 j, SDL_Surface* bg, SDL_Surface* fg, std::string t) {
x = i;
y = j;
SetSurfaces(bg, fg);
SetText(t);
}
Button::State Button::MouseMotion(SDL_MouseMotionEvent const& motion) {
return CalcState(motion.x, motion.y, motion.state & SDL_BUTTON_LMASK);
}
@@ -42,40 +49,41 @@ Button::State Button::MouseButtonUp(SDL_MouseButtonEvent const& button) {
}
void Button::DrawTo(SDL_Surface* const dest) {
if (!image || !font) {
throw(std::runtime_error("Surface not set for Button"));
}
image->SetClipY(state * image->GetClipH());
image->DrawTo(dest, x, y);
font->DrawStringTo(text, dest, textX + x, textY + y);
image.DrawTo(dest, x, y);
font.DrawStringTo(text, dest, textX + x, textY + y);
}
void Button::SetSurfaces(SDL_Surface* bg, SDL_Surface* fg) {
//graphical stuff
image.SetSurface(bg);
image.SetClipH(image.GetClipH() / 3); //3 phases, vertical storage
font.SetSurface(fg);
//reset textX & textY
SetText(text);
}
std::string Button::SetText(std::string t) {
if (!image || !font) {
throw(std::runtime_error("Surface not set for Button"));
}
//one line, cache the position
text = t;
textX = (image->GetClipW() / 2) - (font->GetCharW() * text.size() / 2);
textY = (image->GetClipH() / 2) - (font->GetCharH() / 2);
textX = (image.GetClipW() / 2) - (font.GetCharW() * text.size() / 2);
textY = (image.GetClipH() / 2) - (font.GetCharH() / 2);
return text;
}
Button::State Button::CalcState(Sint16 i, Sint16 j, bool leftPressed) {
if (!image || !font) {
throw(std::runtime_error("Surface not set for Button"));
}
//if out of bounds
if (i < x || i >= (x + image->GetClipW()) ||
j < y || j >= (y + image->GetClipH())
if (i < x || i > (x + image.GetClipW()) ||
j < y || j > (y + image.GetClipH())
) {
image.SetClipY(0);
return state = State::NORMAL;
}
if (leftPressed) {
image.SetClipY(image.GetClipH()*2);
return state = State::PRESSED;
}
else {
image.SetClipY(image.GetClipH());
return state = State::HOVER;
}
}
+22 -36
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -27,66 +27,52 @@
#include <string>
/* 3-phases, no toggle, centred text
* This class uses the size of the provided image as its bounds. Also,
* The provided image should be formatted correctly.
*
* The button's image should be divided into 3 sections virtucally,
* which act as the different button images. The clip width & height of the
* Image should be set manually, and the height should be 1/3 of the total
* graphical data.
*/
//3-phases, no toggle, centred text
class Button {
public:
enum State {
NORMAL = 0, HOVER = 1, PRESSED = 2
enum class State {
NORMAL, HOVER, PRESSED
};
Button() = default;
~Button() = default;
Button(Sint16 x, Sint16 y, SDL_Surface* bg, SDL_Surface* fg, std::string t = "") { Setup(x, y, bg, fg, t); }
//handle input
void Setup(Sint16 x, Sint16 y, SDL_Surface* bg, SDL_Surface* fg, std::string text = "");
//return the current state
State MouseMotion(SDL_MouseMotionEvent const&);
State MouseButtonDown(SDL_MouseButtonEvent const&);
State MouseButtonUp(SDL_MouseButtonEvent const&);
State GetState() const { return state; }
//yet another draw function
void DrawTo(SDL_Surface* const);
//accessors and mutators
Image* SetImage(Image* const ptr) { return image = ptr; }
Image* GetImage() { return image; }
RasterFont* SetFont(RasterFont* const ptr) { return font = ptr; }
RasterFont* GetFont() { return font; }
//simple accessors and mutators
Sint16 SetX(Sint16 i) { return x = i; }
Sint16 SetY(Sint16 i) { return y = i; }
Sint16 GetX() const { return x; }
Sint16 GetY() const { return y; }
Sint16 SetTextX(Sint16 i) { return textX = i; }
Sint16 SetTextY(Sint16 i) { return textY = i; }
Sint16 GetTextX() const { return textX; }
Sint16 GetTextY() const { return textY; }
void SetSurfaces(SDL_Surface* bg, SDL_Surface* fg);
State SetState(State s) { return state = s; }
State GetState() const { return state; }
std::string SetText(std::string);
std::string SetText(std::string t);
std::string GetText() const { return text; }
//raw access, be careful
Image* GetImage() { return &image; }
RasterFont* GetFont() { return &font; }
//debug
Sint16 GetTextX() const { return textX; }
Sint16 GetTextY() const { return textY; }
private:
State CalcState(Sint16 x, Sint16 y, bool leftPressed);
//point to the provided external objects
Image* image = nullptr;
RasterFont* font = nullptr;
//positions
Sint16 x = 0, y = 0;
Sint16 textX = 0, textY = 0;
//
Sint16 textX = 0, textY = 0; //prevent recalc every loop
Image image;
RasterFont font;
State state = State::NORMAL;
std::string text;
};
+76
View File
@@ -0,0 +1,76 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "config_utility.hpp"
#include <stdexcept>
#include <fstream>
using namespace std;
void ConfigUtility::Load(string fname) {
ifstream is(fname);
if (!is.is_open()) {
throw(runtime_error("Failed to open config file"));
}
string key, val;
for (;;) { //forever
//eat whitespace
while(isspace(is.peek()))
is.ignore();
//end of file
if (is.eof())
break;
//skip comment lines
if (is.peek() == '#') {
while(is.peek() != '\n' && !is.eof()) {
is.ignore();
}
continue;
}
//read in the pair
getline(is, key,'=');
getline(is, val);
//trim the strings at the start & end
while(key.size() && isspace(*key.begin())) key.erase(0, 1);
while(val.size() && isspace(*val.begin())) val.erase(0, 1);
while(key.size() && isspace(*(key.end()-1))) key.erase(key.end() - 1);
while(val.size() && isspace(*(val.end()-1))) val.erase(val.end() - 1);
//allow empty/wiped values
if (key.size() == 0) {
continue;
}
//save the pair
table[key] = val;
}
is.close();
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -22,37 +22,47 @@
#ifndef CONFIGUTILITY_HPP_
#define CONFIGUTILITY_HPP_
#include "singleton.hpp"
#include <map>
#include <string>
#include <cstdlib>
class ConfigUtility : public Singleton<ConfigUtility> {
class ConfigUtility {
public:
void Load(std::string fname, int argc = 0, char* argv[] = nullptr);
ConfigUtility() {}
ConfigUtility(std::string s) { Load(s); }
//convert to a type
std::string& String(std::string);
int Integer(std::string);
double Double(std::string);
bool Boolean(std::string);
void Load(std::string fname);
//shorthand
inline std::string& operator[](std::string s) { return configMap[s]; }
inline int Int(std::string s) { return Integer(s); }
inline bool Bool(std::string s) { return Boolean(s); }
std::string String(std::string s) {
return table[s];
}
const char* CString(std::string s) {
return table[s].c_str();
}
int Integer(std::string s) {
return atoi(table[s].c_str());
}
double Double(std::string s) {
return atof(table[s].c_str());
}
bool Boolean(std::string s) {
return table[s] == "true";
}
std::string& operator[](std::string s) {
return table[s];
}
int Int(std::string s) {
return Integer(s);
}
int Bool(std::string s) {
return Boolean(s);
}
std::map<std::string, std::string>* GetMap() {
return &table;
}
private:
typedef std::map<std::string, std::string> table_t;
friend Singleton<ConfigUtility>;
ConfigUtility() = default;
~ConfigUtility() = default;
table_t Read(std::string fname);
table_t configMap;
std::map<std::string, std::string> table;
};
#endif
-54
View File
@@ -1,54 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef TIMER_HPP_
#define TIMER_HPP_
#include <chrono>
#include <string>
#include <ostream>
class Timer {
public:
typedef std::chrono::high_resolution_clock Clock;
Timer();
Timer(std::string s);
~Timer() = default;
inline void Start();
inline void Stop();
//accessors and mutators
Clock::duration GetTime() { return timeSpan; }
std::string SetName(std::string s) { return name = s; }
std::string GetName() { return name; }
private:
std::string name;
Clock::time_point start;
Clock::duration timeSpan;
};
std::ostream& operator<<(std::ostream& os, Timer& t);
#endif
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,5 +19,16 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "base_monster.hpp"
#ifndef DEFINES_HPP_
#define DEFINES_HPP_
#define GAME_CHANNEL 0
#define CHAT_CHANNEL 1
#define WALKING_SPEED 140
enum class CardinalDirection {
NORTH, SOUTH, EAST, WEST
};
#endif
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,27 +19,26 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "timer.hpp"
#include "frame_rate.hpp"
Timer::Timer(): start(Timer::Clock::now()) {
//
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
static int frameCount = 0;
static int lastFrameRate = 0;
static Clock::time_point tick = Clock::now();
int clockFrameRate() {
frameCount++;
if (Clock::now() - tick >= std::chrono::duration<int>(1)) {
lastFrameRate = frameCount;
frameCount = 0;
tick = Clock::now();
}
return lastFrameRate;
}
Timer::Timer(std::string s): name(s), start(Timer::Clock::now()) {
//
}
void Timer::Start() {
start = Clock::now();
}
void Timer::Stop() {
timeSpan = Clock::now() - start;
}
std::ostream& operator<<(std::ostream& os, Timer& t) {
os << t.GetName() << ": ";
os << std::chrono::duration_cast<std::chrono::milliseconds>(t.GetTime()).count();
os << "ms";
return os;
int getFrameRate() {
return lastFrameRate;
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,11 +19,10 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef CHANNELS_HPP_
#define CHANNELS_HPP_
#ifndef FRAMERATE_HPP_
#define FRAMERATE_HPP_
enum Channels {
SERVER = 0
};
int clockFrameRate();
int getFrameRate();
#endif
-38
View File
@@ -1,38 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef CHARACTERDEFINES_HPP_
#define CHARACTERDEFINES_HPP_
#include <cmath>
//the speeds that the characters move
constexpr double CHARACTER_WALKING_SPEED = 2.24;
constexpr double CHARACTER_WALKING_MOD = 1.0/sqrt(2.0);
constexpr double CHARACTER_WALKING_NEGATIVE_MOD = 1.0 - CHARACTER_WALKING_MOD;
//the bounds for the character objects, mapped to the default sprites
constexpr int CHARACTER_BOUNDS_X = 0;
constexpr int CHARACTER_BOUNDS_Y = 16;
constexpr int CHARACTER_BOUNDS_WIDTH = 32;
constexpr int CHARACTER_BOUNDS_HEIGHT = 32;
#endif
-37
View File
@@ -1,37 +0,0 @@
#config
INCLUDES+=.
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=../..
OUT=$(addprefix $(OUTDIR)/,libcommon.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
-37
View File
@@ -1,37 +0,0 @@
#config
INCLUDES+=.
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=../..
OUT=$(addprefix $(OUTDIR)/,libcommon.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
-102
View File
@@ -1,102 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "sprite_sheet.hpp"
#include <stdexcept>
#include <sstream>
void SpriteSheet::Update(double delta) {
if (delay && (tick += delta) >= delay) {
if (++xIndex >= xCount) {
xIndex = 0;
}
tick = 0;
}
image.SetClipX(xIndex * image.GetClipW());
image.SetClipY(yIndex * image.GetClipH());
}
SDL_Surface* SpriteSheet::LoadSurface(std::string fname, Uint16 xCellCount, Uint16 yCellCount) {
image.LoadSurface(fname);
xCount = xCellCount;
yCount = yCellCount;
image.SetClipW(image.GetSurface()->w / xCount);
image.SetClipH(image.GetSurface()->h / yCount);
xIndex = yIndex = 0;
delay = tick = 0.0;
}
SDL_Surface* SpriteSheet::SetSurface(SDL_Surface* surface, Uint16 xCellCount, Uint16 yCellCount) {
image.SetSurface(surface);
xCount = xCellCount;
yCount = yCellCount;
image.SetClipW(image.GetSurface()->w / xCount);
image.SetClipH(image.GetSurface()->h / yCount);
xIndex = yIndex = 0;
delay = tick = 0.0;
}
void SpriteSheet::FreeSurface() {
image.FreeSurface();
xCount = yCount = 0;
xIndex = yIndex = 0;
delay = tick = 0.0;
}
Uint16 SpriteSheet::SetXCount(Uint16 i) {
xIndex = 0;
return xCount = i;
}
Uint16 SpriteSheet::SetYCount(Uint16 i) {
yIndex = 0;
return yCount = i;
}
Uint16 SpriteSheet::SetXIndex(Uint16 i) {
if (i > xCount) {
std::ostringstream os;
os << "Cannot set x index to " << i;
throw(std::invalid_argument(os.str()));
}
return xIndex = i;
}
Uint16 SpriteSheet::SetYIndex(Uint16 i) {
if (i > yCount) {
std::ostringstream os;
os << "Cannot set y index to " << i;
throw(std::invalid_argument(os.str()));
}
return yIndex = i;
}
double SpriteSheet::SetDelay(double d) {
tick = 0;
return delay = d;
}
+13 -81
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -22,88 +22,16 @@
#include "image.hpp"
#include <stdexcept>
#include <sstream>
Image& Image::operator=(Image const& rhs) {
//don't screw yourself
if (this == &rhs) {
return *this;
}
FreeSurface();
//Copy the other Image's stuff
surface = rhs.surface;
clip = rhs.clip;
local = false;
}
Image& Image::operator=(Image&& rhs) {
//don't screw yourself
if (this == &rhs) {
return *this;
}
FreeSurface();
//Steal the other Image's stuff
surface = rhs.surface;
clip = rhs.clip;
local = rhs.local;
rhs.surface = nullptr;
rhs.clip = {0, 0, 0, 0};
rhs.local = false;
}
SDL_Surface* Image::LoadSurface(std::string fname) {
FreeSurface();
SDL_Surface* p = SDL_LoadBMP(fname.c_str());
if (!p) {
std::ostringstream os;
os << "Failed to load file: " << fname;
throw(std::runtime_error(os.str()));
throw(std::runtime_error(std::string() + "Failed to load file: " + fname));
}
surface = p;
SetTransparentColor(255, 0, 255); //default
clip = {0, 0, (Uint16)surface->w, (Uint16)surface->h};
local = true;
SetTransparentColor(255, 0, 255); //default
return surface;
}
SDL_Surface* Image::CreateSurface(Uint16 w, Uint16 h) {
FreeSurface();
Uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
#else
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
#endif
SDL_Surface* p = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, rmask, gmask, bmask, amask);
if (!p) {
throw(std::runtime_error("Failed to create Image surface"));
}
surface = p;
clip = {0, 0, (Uint16)surface->w, (Uint16)surface->h};
local = true;
SetTransparentColor(255, 0, 255); //default
return surface;
}
SDL_Surface* Image::SetSurface(SDL_Surface* p) {
FreeSurface();
if (!p) {
throw(std::invalid_argument("No surface pointer provided"));
}
surface = p;
clip = {0, 0, (Uint16)surface->w, (Uint16)surface->h};
local = false;
return surface;
}
@@ -116,6 +44,16 @@ void Image::FreeSurface() {
clip = {0, 0, 0, 0};
}
SDL_Surface* Image::SetSurface(SDL_Surface* p) {
if (!p) {
throw(std::invalid_argument("No surface pointer provided"));
}
surface = p;
clip = {0, 0, (Uint16)surface->w, (Uint16)surface->h};
local = false;
return surface;
}
void Image::DrawTo(SDL_Surface* dest, Sint16 x, Sint16 y) {
if (!surface) {
throw(std::logic_error("No image surface to draw"));
@@ -128,9 +66,6 @@ void Image::SetTransparentColor(Uint8 r, Uint8 g, Uint8 b) {
if (!surface) {
throw(std::logic_error("Failed to set the transparent color"));
}
if (!local) {
throw(std::logic_error("Cannot set the transparent color of a non-local surface"));
}
SDL_SetColorKey(surface, SDL_SRCCOLORKEY, SDL_MapRGB(surface->format, r, g, b));
}
@@ -138,8 +73,5 @@ void Image::ClearTransparentColor() {
if (!surface) {
throw(std::logic_error("Failed to clear the transparent color"));
}
if (!local) {
throw(std::logic_error("Cannot clear the transparent color of a non-local surface"));
}
SDL_SetColorKey(surface, 0, 0);
}
+4 -11
View File
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -28,21 +28,14 @@
class Image {
public:
Image() = default;
Image(Image const& rhs) { *this = rhs; }
Image(Image&& rhs) { *this = std::move(rhs); }
Image(std::string fname) { LoadSurface(fname); }
Image(Uint16 w, Uint16 h) { CreateSurface(w, h); }
Image(SDL_Surface* p) { SetSurface(p); }
~Image() { FreeSurface(); }
Image& operator=(Image const&);
Image& operator=(Image&&);
SDL_Surface* LoadSurface(std::string fname);
SDL_Surface* CreateSurface(Uint16 w, Uint16 h);
void FreeSurface();
SDL_Surface* SetSurface(SDL_Surface*);
SDL_Surface* GetSurface() const { return surface; }
void FreeSurface();
void DrawTo(SDL_Surface* const, Sint16 x, Sint16 y);
@@ -60,7 +53,7 @@ public:
Uint16 GetClipW() const { return clip.w; }
Uint16 GetClipH() const { return clip.h; }
bool GetLocal() const { return local; }
bool GetLocal() { return local; }
void SetTransparentColor(Uint8 r, Uint8 g, Uint8 b);
void ClearTransparentColor();
+33 -8
View File
@@ -1,11 +1,36 @@
all:
$(MAKE) -C debugging
$(MAKE) -C gameplay
$(MAKE) -C graphics
$(MAKE) -C map
$(MAKE) -C network
$(MAKE) -C ui
$(MAKE) -C utilities
#config
LOCALLIBS=
LIB=
INCLUDES=
CXXFLAGS+=-std=c++11 -DDEBUG $(addprefix -I,$(INCLUDES))
#source
SRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ=$(addprefix $(OBJDIR)/,$(SRC:.cpp=.o))
#output
OUTDIR=../lib
OUT=$(addprefix $(OUTDIR)/,libCommon.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
-37
View File
@@ -1,37 +0,0 @@
#config
INCLUDES+=. ../graphics ../utilities
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=../..
OUT=$(addprefix $(OUTDIR)/,libcommon.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
-77
View File
@@ -1,77 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "map_system_api.hpp"
//all map API headers
#include "region_api.hpp"
#include "region_pager_api.hpp"
#include "tile_sheet_api.hpp"
//macros
#include "region.hpp"
//useful "globals"
static int getRegionWidth(lua_State* L) {
lua_pushinteger(L, REGION_WIDTH);
return 1;
}
static int getRegionHeight(lua_State* L) {
lua_pushinteger(L, REGION_HEIGHT);
return 1;
}
static int getRegionDepth(lua_State* L) {
lua_pushinteger(L, REGION_DEPTH);
return 1;
}
//This mimics linit.c to create a nested collection of all map modules.
static const luaL_Reg funcs[] = {
//synonyms
{"GetRegionWidth", getRegionWidth},
{"GetRegionHeight", getRegionHeight},
{"GetRegionDepth", getRegionDepth},
{nullptr, nullptr}
};
static const luaL_Reg libs[] = {
{"Region", openRegionAPI},
{"RegionPager", openRegionPagerAPI},
// {"TileSheet", openTileSheetAPI},
{nullptr, nullptr}
};
int openMapSystemAPI(lua_State* L) {
//create the table
luaL_newlibtable(L, libs);
//push the "global" functions
luaL_setfuncs(L, funcs, 0);
//push the substable
for (const luaL_Reg* lib = libs; lib->func; lib++) {
lua_pushcfunction(L, lib->func);
lua_setfield(L, -2, lib->name);
}
return 1;
}
-34
View File
@@ -1,34 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef MAPSYSTEMAPI_HPP_
#define MAPSYSTEMAPI_APP_
#if defined(__MINGW32__)
#include "lua/lua.hpp"
#else
#include "lua.hpp"
#endif
#define TORTUGA_MAP_SYSTEM_API "map_system"
LUAMOD_API int openMapSystemAPI(lua_State* L);
#endif
-58
View File
@@ -1,58 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "region.hpp"
#include <stdexcept>
#include <cmath>
#include <cstring>
int snapToBase(int base, int x) {
return floor((double)x / base) * base;
}
Region::Region(int argX, int argY): x(argX), y(argY) {
if (x != snapToBase(REGION_WIDTH, x) || y != snapToBase(REGION_HEIGHT, y)) {
throw(std::invalid_argument("Region location is off grid"));
}
memset(tiles, 0, REGION_WIDTH*REGION_HEIGHT*REGION_DEPTH*sizeof(type_t));
}
Region::Region(Region const& rhs): x(rhs.x), y(rhs.y) {
memcpy(tiles, rhs.tiles, REGION_WIDTH*REGION_HEIGHT*REGION_DEPTH*sizeof(type_t));
solid = rhs.solid;
}
Region::type_t Region::SetTile(int x, int y, int z, type_t v) {
return tiles[x][y][z] = v;
}
Region::type_t Region::GetTile(int x, int y, int z) {
return tiles[x][y][z];
}
bool Region::SetSolid(int x, int y, bool b) {
return solid[x * REGION_WIDTH + y] = b;
}
bool Region::GetSolid(int x, int y) {
return solid[x * REGION_WIDTH + y];
}
-63
View File
@@ -1,63 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef REGION_HPP_
#define REGION_HPP_
#include <bitset>
//the region's storage format
constexpr int REGION_WIDTH = 20;
constexpr int REGION_HEIGHT = 20;
constexpr int REGION_DEPTH = 3;
//utility function
int snapToBase(int base, int x);
class Region {
public:
typedef unsigned char type_t;
Region() = delete;
Region(int x, int y);
Region(Region const&);
~Region() = default;
type_t SetTile(int x, int y, int z, type_t v);
type_t GetTile(int x, int y, int z);
bool SetSolid(int x, int y, bool b);
bool GetSolid(int x, int y);
//accessors
int GetX() const { return x; }
int GetY() const { return y; }
std::bitset<REGION_WIDTH*REGION_HEIGHT>* GetSolidBitset() { return &solid; }
private:
const int x;
const int y;
type_t tiles[REGION_WIDTH][REGION_HEIGHT][REGION_DEPTH];
std::bitset<REGION_WIDTH*REGION_HEIGHT> solid;
};
#endif
-97
View File
@@ -1,97 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "region_api.hpp"
#include "region.hpp"
static int setTile(lua_State* L) {
Region* region = reinterpret_cast<Region*>(lua_touserdata(L, 1));
int ret = region->SetTile(lua_tointeger(L, 2)-1, lua_tointeger(L, 3)-1, lua_tointeger(L, 4)-1, lua_tointeger(L, 5));
lua_pushinteger(L, ret);
return 1;
}
static int getTile(lua_State* L) {
Region* region = reinterpret_cast<Region*>(lua_touserdata(L, 1));
int ret = region->GetTile(lua_tointeger(L, 2)-1, lua_tointeger(L, 3)-1, lua_tointeger(L, 4)-1);
lua_pushinteger(L, ret);
return 1;
}
static int setSolid(lua_State* L) {
Region* region = reinterpret_cast<Region*>(lua_touserdata(L, 1));
bool ret = region->SetSolid(lua_tointeger(L, 2)-1, lua_tointeger(L, 3)-1, lua_toboolean(L, 4));
lua_pushboolean(L, ret);
return 1;
}
static int getSolid(lua_State* L) {
Region* region = reinterpret_cast<Region*>(lua_touserdata(L, 1));
bool ret = region->GetSolid(lua_tointeger(L, 2)-1, lua_tointeger(L, 3)-1);
lua_pushboolean(L, ret);
return 1;
}
static int getX(lua_State* L) {
Region* region = reinterpret_cast<Region*>(lua_touserdata(L, 1));
lua_pushinteger(L, region->GetX());
return 1;
}
static int getY(lua_State* L) {
Region* region = reinterpret_cast<Region*>(lua_touserdata(L, 1));
lua_pushinteger(L, region->GetY());
return 1;
}
static int getWidth(lua_State* L) {
lua_pushinteger(L, REGION_WIDTH);
return 1;
}
static int getHeight(lua_State* L) {
lua_pushinteger(L, REGION_HEIGHT);
return 1;
}
static int getDepth(lua_State* L) {
lua_pushinteger(L, REGION_DEPTH);
return 1;
}
static const luaL_Reg regionLib[] = {
{"SetTile",setTile},
{"GetTile",getTile},
{"SetSolid",setSolid},
{"GetSolid",getSolid},
{"GetX",getX},
{"GetY",getY},
{"GetWidth",getWidth},
{"GetHeight",getHeight},
{"GetDepth",getDepth},
{nullptr, nullptr}
};
LUAMOD_API int openRegionAPI(lua_State* L) {
luaL_newlib(L, regionLib);
return 1;
}
-146
View File
@@ -1,146 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "region_pager_api.hpp"
#include "region_pager_lua.hpp"
#include "region.hpp"
//DOCS: These glue functions simply wrap RegionPagerLua's methods
static int setTile(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
int ret = pager->SetTile(lua_tointeger(L, 2), lua_tointeger(L, 3), lua_tointeger(L, 4), lua_tointeger(L, 5));
lua_pushinteger(L, ret);
return 1;
}
static int getTile(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
int ret = pager->GetTile(lua_tointeger(L, 2), lua_tointeger(L, 3), lua_tointeger(L, 4));
lua_pushinteger(L, ret);
return 1;
}
static int setSolid(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
bool ret = pager->SetSolid(lua_tointeger(L, 2), lua_tointeger(L, 3), lua_toboolean(L, 4));
lua_pushboolean(L, ret);
return 1;
}
static int getSolid(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
bool ret = pager->GetSolid(lua_tointeger(L, 2), lua_tointeger(L, 3));
lua_pushboolean(L, ret);
return 1;
}
static int getRegion(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
Region* region = pager->GetRegion(lua_tointeger(L, 2), lua_tointeger(L, 3));
lua_pushlightuserdata(L, region);
return 1;
}
static int loadRegion(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
Region* region = pager->LoadRegion(lua_tointeger(L, 2), lua_tointeger(L, 3));
lua_pushlightuserdata(L, region);
return 1;
}
static int saveRegion(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
Region* region = pager->SaveRegion(lua_tointeger(L, 2), lua_tointeger(L, 3));
lua_pushlightuserdata(L, region);
return 1;
}
static int createRegion(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
Region* region = pager->CreateRegion(lua_tointeger(L, 2), lua_tointeger(L, 3));
lua_pushlightuserdata(L, region);
return 1;
}
static int unloadRegion(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
pager->UnloadRegion(lua_tointeger(L, 2), lua_tointeger(L, 3));
return 0;
}
static int setOnLoad(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
luaL_unref(L, LUA_REGISTRYINDEX, pager->GetLoadReference());
pager->SetLoadReference(luaL_ref(L, LUA_REGISTRYINDEX));
return 0;
}
static int setOnSave(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
luaL_unref(L, LUA_REGISTRYINDEX, pager->GetSaveReference());
pager->SetSaveReference(luaL_ref(L, LUA_REGISTRYINDEX));
return 0;
}
static int setOnCreate(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
luaL_unref(L, LUA_REGISTRYINDEX, pager->GetCreateReference());
pager->SetCreateReference(luaL_ref(L, LUA_REGISTRYINDEX));
return 0;
}
static int setOnUnload(lua_State* L) {
RegionPagerLua* pager = reinterpret_cast<RegionPagerLua*>(lua_touserdata(L, 1));
luaL_unref(L, LUA_REGISTRYINDEX, pager->GetUnloadReference());
pager->SetUnloadReference(luaL_ref(L, LUA_REGISTRYINDEX));
return 0;
}
static const luaL_Reg regionPagerLib[] = {
//curry
{"SetTile", setTile},
{"GetTile", getTile},
{"SetSolid", setSolid},
{"GetSolid", getSolid},
//access and control
{"GetRegion", getRegion},
{"LoadRegion", loadRegion},
{"SaveRegion", saveRegion},
{"CreateRegion", createRegion},
{"UnloadRegion", unloadRegion},
//triggers
{"SetOnLoad",setOnLoad},
{"SetOnSave",setOnSave},
{"SetOnCreate",setOnCreate},
{"SetOnUnload",setOnUnload},
//sentinel
{nullptr, nullptr}
};
LUAMOD_API int openRegionPagerAPI(lua_State* L) {
luaL_newlib(L, regionPagerLib);
return 1;
}
-34
View File
@@ -1,34 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef REGIONPAGERAPI_HPP_
#define REGIONPAGERAPI_HPP_
#if defined(__MINGW32__)
#include "lua/lua.hpp"
#else
#include "lua.hpp"
#endif
#define TORTUGA_REGION_PAGER_NAME "region_pager"
LUAMOD_API int openRegionPagerAPI(lua_State* L);
#endif
-111
View File
@@ -1,111 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "region_pager_base.hpp"
#include <stdexcept>
#include <algorithm>
RegionPagerBase::RegionPagerBase() {
//
}
RegionPagerBase::RegionPagerBase(RegionPagerBase&& rhs) {
regionList = std::move(rhs.regionList);
}
RegionPagerBase::~RegionPagerBase() {
UnloadAll();
}
Region::type_t RegionPagerBase::SetTile(int x, int y, int z, Region::type_t v) {
Region* ptr = GetRegion(x, y);
return ptr->SetTile(x - ptr->GetX(), y - ptr->GetY(), z, v);
}
Region::type_t RegionPagerBase::GetTile(int x, int y, int z) {
Region* ptr = GetRegion(x, y);
return ptr->GetTile(x - ptr->GetX(), y - ptr->GetY(), z);
}
bool RegionPagerBase::SetSolid(int x, int y, int b) {
Region* ptr = GetRegion(x, y);
return ptr->SetSolid(x - ptr->GetX(), y - ptr->GetY(), b);
}
bool RegionPagerBase::GetSolid(int x, int y) {
Region* ptr = GetRegion(x, y);
return ptr->GetSolid(x - ptr->GetX(), y - ptr->GetY());
}
Region* RegionPagerBase::GetRegion(int x, int y) {
x = snapToBase(REGION_WIDTH, x);
y = snapToBase(REGION_HEIGHT, y);
//get the region by various means
Region* ptr = nullptr;
ptr = FindRegion(x, y);
if (ptr) return ptr;
ptr = LoadRegion(x, y);
if (ptr) return ptr;
return CreateRegion(x, y);
}
Region* RegionPagerBase::FindRegion(int x, int y) {
//find the region
std::list<Region>::iterator it = find_if(regionList.begin(), regionList.end(), [x, y](Region& region) -> bool {
return region.GetX() == x && region.GetY() == y;
});
return it != regionList.end() ? &(*it) : nullptr;
}
Region* RegionPagerBase::PushRegion(Region* const ptr) {
regionList.push_front(*ptr);
return &regionList.front();
}
Region* RegionPagerBase::LoadRegion(int x, int y) {
//EMPTY, intended for override
return nullptr;
}
Region* RegionPagerBase::SaveRegion(int x, int y) {
//EMPTY, intended for override
return nullptr;
}
Region* RegionPagerBase::CreateRegion(int x, int y) {
if (FindRegion(x, y)) {
throw(std::logic_error("Cannot overwrite an existing region"));
}
regionList.emplace_front(x, y);
return &regionList.front();
}
void RegionPagerBase::UnloadRegion(int x, int y) {
regionList.remove_if([x, y](Region& region) -> bool {
return region.GetX() == x && region.GetY() == y;
});
}
void RegionPagerBase::UnloadAll() {
regionList.clear();
}
-61
View File
@@ -1,61 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef REGIONPAGERBASE_HPP_
#define REGIONPAGERBASE_HPP_
#include "region.hpp"
#include <list>
class RegionPagerBase {
public:
RegionPagerBase();
RegionPagerBase(RegionPagerBase&&);
virtual ~RegionPagerBase();
//tile manipulation
virtual Region::type_t SetTile(int x, int y, int z, Region::type_t v);
virtual Region::type_t GetTile(int x, int y, int z);
//solid manipulation
virtual bool SetSolid(int x, int y, int b);
virtual bool GetSolid(int x, int y);
//region manipulation
virtual Region* GetRegion(int x, int y);
virtual Region* FindRegion(int x, int y);
virtual Region* PushRegion(Region* const);
virtual Region* LoadRegion(int x, int y);
virtual Region* SaveRegion(int x, int y);
virtual Region* CreateRegion(int x, int y);
virtual void UnloadRegion(int x, int y);
virtual void UnloadAll();
//accessors & mutators
std::list<Region>* GetContainer() { return &regionList; }
protected:
std::list<Region> regionList;
};
#endif
-206
View File
@@ -1,206 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "region_pager_lua.hpp"
#include <stdexcept>
RegionPagerLua::RegionPagerLua() {
//
}
RegionPagerLua::RegionPagerLua(RegionPagerLua&& rhs) {
lua = rhs.lua;
loadRef = rhs.loadRef;
saveRef = rhs.saveRef;
createRef = rhs.createRef;
unloadRef = rhs.unloadRef;
}
RegionPagerLua::~RegionPagerLua() {
//unload all regions
UnloadAll();
//clear any stored functions
luaL_unref(lua, LUA_REGISTRYINDEX, loadRef);
luaL_unref(lua, LUA_REGISTRYINDEX, saveRef);
luaL_unref(lua, LUA_REGISTRYINDEX, createRef);
luaL_unref(lua, LUA_REGISTRYINDEX, unloadRef);
}
//return the loaded region, or nullptr on failure
Region* RegionPagerLua::LoadRegion(int x, int y) {
//get the pager's function from the registry
lua_rawgeti(lua, LUA_REGISTRYINDEX, loadRef);
//check if this function is available
if (lua_isnil(lua, -1)) {
lua_pop(lua, 1);
return nullptr;
}
//something to work on
Region tmpRegion(x, y);
lua_pushlightuserdata(lua, &tmpRegion);
//call the funtion, 1 arg, 1 return
if (lua_pcall(lua, 1, 1, 0) != LUA_OK) {
throw(std::runtime_error(std::string() + "Lua error: " + lua_tostring(lua, -1) ));
}
//check the return value, success or failure
if (lua_toboolean(lua, -1)) {
lua_pop(lua, 1);
regionList.push_front(tmpRegion);
return &regionList.front();
}
else {
lua_pop(lua, 1);
return nullptr;
}
}
//return the saved region, or nullptr on failure
Region* RegionPagerLua::SaveRegion(int x, int y) {
//get the pager's function from the registry
lua_rawgeti(lua, LUA_REGISTRYINDEX, saveRef);
//check if this function is available
if (lua_isnil(lua, -1)) {
lua_pop(lua, 1);
return nullptr;
}
//find the specified region
Region* ptr = FindRegion(x, y);
if (!ptr) {
lua_pop(lua, 1);
return nullptr;
}
lua_pushlightuserdata(lua, ptr);
//call the function, 1 arg, 1 return
if (lua_pcall(lua, 1, 1, 0) != LUA_OK) {
throw(std::runtime_error(std::string() + "Lua error: " + lua_tostring(lua, -1) ));
}
//check the return value, success or failure
if (lua_toboolean(lua, -1)) {
lua_pop(lua, 1);
return ptr;
}
else {
lua_pop(lua, 1);
return nullptr;
}
}
//return the created region, or nullptr on failure
Region* RegionPagerLua::CreateRegion(int x, int y) {
if (FindRegion(x, y)) {
throw(std::logic_error("Cannot overwrite an existing region"));
}
//get the pager's function from the registry
lua_rawgeti(lua, LUA_REGISTRYINDEX, createRef);
//check if this function is available
if (lua_isnil(lua, -1)) {
lua_pop(lua, 1);
return nullptr;
}
//something to work on
Region tmpRegion(x, y);
lua_pushlightuserdata(lua, &tmpRegion);
//call the function, 1 arg, 0 return
if (lua_pcall(lua, 1, 0, 0) != LUA_OK) {
throw(std::runtime_error(std::string() + "Lua error: " + lua_tostring(lua, -1) ));
}
//return the new region
regionList.push_front(tmpRegion);
return &regionList.front();
}
//no return
void RegionPagerLua::UnloadRegion(int x, int y) {
//get the pager's function from the registry
lua_rawgeti(lua, LUA_REGISTRYINDEX, unloadRef);
//check if this function is available
if (lua_isnil(lua, -1)) {
lua_pop(lua, 1);
return;
}
//run each region through this lambda
regionList.remove_if([&](Region& region) -> bool {
if (region.GetX() == x && region.GetY() == y) {
//push a copy of the function onto the stack with the region
lua_pushvalue(lua, -1);
lua_pushlightuserdata(lua, &region);
//call the function, 1 arg, 0 return
if (lua_pcall(lua, 1, 0, 0) != LUA_OK) {
throw(std::runtime_error(std::string() + "Lua error: " + lua_tostring(lua, -1) ));
}
//signal to the container
return true;
}
//signal to the container
return false;
});
//pop the base copy of the function
lua_pop(lua, 1);
}
//no return
void RegionPagerLua::UnloadAll() {
//get the pager's function from the registry
lua_rawgeti(lua, LUA_REGISTRYINDEX, unloadRef);
//check if this function is available
if (lua_isnil(lua, -1)) {
lua_pop(lua, 1);
return;
}
for (auto& it : regionList) {
//push a copy of the function onto the stack with the region
lua_pushvalue(lua, -1);
lua_pushlightuserdata(lua, &it);
//call the function, 1 arg, 0 return
if (lua_pcall(lua, 1, 0, 0) != LUA_OK) {
throw(std::runtime_error(std::string() + "Lua error: " + lua_tostring(lua, -1) ));
}
}
//pop the base copy of the function
lua_pop(lua, 1);
//remove from memory
regionList.clear();
}
-73
View File
@@ -1,73 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef REGIONPAGERLUA_HPP_
#define REGIONPAGERLUA_HPP_
#include "region_pager_base.hpp"
#if defined(__MINGW32__)
#include "lua/lua.hpp"
#else
#include "lua.hpp"
#endif
#include <string>
class RegionPagerLua : public RegionPagerBase {
public:
RegionPagerLua();
RegionPagerLua(RegionPagerLua&&);
~RegionPagerLua();
//region manipulation
Region* LoadRegion(int x, int y) override;
Region* SaveRegion(int x, int y) override;
Region* CreateRegion(int x, int y) override;
void UnloadRegion(int x, int y) override;
void UnloadAll() override;
//accessors & mutators
lua_State* SetLuaState(lua_State* L) { return lua = L; }
lua_State* GetLuaState() { return lua; }
//utilities for the API
int SetLoadReference(int i) { return loadRef = i; }
int SetSaveReference(int i) { return saveRef = i; }
int SetCreateReference(int i) { return createRef = i; }
int SetUnloadReference(int i) { return unloadRef = i; }
int GetLoadReference() { return loadRef; }
int GetSaveReference() { return saveRef; }
int GetCreateReference() { return createRef; }
int GetUnloadReference() { return unloadRef; }
protected:
lua_State* lua = nullptr;
int loadRef = LUA_NOREF;
int saveRef = LUA_NOREF;
int createRef = LUA_NOREF;
int unloadRef = LUA_NOREF;
};
#endif
-61
View File
@@ -1,61 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "tile_sheet.hpp"
void TileSheet::Load(std::string fname, int tileWidth, int tileHeight) {
image.LoadSurface(fname);
image.SetClipW(tileWidth);
image.SetClipH(tileHeight);
xCount = image.GetSurface()->w / image.GetClipW();
yCount = image.GetSurface()->h / image.GetClipH();
}
void TileSheet::Unload() {
image.FreeSurface();
xCount = yCount = 0;
}
void TileSheet::DrawTileTo(SDL_Surface* const dest, int x, int y, Region::type_t tile) {
//0 is invisible
if (tile == 0) return;
image.SetClipX((tile-1) % xCount * image.GetClipW());
image.SetClipY((tile-1) / xCount * image.GetClipH());
image.DrawTo(dest, x, y);
}
void TileSheet::DrawRegionTo(SDL_Surface* const dest, Region* const region, int camX, int camY) {
Region::type_t tile = 0;
for (register int i = 0; i < REGION_WIDTH; ++i) {
for (register int j = 0; j < REGION_HEIGHT; ++j) {
for (register int k = 0; k < REGION_DEPTH; ++k) {
tile = region->GetTile(i, j, k);
//0 is invisible
if (tile == 0) continue;
image.SetClipX((tile-1) % xCount * image.GetClipW());
image.SetClipY((tile-1) / xCount * image.GetClipH());
image.DrawTo(dest,
(region->GetX() + i) * image.GetClipW() - camX,
(region->GetY() + j) * image.GetClipH() - camY);
}
}
}
}
-54
View File
@@ -1,54 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef TILESHEET_HPP_
#define TILESHEET_HPP_
#include "region.hpp"
#include "image.hpp"
#include <string>
class TileSheet {
public:
TileSheet() = default;
TileSheet(std::string f, int w, int h) { Load(f, w, h); }
~TileSheet() = default;
void Load(std::string fname, int tileWidth, int tileHeight);
void Unload();
void DrawTileTo(SDL_Surface* const dest, int x, int y, Region::type_t tile);
void DrawRegionTo(SDL_Surface* const dest, Region* const region, int camX, int camY);
//accessors
Image* GetImage() { return &image; }
int GetXCount() { return xCount; }
int GetYCount() { return yCount; }
int GetTileW() { return image.GetClipW(); }
int GetTileH() { return image.GetClipH(); }
private:
Image image;
int xCount = 0, yCount = 0;
};
#endif
-75
View File
@@ -1,75 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "tile_sheet_api.hpp"
#include "tile_sheet.hpp"
static int load(lua_State* L) {
TileSheet* sheet = reinterpret_cast<TileSheet*>(lua_touserdata(L, 1));
sheet->Load(lua_tostring(L, 2), lua_tointeger(L, 3), lua_tointeger(L, 4));
return 0;
}
static int unload(lua_State* L) {
TileSheet* sheet = reinterpret_cast<TileSheet*>(lua_touserdata(L, 1));
sheet->Unload();
return 0;
}
static int getXCount(lua_State* L) {
TileSheet* sheet = reinterpret_cast<TileSheet*>(lua_touserdata(L, 1));
lua_pushinteger(L, sheet->GetXCount());
return 1;
}
static int getYCount(lua_State* L) {
TileSheet* sheet = reinterpret_cast<TileSheet*>(lua_touserdata(L, 1));
lua_pushinteger(L, sheet->GetYCount());
return 1;
}
static int getTileW(lua_State* L) {
TileSheet* sheet = reinterpret_cast<TileSheet*>(lua_touserdata(L, 1));
lua_pushinteger(L, sheet->GetTileW());
return 1;
}
static int getTileH(lua_State* L) {
TileSheet* sheet = reinterpret_cast<TileSheet*>(lua_touserdata(L, 1));
lua_pushinteger(L, sheet->GetTileH());
return 1;
}
static const luaL_Reg tileSheetLib[] = {
{"Load",load},
{"Unload",unload},
{"GetXCount",getXCount},
{"GetYCount",getYCount},
{"GetTileW",getTileW},
{"GetTileH",getTileH},
{nullptr, nullptr}
};
LUAMOD_API int openTileSheetAPI(lua_State* L) {
luaL_newlib(L, tileSheetLib);
return 1;
}
-34
View File
@@ -1,34 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef TILESHEETAPI_HPP_
#define TILESHEETAPI_HPP_
#if defined(__MINGW32__)
#include "lua/lua.hpp"
#else
#include "lua.hpp"
#endif
#define TORTUGA_TILE_SHEET_NAME "tile_sheet"
LUAMOD_API int openTileSheetAPI(lua_State* L);
#endif
-38
View File
@@ -1,38 +0,0 @@
#config
INCLUDES+=. packet_types ../gameplay ../map ../utilities
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=../..
OUT=$(addprefix $(OUTDIR)/,libcommon.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(MAKE) -C packet_types
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
@@ -1,66 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "character_packet.hpp"
#include "serial_utility.hpp"
void serializeCharacter(void* buffer, CharacterPacket* packet) {
serialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//identify the character
serialCopy(&buffer, &packet->characterIndex, sizeof(int));
serialCopy(&buffer, packet->handle, PACKET_STRING_SIZE);
serialCopy(&buffer, packet->avatar, PACKET_STRING_SIZE);
//the owner
serialCopy(&buffer, &packet->accountIndex, sizeof(int));
//location
serialCopy(&buffer, &packet->roomIndex, sizeof(int));
serialCopy(&buffer, &packet->origin.x, sizeof(double));
serialCopy(&buffer, &packet->origin.y, sizeof(double));
serialCopy(&buffer, &packet->motion.x, sizeof(double));
serialCopy(&buffer, &packet->motion.y, sizeof(double));
//gameplay components: equipment, items, buffs, debuffs...
}
void deserializeCharacter(void* buffer, CharacterPacket* packet) {
deserialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//identify the character
deserialCopy(&buffer, &packet->characterIndex, sizeof(int));
deserialCopy(&buffer, packet->handle, PACKET_STRING_SIZE);
deserialCopy(&buffer, packet->avatar, PACKET_STRING_SIZE);
//the owner
deserialCopy(&buffer, &packet->accountIndex, sizeof(int));
//location
deserialCopy(&buffer, &packet->roomIndex, sizeof(int));
deserialCopy(&buffer, &packet->origin.x, sizeof(double));
deserialCopy(&buffer, &packet->origin.y, sizeof(double));
deserialCopy(&buffer, &packet->motion.x, sizeof(double));
deserialCopy(&buffer, &packet->motion.y, sizeof(double));
//gameplay components: equipment, items, buffs, debuffs...
}
@@ -1,50 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef CHARACTERPACKET_HPP_
#define CHARACTERPACKET_HPP_
#include "serial_packet_base.hpp"
#include "vector2.hpp"
struct CharacterPacket : SerialPacketBase {
//identify the character
int characterIndex;
char handle[PACKET_STRING_SIZE];
char avatar[PACKET_STRING_SIZE];
//the owner
int accountIndex;
//TODO: Authentication token?
//location
int roomIndex;
Vector2 origin;
Vector2 motion;
//gameplay components: equipment, items, buffs, debuffs...
};
void serializeCharacter(void* buffer, CharacterPacket* packet);
void deserializeCharacter(void* buffer, CharacterPacket* packet);
#endif
@@ -1,40 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "client_packet.hpp"
#include "serial_utility.hpp"
void serializeClient(void* buffer, ClientPacket* packet) {
serialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
serialCopy(&buffer, &packet->clientIndex, sizeof(int));
serialCopy(&buffer, &packet->accountIndex, sizeof(int));
serialCopy(&buffer, packet->username, PACKET_STRING_SIZE);
}
void deserializeClient(void* buffer, ClientPacket* packet) {
deserialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
deserialCopy(&buffer, &packet->clientIndex, sizeof(int));
deserialCopy(&buffer, &packet->accountIndex, sizeof(int));
deserialCopy(&buffer, packet->username, PACKET_STRING_SIZE);
}
@@ -1,36 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef CLIENTPACKET_HPP_
#define CLIENTPACKET_HPP_
#include "serial_packet_base.hpp"
struct ClientPacket : SerialPacketBase {
int clientIndex;
int accountIndex;
char username[PACKET_STRING_SIZE];
};
void serializeClient(void* buffer, ClientPacket* packet);
void deserializeClient(void* buffer, ClientPacket* packet);
#endif
-37
View File
@@ -1,37 +0,0 @@
#config
INCLUDES+=. .. ../../gameplay ../../map ../../utilities
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=../../..
OUT=$(addprefix $(OUTDIR)/,libcommon.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
@@ -1,79 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "region_packet.hpp"
#include "serial_utility.hpp"
void serializeRegion(void* buffer, RegionPacket* packet) {
serialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//format
serialCopy(&buffer, &packet->roomIndex, sizeof(int));
serialCopy(&buffer, &packet->x, sizeof(int));
serialCopy(&buffer, &packet->y, sizeof(int));
if (packet->type != SerialPacketType::REGION_CONTENT) {
return;
}
//tiles
for (int i = 0; i < REGION_WIDTH; i++) {
for (int j = 0; j < REGION_HEIGHT; j++) {
for (int k = 0; k < REGION_DEPTH; k++) {
*reinterpret_cast<Region::type_t*>(buffer) = packet->region->GetTile(i, j, k);
buffer = reinterpret_cast<char*>(buffer) + sizeof(Region::type_t);
}
}
}
//solids
serialCopy(&buffer, packet->region->GetSolidBitset(), REGION_SOLID_FOOTPRINT);
}
void deserializeRegion(void* buffer, RegionPacket* packet) {
deserialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//format
deserialCopy(&buffer, &packet->roomIndex, sizeof(int));
deserialCopy(&buffer, &packet->x, sizeof(int));
deserialCopy(&buffer, &packet->y, sizeof(int));
if (packet->type != SerialPacketType::REGION_CONTENT) {
return;
}
//an object to work on
packet->region = new Region(packet->x, packet->y);
//tiles
for (int i = 0; i < REGION_WIDTH; i++) {
for (int j = 0; j < REGION_HEIGHT; j++) {
for (int k = 0; k < REGION_DEPTH; k++) {
packet->region->SetTile(i, j, k, *reinterpret_cast<Region::type_t*>(buffer));
buffer = reinterpret_cast<char*>(buffer) + sizeof(Region::type_t);
}
}
}
//solids
deserialCopy(&buffer, packet->region->GetSolidBitset(), REGION_SOLID_FOOTPRINT);
}
@@ -1,48 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef REGIONPACKET_HPP_
#define REGIONPACKET_HPP_
#include "serial_packet_base.hpp"
#include "region.hpp"
#include <cmath>
//define the memory footprint for the region's members
constexpr int REGION_TILE_FOOTPRINT = sizeof(Region::type_t) * REGION_WIDTH * REGION_HEIGHT * REGION_DEPTH;
constexpr int REGION_SOLID_FOOTPRINT = ceil(REGION_WIDTH * REGION_HEIGHT / 8.0);
constexpr int REGION_METADATA_FOOTPRINT = sizeof(int) * 3;
struct RegionPacket : SerialPacketBase {
//location/identify the region
int roomIndex;
int x, y;
//the data
Region* region;
};
void serializeRegion(void* buffer, RegionPacket* packet);
void deserializeRegion(void* buffer, RegionPacket* packet);
#endif
@@ -1,24 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "serial_packet_base.hpp"
//sanity check
@@ -1,39 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SERIALPACKETBASE_HPP_
#define SERIALPACKETBASE_HPP_
#include "serial_packet_type.hpp"
#include "SDL/SDL_net.h"
constexpr int PACKET_STRING_SIZE = 100;
struct SerialPacketBase {
//members
SerialPacketType type;
IPaddress srcAddress;
virtual ~SerialPacketBase() {};
};
#endif
@@ -1,42 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "server_packet.hpp"
#include "serial_utility.hpp"
void serializeServer(void* buffer, ServerPacket* packet) {
serialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//identify the server
serialCopy(&buffer, packet->name, PACKET_STRING_SIZE);
serialCopy(&buffer, &packet->playerCount, sizeof(int));
serialCopy(&buffer, &packet->version, sizeof(int));
}
void deserializeServer(void* buffer, ServerPacket* packet) {
deserialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//identify the server
deserialCopy(&buffer, packet->name, PACKET_STRING_SIZE);
deserialCopy(&buffer, &packet->playerCount, sizeof(int));
deserialCopy(&buffer, &packet->version, sizeof(int));
}
@@ -1,37 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SERVERPACKET_HPP_
#define SERVERPACKET_HPP_
#include "serial_packet_base.hpp"
struct ServerPacket : SerialPacketBase {
//identify the server
char name[PACKET_STRING_SIZE];
int playerCount;
int version;
};
void serializeServer(void* buffer, ServerPacket* packet);
void deserializeServer(void* buffer, ServerPacket* packet);
#endif
@@ -1,40 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "text_packet.hpp"
#include "serial_utility.hpp"
void serializeText(void* buffer, TextPacket* packet) {
serialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//content
serialCopy(&buffer, packet->name, PACKET_STRING_SIZE);
serialCopy(&buffer, packet->text, PACKET_STRING_SIZE);
}
void deserializeText(void* buffer, TextPacket* packet) {
deserialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//content
deserialCopy(&buffer, packet->name, PACKET_STRING_SIZE);
deserialCopy(&buffer, packet->text, PACKET_STRING_SIZE);
}
@@ -1,35 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef TEXTPACKET_HPP_
#define TEXTPACKET_HPP_
#include "serial_packet_base.hpp"
struct TextPacket : SerialPacketBase {
char name[PACKET_STRING_SIZE];
char text[PACKET_STRING_SIZE];
};
void serializeText(void* buffer, TextPacket* packet);
void deserializeText(void* buffer, TextPacket* packet);
#endif
-64
View File
@@ -1,64 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SERIALPACKET_HPP_
#define SERIALPACKET_HPP_
#include "serial_packet_base.hpp"
#include "character_packet.hpp"
#include "client_packet.hpp"
#include "region_packet.hpp"
#include "server_packet.hpp"
#include "text_packet.hpp"
//SerialPacketBase is defined in serial_packet_base.hpp
typedef SerialPacketBase SerialPacket;
//DOCS: NETWORK_VERSION is used to discern compatible servers and clients
constexpr int NETWORK_VERSION = -1;
union MaxPacket {
CharacterPacket a;
ClientPacket b;
RegionPacket c;
ServerPacket d;
TextPacket e;
};
constexpr int MAX_PACKET_SIZE = sizeof(MaxPacket);
/* DOCS: PACKET_BUFFER_SIZE is the memory required to store serialized data
* DOCS: SerialPacketType::REGION_CONTENT is currently the largest packet type
* Serialized RegionPacket structure:
* SerialPacketType
* room index (int)
* X & Y position (int)
* tile data (3 layers)
* solid data (bitset)
*/
constexpr int PACKET_BUFFER_SIZE =
sizeof(SerialPacketType) +
REGION_METADATA_FOOTPRINT +
REGION_TILE_FOOTPRINT +
REGION_SOLID_FOOTPRINT;
#endif
-130
View File
@@ -1,130 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SERIALPACKETTYPE_HPP_
#define SERIALPACKETTYPE_HPP_
/* DOCS: The headers indicate what packet type is used for each message
* different messages under the same header will carry different amounts of
* valid data, but it will still be carried in that packet's format.
*/
//TODO: This needs to be smoothed out
enum class SerialPacketType {
//default: there is something wrong
NONE = 0,
//-------------------------
//ServerPacket
// name, player count, version
//-------------------------
//heartbeat
PING,
PONG,
//Used for finding available servers
BROADCAST_REQUEST,
BROADCAST_RESPONSE,
//-------------------------
//ClientPacket
// client index, account index, username
//-------------------------
//Connecting to a server as a client
JOIN_REQUEST,
JOIN_RESPONSE,
//disconnect from the server
DISCONNECT_REQUEST,
DISCONNECT_RESPONSE,
DISCONNECT_FORCED,
//load the account
LOGIN_REQUEST,
LOGIN_RESPONSE,
//unload the account
LOGOUT_REQUEST,
LOGOUT_RESPONSE,
//shut down the server
SHUTDOWN_REQUEST,
//-------------------------
//RegionPacket
// room index, x, y, raw data
//-------------------------
//map data
REGION_REQUEST, //NOTE: technically a query
REGION_CONTENT,
//-------------------------
//CharacterPacket
// character index,
// handle, avatar,
// account index (owner),
// room index, origin, motion,
// statistics
//-------------------------
//character management
CHARACTER_CREATE,
CHARACTER_DELETE,
CHARACTER_LOAD,
CHARACTER_UNLOAD,
//find out info from the server
QUERY_CHARACTER_EXISTS,
QUERY_CHARACTER_STATS,
QUERY_CHARACTER_LOCATION,
//set the info in the server
CHARACTER_SET_ROOM,
CHARACTER_SET_ORIGIN,
CHARACTER_SET_MOTION,
//TODO: enemy management
//-------------------------
//TextPacket
// name, text
//-------------------------
//general speech
TEXT_BROADCAST,
//rejection/error messages
JOIN_REJECTION,
LOGIN_REJECTION,
CHARACTER_REJECTION,
SHUTDOWN_REJECTION,
//-------------------------
//not used
//-------------------------
LAST
};
#endif
-141
View File
@@ -1,141 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "serial_utility.hpp"
//packet types
#include "character_packet.hpp"
#include "client_packet.hpp"
#include "region_packet.hpp"
#include "server_packet.hpp"
#include "text_packet.hpp"
#include <cstring>
//raw memory copy
void serialCopy(void** buffer, void* data, int size) {
memcpy(*buffer, data, size);
*buffer = reinterpret_cast<char*>(*buffer) + size;
}
void deserialCopy(void** buffer, void* data, int size) {
memcpy(data, *buffer, size);
*buffer = reinterpret_cast<char*>(*buffer) + size;
}
//DOCS: The server and client MUST use the correct packet types
//main switch functions
void serializePacket(void* buffer, SerialPacketBase* packet) {
switch(packet->type) {
case SerialPacketType::PING:
case SerialPacketType::PONG:
case SerialPacketType::BROADCAST_REQUEST:
case SerialPacketType::BROADCAST_RESPONSE:
serializeServer(buffer, static_cast<ServerPacket*>(packet));
break;
case SerialPacketType::JOIN_REQUEST:
case SerialPacketType::JOIN_RESPONSE:
case SerialPacketType::DISCONNECT_REQUEST:
case SerialPacketType::DISCONNECT_RESPONSE:
case SerialPacketType::DISCONNECT_FORCED:
case SerialPacketType::LOGIN_REQUEST:
case SerialPacketType::LOGIN_RESPONSE:
case SerialPacketType::LOGOUT_REQUEST:
case SerialPacketType::LOGOUT_RESPONSE:
case SerialPacketType::SHUTDOWN_REQUEST:
serializeClient(buffer, static_cast<ClientPacket*>(packet));
break;
case SerialPacketType::REGION_REQUEST:
case SerialPacketType::REGION_CONTENT:
serializeRegion(buffer, static_cast<RegionPacket*>(packet));
break;
case SerialPacketType::CHARACTER_CREATE:
case SerialPacketType::CHARACTER_DELETE:
case SerialPacketType::CHARACTER_LOAD:
case SerialPacketType::CHARACTER_UNLOAD:
case SerialPacketType::QUERY_CHARACTER_EXISTS:
case SerialPacketType::QUERY_CHARACTER_STATS:
case SerialPacketType::QUERY_CHARACTER_LOCATION:
case SerialPacketType::CHARACTER_SET_ROOM:
case SerialPacketType::CHARACTER_SET_ORIGIN:
case SerialPacketType::CHARACTER_SET_MOTION:
serializeCharacter(buffer, static_cast<CharacterPacket*>(packet));
break;
case SerialPacketType::TEXT_BROADCAST:
case SerialPacketType::JOIN_REJECTION:
case SerialPacketType::LOGIN_REJECTION:
case SerialPacketType::CHARACTER_REJECTION:
case SerialPacketType::SHUTDOWN_REJECTION:
serializeText(buffer, static_cast<TextPacket*>(packet));
break;
}
}
void deserializePacket(void* buffer, SerialPacketBase* packet) {
//find the type, so that you can actually deserialize the packet!
SerialPacketType type;
memcpy(&type, buffer, sizeof(SerialPacketType));
switch(packet->type) {
case SerialPacketType::PING:
case SerialPacketType::PONG:
case SerialPacketType::BROADCAST_REQUEST:
case SerialPacketType::BROADCAST_RESPONSE:
deserializeServer(buffer, static_cast<ServerPacket*>(packet));
break;
case SerialPacketType::JOIN_REQUEST:
case SerialPacketType::JOIN_RESPONSE:
case SerialPacketType::DISCONNECT_REQUEST:
case SerialPacketType::DISCONNECT_RESPONSE:
case SerialPacketType::DISCONNECT_FORCED:
case SerialPacketType::LOGIN_REQUEST:
case SerialPacketType::LOGIN_RESPONSE:
case SerialPacketType::LOGOUT_REQUEST:
case SerialPacketType::LOGOUT_RESPONSE:
case SerialPacketType::SHUTDOWN_REQUEST:
deserializeClient(buffer, static_cast<ClientPacket*>(packet));
break;
case SerialPacketType::REGION_REQUEST:
case SerialPacketType::REGION_CONTENT:
deserializeRegion(buffer, static_cast<RegionPacket*>(packet));
break;
case SerialPacketType::CHARACTER_CREATE:
case SerialPacketType::CHARACTER_DELETE:
case SerialPacketType::CHARACTER_LOAD:
case SerialPacketType::CHARACTER_UNLOAD:
case SerialPacketType::QUERY_CHARACTER_EXISTS:
case SerialPacketType::QUERY_CHARACTER_STATS:
case SerialPacketType::QUERY_CHARACTER_LOCATION:
case SerialPacketType::CHARACTER_SET_ROOM:
case SerialPacketType::CHARACTER_SET_ORIGIN:
case SerialPacketType::CHARACTER_SET_MOTION:
deserializeCharacter(buffer, static_cast<CharacterPacket*>(packet));
break;
case SerialPacketType::TEXT_BROADCAST:
case SerialPacketType::JOIN_REJECTION:
case SerialPacketType::LOGIN_REJECTION:
case SerialPacketType::CHARACTER_REJECTION:
case SerialPacketType::SHUTDOWN_REJECTION:
deserializeText(buffer, static_cast<TextPacket*>(packet));
break;
}
}
-37
View File
@@ -1,37 +0,0 @@
/* Copyright: (c) Kayne Ruse 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef SERIALIZEUTILITY_HPP_
#define SERIALIZEUTILITY_HPP_
#include "serial_packet_base.hpp"
#include <cstring>
//raw memory copy
void serialCopy(void** buffer, void* data, int size);
void deserialCopy(void** buffer, void* data, int size);
//primary functions
void serializePacket(void* buffer, SerialPacketBase* packet);
void deserializePacket(void* buffer, SerialPacketBase* packet);
#endif
-225
View File
@@ -1,225 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "udp_network_utility.hpp"
#include "serial_packet.hpp"
#include "serial_utility.hpp"
#include <stdexcept>
//NOTE: memset() is used before sending a packet to remove old data; you don't want to send sensitive data over the network
//NOTE: don't confuse SerialPacketBase with UDPpacket
void UDPNetworkUtility::Open(int port) {
socket = SDLNet_UDP_Open(port);
packet = SDLNet_AllocPacket(PACKET_BUFFER_SIZE);
if (!socket || !packet) {
Close();
throw(std::runtime_error("Failed to open UDPNetworkUtility"));
}
}
void UDPNetworkUtility::Close() {
SDLNet_UDP_Close(socket);
SDLNet_FreePacket(packet);
socket = nullptr;
packet = nullptr;
}
//-------------------------
//bind to a channel
//-------------------------
int UDPNetworkUtility::Bind(const char* ip, int port, int channel) {
IPaddress add;
if (SDLNet_ResolveHost(&add, ip, port) == -1) {
throw(std::runtime_error("Failed to resolve a host"));
}
return Bind(add, channel);
}
int UDPNetworkUtility::Bind(IPaddress add, int channel) {
int ret = SDLNet_UDP_Bind(socket, channel, &add);
if (ret < 0) {
throw(std::runtime_error("Failed to bind to a channel"));
}
return ret;
}
void UDPNetworkUtility::Unbind(int channel) {
SDLNet_UDP_Unbind(socket, channel);
}
//-------------------------
//send a buffer
//-------------------------
int UDPNetworkUtility::SendTo(const char* ip, int port, void* data, int len) {
IPaddress add;
if (SDLNet_ResolveHost(&add, ip, port) == -1) {
throw(std::runtime_error("Failed to resolve a host"));
}
SendTo(add, data, len);
}
int UDPNetworkUtility::SendTo(IPaddress add, void* data, int len) {
if (len > packet->maxlen) {
throw(std::runtime_error("The buffer is to large for the UDPpacket"));
}
memset(packet->data, 0, packet->maxlen);
memcpy(packet->data, data, len);
packet->len = len;
packet->address = add;
int ret = SDLNet_UDP_Send(socket, -1, packet);
if (ret <= 0) {
throw(std::runtime_error("Failed to send a packet"));
}
return ret;
}
int UDPNetworkUtility::SendTo(int channel, void* data, int len) {
if (len > packet->maxlen) {
throw(std::runtime_error("The buffer is to large for the UDPpacket"));
}
memset(packet->data, 0, packet->maxlen);
memcpy(packet->data, data, len);
packet->len = len;
int ret = SDLNet_UDP_Send(socket, channel, packet);
if (ret <= 0) {
throw(std::runtime_error("Failed to send a packet"));
}
return ret;
}
int UDPNetworkUtility::SendToAllChannels(void* data, int len) {
if (len > packet->maxlen) {
throw(std::runtime_error("The buffer is to large for the UDPpacket"));
}
memset(packet->data, 0, packet->maxlen);
memcpy(packet->data, data, len);
packet->len = len;
int sent = 0;
//send to all bound channels
for (int i = 0; i < SDLNET_MAX_UDPCHANNELS; i++) {
if (SDLNet_UDP_GetPeerAddress(socket, i)) {
sent += SDLNet_UDP_Send(socket, i, packet);
}
}
return sent;
}
//TODO: put a void* and int* parameter list here
int UDPNetworkUtility::Receive() {
memset(packet->data, 0, packet->maxlen);
int ret = SDLNet_UDP_Recv(socket, packet);
if (ret < 0) {
throw(std::runtime_error("Unknown network error occured"));
}
return ret;
}
//-------------------------
//send a SerialPacketBase
//-------------------------
int UDPNetworkUtility::SendTo(const char* ip, int port, SerialPacketBase* serialPacket) {
IPaddress add;
if (SDLNet_ResolveHost(&add, ip, port) == -1) {
throw(std::runtime_error("Failed to resolve a host"));
}
SendTo(add, serialPacket);
}
int UDPNetworkUtility::SendTo(IPaddress add, SerialPacketBase* serialPacket) {
memset(packet->data, 0, packet->maxlen);
serializePacket(packet->data, serialPacket);
packet->len = PACKET_BUFFER_SIZE;
packet->address = add;
int ret = SDLNet_UDP_Send(socket, -1, packet);
if (ret <= 0) {
throw(std::runtime_error("Failed to send a packet"));
}
return ret;
}
int UDPNetworkUtility::SendTo(int channel, SerialPacketBase* serialPacket) {
memset(packet->data, 0, packet->maxlen);
serializePacket(packet->data, serialPacket);
packet->len = PACKET_BUFFER_SIZE;
int ret = SDLNet_UDP_Send(socket, channel, packet);
if (ret <= 0) {
throw(std::runtime_error("Failed to send a packet"));
}
return ret;
}
int UDPNetworkUtility::SendToAllChannels(SerialPacketBase* serialPacket) {
memset(packet->data, 0, packet->maxlen);
serializePacket(packet->data, serialPacket);
packet->len = PACKET_BUFFER_SIZE;
int sent = 0;
//send to all bound channels
for (int i = 0; i < SDLNET_MAX_UDPCHANNELS; i++) {
if (SDLNet_UDP_GetPeerAddress(socket, i)) {
sent += SDLNet_UDP_Send(socket, i, packet);
}
}
return sent;
}
int UDPNetworkUtility::Receive(SerialPacketBase* serialPacket) {
memset(packet->data, 0, packet->maxlen);
int ret = SDLNet_UDP_Recv(socket, packet);
deserializePacket(packet->data, serialPacket);
serialPacket->srcAddress = packet->address;
if (ret < 0) {
throw(std::runtime_error("Unknown network error occured"));
}
return ret;
}
+110
View File
@@ -0,0 +1,110 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "network_queue.hpp"
#include "singleton.hpp"
#include "udp_network_utility.hpp"
#include "SDL/SDL_thread.h"
#include <stdexcept>
#include <deque>
static SDL_sem* lock = SDL_CreateSemaphore(1);
static SDL_Thread* queueThread = nullptr;
static std::deque<Packet> queue;
static bool running = false;
static int networkQueue(void*) {
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
while(running) {
SDL_SemWait(lock);
while(netUtil->Receive()) {
Packet p;
memcpy(&p, netUtil->GetInData(), sizeof(Packet));
p.meta.address = netUtil->GetInPacket()->address;
queue.push_back(p);
}
SDL_SemPost(lock);
SDL_Delay(10);
}
return 0;
}
void beginQueueThread() {
if (running) {
return;
}
running = true;
if (!(queueThread = SDL_CreateThread(networkQueue, nullptr))) {
throw(std::runtime_error("Failed to create the network thread"));
}
}
void endQueueThread() {
if (!running) {
return;
}
running = false;
SDL_WaitThread(queueThread, nullptr);
queueThread = nullptr;
}
void killQueueThread() {
if (!running) {
return;
}
running = false;
SDL_KillThread(queueThread);
queueThread = nullptr;
}
Packet peekNetworkPacket() {
SDL_SemWait(lock);
Packet p;
if (queue.size() > 0) {
Packet p = queue[0];
}
SDL_SemPost(lock);
return p;
}
Packet popNetworkPacket() {
SDL_SemWait(lock);
Packet p;
if (queue.size() > 0) {
p = queue[0];
queue.pop_front();
}
SDL_SemPost(lock);
return p;
}
void flushNetworkQueue() {
UDPNetworkUtility* netUtil = Singleton<UDPNetworkUtility>::Get();
SDL_SemWait(lock);
while(netUtil->Receive());
queue.clear();
SDL_SemPost(lock);
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,16 +19,16 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef REGIONAPI_HPP_
#define REGIONAPI_HPP_
#ifndef NETWORKQUEUE_HPP_
#define NETWORKQUEUE_HPP_
#if defined(__MINGW32__)
#include "lua/lua.hpp"
#else
#include "lua.hpp"
#endif
#include "packet.hpp"
#define TORTUGA_REGION_NAME "region"
LUAMOD_API int openRegionAPI(lua_State* L);
void beginQueueThread();
void endQueueThread();
void killQueueThread();
Packet peekNetworkPacket();
Packet popNetworkPacket();
void flushNetworkQueue();
#endif
+90
View File
@@ -0,0 +1,90 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef PACKETTYPE_HPP_
#define PACKETTYPE_HPP_
#include "vector2.hpp"
#include "SDL/SDL_net.h"
#define PACKET_STRING_SIZE 100
#pragma pack(push, 0)
union Packet {
//the type of packet being sent
enum class Type {
NONE = 0,
PING = 1,
PONG = 2,
BROADCAST_REQUEST = 3,
BROADCAST_RESPONSE = 4,
JOIN_REQUEST = 5,
JOIN_RESPONSE = 6,
DISCONNECT = 7,
SYNCHRONIZE = 8,
PLAYER_NEW = 9,
PLAYER_DELETE = 10,
PLAYER_UPDATE = 11,
};
//metadata on the packet itself
struct Metadata {
Type type;
IPaddress address;
int clientIndex;
}meta;
//information about the server
struct ServerInformation {
Metadata meta;
//TODO: version info
char name[PACKET_STRING_SIZE];
//TODO: player count
}serverInfo;
//information about a specific player
struct PlayerInformation {
Metadata meta;
int index;
char handle[PACKET_STRING_SIZE];
char avatar[PACKET_STRING_SIZE];
Vector2 position;
Vector2 motion;
//TODO Playerdata
}playerInfo;
//zero the packet
Packet() {
meta.type = Type::NONE;
meta.address.host = 0;
meta.address.port = 0;
meta.clientIndex = -1;
};
};
#pragma pack(pop)
#endif
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -23,8 +23,9 @@
#include <stdexcept>
/* It might be more efficient to render to a different surface (like an Image)
* rather than calling this function with all of it's '%' and '/'.
/* Note: This class can only take a raster font with 16*16 characters, and the
* indevidual characters must have the same dimensions. Overall this class is too
* restrictive; I suggest using a 3rd party library.
*/
void RasterFont::DrawStringTo(std::string s, SDL_Surface* const dest, Sint16 x, Sint16 y) {
@@ -40,21 +41,10 @@ void RasterFont::DrawStringTo(std::string s, SDL_Surface* const dest, Sint16 x,
}
}
/* Note: This class can only take a raster font with 16*16 characters, and the
* indevidual characters must have the same dimensions. Overall this class is too
* restrictive; I suggest using a 3rd party library.
*/
SDL_Surface* RasterFont::LoadSurface(std::string fname) {
image.LoadSurface(fname);
image.SetClipW(image.GetSurface()->w/16);
image.SetClipH(image.GetSurface()->h/16);
return image.GetSurface();
}
SDL_Surface* RasterFont::SetSurface(SDL_Surface* p) {
image.SetSurface(p);
image.SetClipW(image.GetSurface()->w/16);
image.SetClipH(image.GetSurface()->h/16);
if (image.SetSurface(p)) {
image.SetClipW(image.GetSurface()->w/16);
image.SetClipH(image.GetSurface()->h/16);
}
return image.GetSurface();
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -24,29 +24,21 @@
#include "image.hpp"
#include <string>
class RasterFont {
public:
RasterFont() = default;
RasterFont(RasterFont const& rhs) { *this = rhs; }
RasterFont(RasterFont&& rhs) { *this = std::move(rhs); }
RasterFont(std::string fname) { LoadSurface(fname); }
RasterFont(SDL_Surface* p) { SetSurface(p); }
~RasterFont() = default;
RasterFont& operator=(RasterFont const& rhs) { image = rhs.image; }
RasterFont& operator=(RasterFont&& rhs) { image = std::move(rhs.image); }
void DrawStringTo(std::string, SDL_Surface* const, Sint16 x, Sint16 y);
//Accessors and Mutators
SDL_Surface* LoadSurface(std::string);
SDL_Surface* SetSurface(SDL_Surface*);
SDL_Surface* GetSurface() const { return image.GetSurface(); }
void FreeSurface() { image.FreeSurface(); }
Uint16 GetCharW() const { return image.GetClipW(); }
Uint16 GetCharH() const { return image.GetClipH(); }
Uint16 GetCharW() { return image.GetClipW(); }
Uint16 GetCharH() { return image.GetClipH(); }
private:
Image image;
};
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,18 +19,20 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef BASEMONSTER_HPP_
#define BASEMONSTER_HPP_
#ifndef SINGLETON_HPP_
#define SINGLETON_HPP_
#include "entity.hpp"
class BaseMonster : public Entity {
template<typename T>
class Singleton {
public:
BaseMonster() = default;
virtual ~BaseMonster() = default;
static T* Get() {
return &instance;
}
private:
//
static T instance;
};
#endif
template<typename T>
T Singleton<T>::instance;
#endif
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,30 +19,23 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef FRAMERATE_HPP_
#define FRAMERATE_HPP_
#include "sprite_sheet.hpp"
#include <chrono>
class FrameRate {
public:
typedef std::chrono::high_resolution_clock Clock;
FrameRate() = default;
int Calculate() {
frameCount++;
if (Clock::now() - tick >= std::chrono::duration<int>(1)) {
lastFrameRate = frameCount;
frameCount = 0;
tick = Clock::now();
void SpriteSheet::Update(double delta) {
if (delay && (ticks += delta) >= delay) {
if (++currentFrame >= maxFrames) {
currentFrame = 0;
}
return lastFrameRate;
ticks = 0;
}
int GetFrameRate() { return lastFrameRate; }
private:
int frameCount = 0;
int lastFrameRate = 0;
Clock::time_point tick = Clock::now();
};
image.SetClipX(currentFrame * image.GetClipW());
image.SetClipY(currentStrip * image.GetClipH());
}
#endif
SDL_Surface* SpriteSheet::SetSurface(SDL_Surface* const s, Uint16 w, Uint16 h) {
image.SetSurface(s);
image.SetClip({0, 0, w, h});
currentFrame = 0; maxFrames = image.GetSurface()->w / image.GetClipW();
currentStrip = 0; maxStrips = image.GetSurface()->h / image.GetClipH();
delay = ticks = 0;
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -24,43 +24,39 @@
#include "image.hpp"
#include "SDL/SDL.h"
class SpriteSheet {
public:
SpriteSheet() = default;
SpriteSheet(std::string fname, Uint16 xCellCount, Uint16 yCellCount) { LoadSurface(fname, xCellCount, yCellCount); }
SpriteSheet(SDL_Surface* surface, Uint16 xCellCount, Uint16 yCellCount) { SetSurface(surface, xCellCount, yCellCount); }
~SpriteSheet() { FreeSurface(); };
SpriteSheet(SDL_Surface* s, Uint16 w, Uint16 h) { SetSurface(s, w, h); }
~SpriteSheet() = default;
void Update(double delta);
SDL_Surface* LoadSurface(std::string fname, Uint16 xCellCount, Uint16 yCellCount);
SDL_Surface* SetSurface(SDL_Surface* surface, Uint16 xCellCount, Uint16 yCellCount);
SDL_Surface* GetSurface() { return image.GetSurface(); }
void FreeSurface();
SDL_Surface* SetSurface(SDL_Surface* const, Uint16 w, Uint16 h);
SDL_Surface* GetSurface() const { return image.GetSurface(); }
void DrawTo(SDL_Surface* const dest, Sint16 x, Sint16 y) { image.DrawTo(dest, x, y); }
//accessors and mutators
Image* GetImage() { return &image; } //OO breaker
Uint16 SetXCount(Uint16);
Uint16 SetYCount(Uint16);
Uint16 SetXIndex(Uint16);
Uint16 SetYIndex(Uint16);
Uint16 GetXCount() const { return xCount; }
Uint16 GetYCount() const { return yCount; }
Uint16 GetXIndex() const { return xIndex; }
Uint16 GetYIndex() const { return yIndex; }
double SetDelay(double d);
//Accessors and Mutators
double SetDelay(double i) { return delay = i; }
double GetDelay() const { return delay; }
int SetCurrentFrame(int i) { return currentFrame = i; }
int SetCurrentStrip(int i) { return currentStrip = i; }
Uint16 GetFrameWidth() const { return image.GetClipW(); }
Uint16 GetFrameHeight() const { return image.GetClipH(); }
int GetCurrentFrame() const { return currentFrame; };
int GetCurrentStrip() const { return currentStrip; };
int GetMaxFrames() const { return maxFrames; }
int GetMaxStrips() const { return maxStrips; }
private:
Image image;
Uint16 xCount = 0, yCount = 0; //number of cells
Uint16 xIndex = 0, yIndex = 0; //current cell being drawn
double delay = 0.0, tick = 0.0;
int currentFrame = 0, maxFrames = 0;
int currentStrip = 0, maxStrips = 0;
double delay = 0, ticks = 0;
};
#endif
+81
View File
@@ -0,0 +1,81 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "surface_manager.hpp"
#include <stdexcept>
SDL_Surface* SurfaceManager::Load(std::string key, std::string fname) {
MapType::iterator it = surfaceMap.find(key);
if (it != surfaceMap.end()) {
throw(std::runtime_error(std::string("Surface already loaded: ") + key + std::string(", ") + fname));
}
return LoadSurface(key, fname);
}
SDL_Surface* SurfaceManager::Reload(std::string key, std::string fname) {
MapType::iterator it = surfaceMap.find(key);
if (it != surfaceMap.end()) {
SDL_FreeSurface(it->second);
surfaceMap.erase(it);
}
return LoadSurface(key, fname);
}
SDL_Surface* SurfaceManager::Get(std::string key) {
MapType::iterator it = surfaceMap.find(key);
if (it == surfaceMap.end()) {
throw(std::runtime_error(std::string("Could not find key: ") + key));
}
return it->second;
}
SDL_Surface* SurfaceManager::Set(std::string key, SDL_Surface* ptr) {
MapType::iterator it = surfaceMap.find(key);
if (it != surfaceMap.end()) {
throw(std::runtime_error(std::string("Key already exists: ") + key));
}
return surfaceMap[key] = ptr;
}
void SurfaceManager::Free(std::string key) {
MapType::iterator it = surfaceMap.find(key);
if (it != surfaceMap.end()) {
SDL_FreeSurface(it->second);
surfaceMap.erase(it);
}
}
void SurfaceManager::FreeAll() {
for (auto it : surfaceMap) {
SDL_FreeSurface(it.second);
}
surfaceMap.clear();
}
SDL_Surface* SurfaceManager::LoadSurface(std::string key, std::string fname) {
SDL_Surface* ptr = SDL_LoadBMP(fname.c_str());
if (!ptr) {
throw(std::runtime_error(std::string("Failed to load file: ") + fname));
}
SDL_SetColorKey(ptr, SDL_SRCCOLORKEY, SDL_MapRGB(ptr->format, 255, 0, 255)); //default
return surfaceMap[key] = ptr;
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -19,36 +19,31 @@
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef CHARACTERDATA_HPP_
#define CHARACTERDATA_HPP_
#ifndef SURFACEMANAGER_HPP_
#define SURFACEMANAGER_HPP_
//components
#include "character_defines.hpp"
#include "entity.hpp"
#include "SDL/SDL.h"
//std namespace
#include <map>
#include <string>
#include <cmath>
class CharacterData: public Entity {
class SurfaceManager {
public:
CharacterData() = default;
~CharacterData() = default;
SurfaceManager() = default;
~SurfaceManager() noexcept { FreeAll(); }
//accessors and mutators
//...
//database stuff
int GetOwner();
std::string GetHandle();
std::string GetAvatar();
SDL_Surface* Load(std::string key, std::string fname);
SDL_Surface* Reload(std::string key, std::string fname);
SDL_Surface* Get(std::string key);
SDL_Surface* Set(std::string key, SDL_Surface* ptr);
void Free(std::string key);
void FreeAll();
SDL_Surface* operator[](std::string key) { return Get(key); };
private:
friend class CharacterManager;
int owner;
std::string handle;
std::string avatar;
SDL_Surface* LoadSurface(std::string key, std::string fname);
typedef std::map<std::string, SDL_Surface*> MapType;
MapType surfaceMap;
};
#endif
+148
View File
@@ -0,0 +1,148 @@
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "udp_network_utility.hpp"
#include <stdexcept>
void UDPNetworkUtility::Open(int port, int packSize) {
if (!(socket = SDLNet_UDP_Open(port))) {
Close();
throw(std::runtime_error("Failed to open a UDP socket"));
}
if (!(packOut = SDLNet_AllocPacket(packSize))) {
Close();
throw(std::runtime_error("Failed to allocate the out packet"));
}
if (!(packIn = SDLNet_AllocPacket(packSize))) {
Close();
throw(std::runtime_error("Failed to allocate the in packet"));
}
}
void UDPNetworkUtility::Close() {
SDLNet_UDP_Close(socket);
SDLNet_FreePacket(packOut);
SDLNet_FreePacket(packIn);
socket = nullptr;
packOut = nullptr;
packIn = nullptr;
}
int UDPNetworkUtility::Bind(const char* ip, int port, int channel) {
IPaddress add;
if (SDLNet_ResolveHost(&add, ip, port) == -1) {
throw(std::runtime_error("Failed to resolve a host"));
}
return Bind(&add, channel);
}
int UDPNetworkUtility::Bind(IPaddress* add, int channel) {
int ret = SDLNet_UDP_Bind(socket, channel, add);
if (ret == -1) {
throw(std::runtime_error("Failed to bind to a channel"));
}
return ret;
}
void UDPNetworkUtility::Unbind(int channel) {
SDLNet_UDP_Unbind(socket, channel);
}
int UDPNetworkUtility::Send(const char* ip, int port, void* data, int len) {
IPaddress add;
if (SDLNet_ResolveHost(&add, ip, port) == -1) {
throw(std::runtime_error("Failed to resolve a host"));
}
Send(&add, data, len);
}
int UDPNetworkUtility::Send(IPaddress* add, void* data, int len) {
if (len > packOut->maxlen) {
throw(std::runtime_error("Failed to copy the data into the packet"));
}
memset(packOut->data, 0, packOut->maxlen);
memcpy(packOut->data, data, len);
packOut->len = len;
packOut->address = *add;
int ret = SDLNet_UDP_Send(socket, -1, packOut);
if (ret <= 0) {
throw(std::runtime_error("Failed to send a packet"));
}
return ret;
}
int UDPNetworkUtility::Send(int channel, void* data, int len) {
if (len > packOut->maxlen) {
throw(std::runtime_error("Failed to copy the data into the packet"));
}
memset(packOut->data, 0, packOut->maxlen);
memcpy(packOut->data, data, len);
packOut->len = len;
int ret = SDLNet_UDP_Send(socket, channel, packOut);
if (ret <= 0) {
throw(std::runtime_error("Failed to send a packet"));
}
return ret;
}
int UDPNetworkUtility::SendAll(void* data, int len) {
if (len > packOut->maxlen) {
throw(std::runtime_error("Failed to copy the data into the packet"));
}
memset(packOut->data, 0, packOut->maxlen);
memcpy(packOut->data, data, len);
packOut->len = len;
int sent = 0;
//send to all bound channels
for (int i = 0; i < SDLNET_MAX_UDPCHANNELS; i++) {
if (SDLNet_UDP_GetPeerAddress(socket, i)) {
sent += SDLNet_UDP_Send(socket, i, packOut);
}
}
return sent;
}
int UDPNetworkUtility::Receive() {
memset(packIn->data, 0, packIn->maxlen);
int ret = SDLNet_UDP_Recv(socket, packIn);
if (ret < 0) {
throw(std::runtime_error("Unknown network error occured"));
}
return ret;
}
@@ -1,4 +1,4 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
/* Copyright: (c) Kayne Ruse 2013
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
@@ -22,56 +22,58 @@
#ifndef UDPNETWORKUTILITY_HPP_
#define UDPNETWORKUTILITY_HPP_
//common
#include "serial_packet_base.hpp"
#include "singleton.hpp"
//APIs
#include "SDL/SDL_net.h"
class UDPNetworkUtility : public Singleton<UDPNetworkUtility> {
class UDPNetworkUtility {
public:
void Open(int port);
UDPNetworkUtility() = default;
~UDPNetworkUtility() = default;
void Open(int port, int packSize);
void Close();
//bind to a channel
int Bind(const char* ip, int port, int channel = -1);
int Bind(IPaddress add, int channel = -1);
//bind to an available channel
int Bind(const char* ip, int port) {
Bind(ip, port, -1);
}
int Bind(IPaddress* add) {
Bind(add, -1);
}
//bind to certain channel
int Bind(const char* ip, int port, int channel);
int Bind(IPaddress* add, int channel);
void Unbind(int channel);
IPaddress* GetIPAddress(int channel) {
return SDLNet_UDP_GetPeerAddress(socket, channel);
}
//send a buffer
int SendTo(const char* ip, int port, void* data, int len);
int SendTo(IPaddress add, void* data, int len);
int SendTo(int channel, void* data, int len);
int SendToAllChannels(void* data, int len);
int Send(const char* ip, int port, void* data, int len);
int Send(IPaddress* add, void* data, int len);
int Send(int channel, void* data, int len);
int SendAll(void* data, int len);
int Receive();
//send a SerialPacketBase
int SendTo(const char* ip, int port, SerialPacketBase* serialPacket);
int SendTo(IPaddress add, SerialPacketBase* serialPacket);
int SendTo(int channel, SerialPacketBase* serialPacket);
int SendToAllChannels(SerialPacketBase* serialPacket);
int Receive(SerialPacketBase* serialPacket);
//accessors
UDPpacket* GetPacket() const {
return packet;
void* GetOutData() const {
return reinterpret_cast<void*>(packOut->data);
};
void* GetInData() const {
return reinterpret_cast<void*>(packIn->data);
};
UDPpacket* GetOutPacket() const {
return packOut;
}
UDPpacket* GetInPacket() const {
return packIn;
}
UDPsocket GetSocket() const {
return socket;
}
private:
friend Singleton<UDPNetworkUtility>;
UDPNetworkUtility() = default;
~UDPNetworkUtility() = default;
UDPsocket socket = nullptr;
UDPpacket* packet = nullptr;
UDPpacket* packOut = nullptr;
UDPpacket* packIn = nullptr;
};
#endif
-37
View File
@@ -1,37 +0,0 @@
#config
INCLUDES+=. ../graphics
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=../..
OUT=$(addprefix $(OUTDIR)/,libcommon.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
clean:
$(RM) *.o *.a *.exe
rebuild: clean all
-139
View File
@@ -1,139 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "menu_bar.hpp"
#include <stdexcept>
#include <sstream>
void MenuBar::DrawTo(SDL_Surface* const dest) {
for (auto& i : entries) {
i.DrawTo(dest);
}
}
void MenuBar::MouseMotion(SDL_MouseMotionEvent const& motion) {
for (auto& i : entries) {
i.MouseMotion(motion);
}
}
void MenuBar::MouseButtonDown(SDL_MouseButtonEvent const& button) {
for (auto& i : entries) {
i.MouseButtonDown(button);
}
}
void MenuBar::MouseButtonUp(SDL_MouseButtonEvent const& button, int* entry, int* butt) {
*entry = *butt = -1;
int ret = -1;
for (auto& i : entries) {
ret = i.MouseButtonUp(button);
if (ret != -1) {
*entry = (&i - entries.data());
*butt = ret;
}
}
}
void MenuBar::SetEntries(std::vector<std::vector<std::string>> info) {
if (!image || !font) {
throw(std::runtime_error("Surfaces not loaded into the menu bar"));
}
entries.clear();
for (int i = 0; i < info.size(); i++) {
//create the entry & the main button
entries.push_back(MenuBarEntry());
entries[i].mainButton.SetImage(image);
entries[i].mainButton.SetFont(font);
entries[i].mainButton.SetText(info[i][0]);
entries[i].mainButton.SetX(i * image->GetClipW());
entries[i].mainButton.SetY(0);
for (int j = 0; j < info[i].size()-1; j++) {
//create each drop button in this entry
entries[i].dropButtons.push_back(Button());
entries[i].dropButtons[j].SetImage(image);
entries[i].dropButtons[j].SetFont(font);
entries[i].dropButtons[j].SetText(info[i][j+1]);
entries[i].dropButtons[j].SetX(i * image->GetClipW());
entries[i].dropButtons[j].SetY((j+1) * image->GetClipH());
}
}
}
void MenuBar::MenuBarEntry::DrawTo(SDL_Surface* const dest) {
//only draw the dropButtons in the user has this menu open
mainButton.DrawTo(dest);
if (!open) {
return;
}
for (auto& i : dropButtons) {
i.DrawTo(dest);
}
}
void MenuBar::MenuBarEntry::MouseMotion(SDL_MouseMotionEvent const& motion) {
//open the menu
bool o = mainButton.MouseMotion(motion) == Button::State::PRESSED;
if (!(open |= o)) {
return;
}
for (auto& i : dropButtons) {
//dragging down the menu
o |= i.MouseMotion(motion) == Button::State::PRESSED;
}
open = o;
}
void MenuBar::MenuBarEntry::MouseButtonDown(SDL_MouseButtonEvent const& button) {
//open the menu
if (!(open = mainButton.MouseButtonDown(button) == Button::State::PRESSED)) {
return;
}
//update the others anyway
for (auto& i : dropButtons) {
i.MouseButtonDown(button);
}
}
int MenuBar::MenuBarEntry::MouseButtonUp(SDL_MouseButtonEvent const& button) {
int ret = -1;
mainButton.MouseButtonUp(button);
for (auto& i : dropButtons) {
//the user just released this button
if (i.GetState() != i.MouseButtonUp(button) && i.GetState() == Button::State::HOVER && open) {
//get this button's index
ret = (&i - dropButtons.data());
}
}
open = false;
return ret;
}
-92
View File
@@ -1,92 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef MENUBAR_HPP_
#define MENUBAR_HPP_
#include "image.hpp"
#include "raster_font.hpp"
#include "button.hpp"
#include <string>
#include <vector>
/* I've redesigned this so that the contents of the menu bar can't change during run time.
* This is more restrictive but I'm focusing on getting this working first.
* The Image and Font pointers must be set before the text data is entered.
*
* This class needs a rewrite.
*/
//TODO: This thing is fucking terrible, fix it and the button class
class MenuBar {
public:
MenuBar() = default;
~MenuBar() = default;
//yet another draw function
void DrawTo(SDL_Surface* const dest);
//user inputs
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
void MouseButtonUp(SDL_MouseButtonEvent const&, int* entry, int* button);
//manage the entries & buttons
void SetEntries(std::vector<std::vector<std::string>> info);
void ClearEntries() { entries.clear(); }
//Accessors and mutators
Image* SetImage(Image* const ptr) { return image = ptr; }
Image* GetImage() { return image; }
RasterFont* SetFont(RasterFont* const ptr) { return font = ptr; }
RasterFont* GetFont() { return font; }
private:
class MenuBarEntry;
std::vector<MenuBarEntry> entries;
Image* image = nullptr;
RasterFont* font = nullptr;
};
class MenuBar::MenuBarEntry {
public:
MenuBarEntry() = default;
~MenuBarEntry() = default;
void DrawTo(SDL_Surface* const dest);
void MouseMotion(SDL_MouseMotionEvent const&);
void MouseButtonDown(SDL_MouseButtonEvent const&);
int MouseButtonUp(SDL_MouseButtonEvent const&);
private:
Button mainButton;
std::vector<Button> dropButtons;
bool open = false;
friend class MenuBar;
};
#endif
-78
View File
@@ -1,78 +0,0 @@
/* Copyright: (c) Kayne Ruse 2013, 2014
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#ifndef BOUNDINGBOX_HPP_
#define BOUNDINGBOX_HPP_
#include <type_traits>
#include <algorithm>
class BoundingBox {
public:
//This is explicitly a POD
int x, y;
int w, h;
BoundingBox() = default;
BoundingBox(int i, int j): x(i), y(j), w(0), h(0) {};
BoundingBox(int i, int j, int k, int l): x(i), y(j), w(k), h(l) {};
~BoundingBox() = default;
BoundingBox& operator=(BoundingBox const&) = default;
int Size() {
return std::max(w*h,0);
}
bool CheckOverlap(BoundingBox rhs) {
return !(
x >= rhs.x + rhs.w ||
y >= rhs.y + rhs.h ||
rhs.x >= x + w ||
rhs.y >= y + h);
}
BoundingBox CalcOverlap(BoundingBox rhs) {
if (!CheckOverlap(rhs)) {
return {0, 0, 0, 0};
}
BoundingBox ret;
ret.x = std::max(x, rhs.x);
ret.y = std::max(y, rhs.y);
ret.w = std::min(x+w, rhs.x+rhs.w) - ret.x;
ret.h = std::min(y+h, rhs.y+rhs.h) - ret.y;
return ret;
}
};
//This is explicitly a POD
static_assert(std::is_pod<BoundingBox>::value, "BoundingBox is not a POD");
#include "vector2.hpp"
//operators
inline BoundingBox operator+(BoundingBox b, Vector2 v) {
return {b.x + (int)v.x, b.y + (int)v.y, b.w, b.h};
}
inline BoundingBox operator+(Vector2 v, BoundingBox b) {
return b + v;
}
#endif

Some files were not shown because too many files have changed in this diff Show More