diff --git a/Button.cpp b/Button.cpp new file mode 100644 index 0000000..4672323 --- /dev/null +++ b/Button.cpp @@ -0,0 +1,76 @@ +#include "Button.h" +#include +#include "Util.h" +#include "Vector.h" +#include "Cursor.h" + +Button::Button(const std::string & text, Vec2f position, float width, float height) : Text(text,position) +{ + this->width = width; + this->height = height; + this->planePosition = position; + + cursorOnButton = false; + alfa = 0.5f; + background = Vec3f(10, 10, 10); + //foreground = Vec3f(255, 255, 255); + this->setColor(Vec3f(255, 255, 255)); + + this->position.x += width / 2 - textWidth / 2; + this->position.y += height / 2 - textHeight / 2; +} + +Button::~Button() +{ + /*if (action != nullptr) + delete action;*/ +} + +void Button::draw(void) +{ + + glColor4f(background.x/255.0f, background.y / 255.0f, background.z / 255.0f, alfa); + + glBegin(GL_QUADS); + glVertex2f(planePosition.x, planePosition.y); + glVertex2f(planePosition.x, planePosition.y + height); + glVertex2f(planePosition.x + width, planePosition.y + height); + glVertex2f(planePosition.x + width, planePosition.y); + glEnd(); + + /*glColor4f(foreground.x / 255.0f, foreground.y / 255.0f, foreground.z / 255.0f, 1.0f); + Util::glutBitmapString(text, position.x, position.y+height/2+14/2);*/ + Text::draw(); +} + +void Button::update(int x, int y) +{ + cursorOnButton = + (x > planePosition.x && x < planePosition.x + width) && + y > planePosition.y && y < planePosition.y + height; + + + if (cursorOnButton) + alfa = 1.0f; + else + alfa = 0.5f; + + if (cursorOnButton && Cursor::getInstance()->clicked) + if(action != nullptr) + action(this); +} + +void Button::addAction(action_function action) +{ + this->action = action; +} + +void Button::setForeground(Vec3f color) +{ + this->setColor(color); +} + +void Button::setBackground(Vec3f color) +{ + background = color; +} diff --git a/Button.h b/Button.h new file mode 100644 index 0000000..27d617e --- /dev/null +++ b/Button.h @@ -0,0 +1,30 @@ +#pragma once +#include "Text.h" + + + +class Button : public Text +{ +private: + typedef void(*action_function)(Button* b); + float width, height; + Vec3f background; + Vec2f planePosition; + bool cursorOnButton; + float alfa; + action_function action = nullptr; +public: + Button(const std::string &text, Vec2f position, float width, float height); + ~Button(); + + + + void draw(); + void update(int x, int y); + + void addAction(action_function action); + + void setForeground(Vec3f color); + void setBackground(Vec3f color); +}; + diff --git a/CMakeLists.txt b/CMakeLists.txt index 180810f..ca1bc26 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,15 +1,17 @@ cmake_minimum_required(VERSION 3.5) project(CrystalPoint) -file(GLOB SOURCE_FILES +file(GLOB_RECURSE SOURCE_FILES "*.h" "*.cpp" + "*.cc" ) add_executable(CrystalPoint ${SOURCE_FILES}) find_package(OpenGL REQUIRED) find_package(GLUT REQUIRED) -include_directories( ${OPENGL_INCLUDE_DIRS} ${GLUT_INCLUDE_DIRS} ) -target_link_libraries(CrystalPoint ${OPENGL_LIBRARIES} ${GLUT_LIBRARY} ) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall ") +find_package(OpenAL REQUIRED) +include_directories( ${OPENGL_INCLUDE_DIRS} ${GLUT_INCLUDE_DIRS} ${OPENAL_INCLUDE_DIRS} ) +target_link_libraries(CrystalPoint ${OPENGL_LIBRARIES} ${GLUT_LIBRARY} ${OPENAL_LIBRARY} ) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -lpthread") \ No newline at end of file diff --git a/Controller.cpp b/Controller.cpp index a5b9b3d..892b5e8 100644 --- a/Controller.cpp +++ b/Controller.cpp @@ -8,6 +8,7 @@ Controller::Controller(int controllerId) { this->controllerId = controllerId; this->ypr = Vec3f(); this->joystick = Vec2f(); + this->setConnected(false); this->setConnected(true); } diff --git a/ControllerHandler.cpp b/ControllerHandler.cpp index 4fed053..03aaf2f 100644 --- a/ControllerHandler.cpp +++ b/ControllerHandler.cpp @@ -4,9 +4,6 @@ #include "ControllerHandler.h" #include -#include -#include -#include /* * String split helper functions @@ -30,10 +27,24 @@ ControllerHandler::ControllerHandler(){ }; Controller* ControllerHandler::getLeftController(void){ - for (auto e : controllers) + for (int i = 0; i < 4; i++) { - if(e != nullptr && e->isConnected()){ - return e; + if(controllers[i] != nullptr && controllers[i]->isConnected()){ + return controllers[i]; + } + } + return nullptr; +} + +Controller* ControllerHandler::getRightController(void){ + bool c1found = false; + for (int i = 0; i < 4; i++) + { + if(controllers[i] != nullptr && controllers[i]->isConnected()){ + if(c1found){ + return controllers[i]; + } + c1found = true; } } return nullptr; @@ -107,8 +118,8 @@ void ControllerHandler::commandControllerData(std::vector data) { c->ypr.y = std::stoi(data[6])/100.0f; c->ypr.z = std::stoi(data[7])/100.0f; - c->joystick.x = std::stoi(data[2])/3000.0f; - c->joystick.y = std::stoi(data[3])/3000.0f; + c->joystick.x = std::stoi(data[2])/2000.0f; + c->joystick.y = std::stoi(data[3])/2000.0f; c->joystickButton = !(data[4] == "0"); c->magnetSwitch = !(data[9] == "0"); @@ -128,9 +139,10 @@ void ControllerHandler::commandControllerEvent(std::vector data) { } void ControllerHandler::commandControllerList(std::vector data) { - for(unsigned int i = 1; i < data.size() -1; i++){ + for(unsigned int i = 1; i < data.size() - 1; i++){ int controllerId = std::stoi(data[i]); controllers[controllerId] = new Controller(controllerId); + rumble(controllerId, 100, 100); } if(basestationFound) baseStation->write("start\n"); diff --git a/ControllerHandler.h b/ControllerHandler.h index 3c306b6..1e23791 100644 --- a/ControllerHandler.h +++ b/ControllerHandler.h @@ -5,13 +5,21 @@ #define BasestationBaudrate 115200 #include + +#ifdef WIN32 #include "include/serial.h" +#else +#include "lib/serial/include/serial.h" +#endif + + #include "Controller.h" class ControllerHandler{ public: ControllerHandler(); Controller* getLeftController(void); + Controller* getRightController(void); void rumble(int idController, int duration, int power); private: void SearchBasestation(void); @@ -20,7 +28,7 @@ private: bool basestationFound; serial::Serial *baseStation; std::thread readthread; - std::vector controllers {0}; + Controller* controllers[4]; //Command functions void commandDebug(std::vector data); diff --git a/CrystalPoint.cpp b/CrystalPoint.cpp index 0d3bd76..52b44fa 100644 --- a/CrystalPoint.cpp +++ b/CrystalPoint.cpp @@ -5,23 +5,33 @@ #include #include "WorldHandler.h" #include "Player.h" +#include "Cursor.h" +#include "Menu.h" +#include "Text.h" +#include "Vector.h" +#include "Button.h" int CrystalPoint::width = 0; int CrystalPoint::height = 0; SoundSystem CrystalPoint::sound_system; +bool state = false; + + void CrystalPoint::init() { player = Player::getInstance(); worldhandler = WorldHandler::getInstance(); - //cursor = Cursor::getInstance(); + cursor = Cursor::getInstance(); + + menu = new Menu(); + buildMenu(); lastFrameTime = 0; + state = true; glClearColor(0.7f, 0.7f, 1.0f, 1.0f); - - mousePosition = Vec2f(width / 2, height / 2); } @@ -39,9 +49,10 @@ void CrystalPoint::draw() glMatrixMode(GL_MODELVIEW); glLoadIdentity(); + worldhandler->draw(); - player->draw(); - + if(!state) + menu->draw(); //cursor->draw(); glutSwapBuffers(); @@ -54,68 +65,86 @@ void CrystalPoint::update() float deltaTime = frameTime - lastFrameTime; lastFrameTime = frameTime; - if (keyboardState.special[GLUT_KEY_LEFT] && !prevKeyboardState.special[GLUT_KEY_LEFT]) - worldhandler->PreviousWorld(); - if (keyboardState.special[GLUT_KEY_RIGHT] && !prevKeyboardState.special[GLUT_KEY_RIGHT]) - worldhandler->NextWorld(); - if (keyboardState.keys[27]) - exit(0); + if (state) + { + if (keyboardState.special[GLUT_KEY_LEFT] && !prevKeyboardState.special[GLUT_KEY_LEFT]) + worldhandler->PreviousWorld(); + if (keyboardState.special[GLUT_KEY_RIGHT] && !prevKeyboardState.special[GLUT_KEY_RIGHT]) + worldhandler->NextWorld(); + if (keyboardState.keys[27]) + state = false; - Player* player = Player::getInstance(); + Player* player = Player::getInstance(); - player->rotation.y += mouseOffset.x / 10.0f; - player->rotation.x += mouseOffset.y / 10.0f; - if (player->rotation.x > 90) - player->rotation.x = 90; - if (player->rotation.x < -90) - player->rotation.x = -90; + player->rotation.y += mouseOffset.x / 10.0f; + player->rotation.x += mouseOffset.y / 10.0f; - float speed = 10; - Vec3f oldPosition = player->position; - if (keyboardState.keys['a']) player->setPosition(0, deltaTime*speed, false); - if (keyboardState.keys['d']) player->setPosition(180, deltaTime*speed, false); - if (keyboardState.keys['w']) player->setPosition(90, deltaTime*speed, false); - if (keyboardState.keys['s']) player->setPosition(270, deltaTime*speed, false); - if (keyboardState.keys['q']) player->setPosition(1, deltaTime*speed, true); - if (keyboardState.keys['e']) player->setPosition(-1, deltaTime*speed, true); + float speed = 10; - Controller *leftcontroller = controller.getLeftController(); - if (leftcontroller != nullptr) { - Vec2f *leftControllerJoystick = &leftcontroller->joystick; + Vec3f oldPosition = player->position; + if (keyboardState.keys['a']) player->setPosition(0, deltaTime*speed, false); + if (keyboardState.keys['d']) player->setPosition(180, deltaTime*speed, false); + if (keyboardState.keys['w']) player->setPosition(90, deltaTime*speed, false); + if (keyboardState.keys['s']) player->setPosition(270, deltaTime*speed, false); + if (keyboardState.keys['q']) player->setPosition(1, deltaTime*speed, true); + if (keyboardState.keys['e']) player->setPosition(-1, deltaTime*speed, true); - if (leftcontroller->joystickButton) { - controller.rumble(leftcontroller->controllerId, 100, 100); + Controller *leftcontroller = controller.getLeftController(); + if (leftcontroller != nullptr) { + Vec2f *leftControllerJoystick = &leftcontroller->joystick; + + + if (leftcontroller->joystickButton) { + controller.rumble(leftcontroller->controllerId, 100, 100); + } + + + if (leftControllerJoystick->y > 0.3) { + player->setPosition(270, leftControllerJoystick->y * deltaTime, false); + } + else if (leftControllerJoystick->y < -0.3) { + player->setPosition(90, leftControllerJoystick->y * -1 * deltaTime, false); + } + if (leftControllerJoystick->x > 0.3) { + player->setPosition(180, leftControllerJoystick->x * deltaTime, false); + } + else if (leftControllerJoystick->x < -0.3) { + player->setPosition(0, leftControllerJoystick->x * -1 * deltaTime, false); + } + + player->leftWeapon->rotateWeapon(Vec3f(leftcontroller->ypr.y + 140, 0, -leftcontroller->ypr.z)); + + } + Controller *rightcontroller = controller.getRightController(); + if(rightcontroller != nullptr){ + Vec2f *rightControllerJoystick = &rightcontroller->joystick; + if (rightControllerJoystick->y > 0.3 || rightControllerJoystick->y < -0.3) { + player->rotation.x += rightcontroller->joystick.y/2; + } + + if (rightControllerJoystick->x > 0.3 || rightControllerJoystick->x < -0.3) { + player->rotation.y += rightcontroller->joystick.x/2; + } } - if (leftControllerJoystick->y > 0.3) { - player->setPosition(270, leftControllerJoystick->y*deltaTime, false); - } - else if (leftControllerJoystick->y < -0.3) { - player->setPosition(90, leftControllerJoystick->y*-1 * deltaTime, false); - } - if (leftControllerJoystick->x > 0.3) { - player->setPosition(180, leftControllerJoystick->x*deltaTime, false); - } - else if (leftControllerJoystick->x < -0.3) { - player->setPosition(0, leftControllerJoystick->x*-1 * deltaTime, false); - } - - player->leftWeapon->rotateWeapon(Vec3f(leftcontroller->ypr.y + 140, 0, -leftcontroller->ypr.z)); + if (player->rotation.x > 90) + player->rotation.x = 90; + if (player->rotation.x < -90) + player->rotation.x = -90; + if (!worldhandler->isPlayerPositionValid()) + player->position = oldPosition; + player->position.y = worldhandler->getHeight(player->position.x, player->position.z) + 1.7f; + worldhandler->update(deltaTime); + } + else + { + menu->update(); + cursor->update(cursor->mousePosition + mouseOffset); } - if (!worldhandler->isPlayerPositionValid()) - player->position = oldPosition; - - player->position.y = worldhandler->getHeight(player->position.x, player->position.z) + 1.7f; - - worldhandler->update(deltaTime); - - mousePosition = mousePosition + mouseOffset; - //cursor->update(mousePosition); - mouseOffset = Vec2f(0, 0); prevKeyboardState = keyboardState; glutPostRedisplay(); @@ -123,6 +152,28 @@ void CrystalPoint::update() sound_system.SetListener(player->position, Vec3f(), Vec3f()); } +void CrystalPoint::buildMenu() +{ + Button* start = new Button("Resume", Vec2f(1920 / 2 - 50, 1080 / 2 - 30), 100, 50); + auto toWorld = [](Button* b) + { + state = true; + }; + start->addAction(toWorld); + menu->AddMenuElement(start); + + + Button* test = new Button("Exit", Vec2f(1920 / 2 - 50, 1080 / 2 + 30), 100, 50); + test->addAction([](Button* b) + { + exit(0); + }); + menu->AddMenuElement(test); + Text* t = new Text("Pause", Vec2f(1920 / 2 - Util::glutTextWidth("Pause") / 2, 1080 / 2 - 75)); + t->setColor(Vec3f(255, 255, 0)); + menu->AddMenuElement(t); +} + KeyboardState::KeyboardState() diff --git a/CrystalPoint.h b/CrystalPoint.h index 1e36bea..3ab6e53 100644 --- a/CrystalPoint.h +++ b/CrystalPoint.h @@ -3,6 +3,8 @@ class WorldHandler; class SoundSystem; class Player; +class Cursor; +class Menu; #include "Vector.h" #include "SoundSystem.h" #include "ControllerHandler.h" @@ -27,6 +29,8 @@ public: WorldHandler* worldhandler; Player* player; ControllerHandler controller; + Cursor* cursor; + Menu* menu; static int width, height; KeyboardState keyboardState; @@ -38,7 +42,9 @@ public: float lastFrameTime; static SoundSystem& GetSoundSystem() { return sound_system; } + private: static SoundSystem sound_system; + void buildMenu(); }; \ No newline at end of file diff --git a/Cursor.cpp b/Cursor.cpp index 69895a3..d5ce794 100644 --- a/Cursor.cpp +++ b/Cursor.cpp @@ -1,5 +1,5 @@ #include "Cursor.h" -#include +#include #include #include "CrystalPoint.h" @@ -8,10 +8,13 @@ Cursor* Cursor::instance = NULL; Cursor::Cursor() { enabled = false; + mousePosition = Vec2f(CrystalPoint::width / 2, CrystalPoint::height / 2); + clicked = false; } Cursor::~Cursor() { + } Cursor* Cursor::getInstance(void) @@ -54,5 +57,24 @@ void Cursor::draw(void) void Cursor::update(Vec2f newPosition) { + if (newPosition.x < 0) + newPosition.x = 0; + + if (newPosition.y < 0) + newPosition.y = 0; + + if (newPosition.x > CrystalPoint::width) + newPosition.x = CrystalPoint::width; + + if (newPosition.y > CrystalPoint::height) + newPosition.y = CrystalPoint::height; + mousePosition = newPosition; + + if (clicked) + clicked = !clicked; + if (state != prev) + if(state == GLUT_UP) + clicked = true; + prev = state; } diff --git a/Cursor.h b/Cursor.h index 78764f0..dd0835e 100644 --- a/Cursor.h +++ b/Cursor.h @@ -8,9 +8,9 @@ private: static Cursor* instance; bool enabled; - Vec2f mousePosition; -public: +public: + Vec2f mousePosition; ~Cursor(); static Cursor* getInstance(void); @@ -18,6 +18,10 @@ public: void enable(bool enable); bool isEnabled(void); + bool clicked; + int state, prev; + + void draw(void); void update(Vec2f newPosition); }; diff --git a/Enemy.cpp b/Enemy.cpp index 3c802b2..36c3f44 100644 --- a/Enemy.cpp +++ b/Enemy.cpp @@ -2,7 +2,6 @@ #include #include "Enemy.h" #include "Model.h" -#include "CrystalPoint.h" #include Enemy::Enemy(const std::string &fileName, @@ -19,7 +18,8 @@ Enemy::Enemy(const std::string &fileName, speed = 1; radius = 10; hasTarget = false; - hit_sound_id = CrystalPoint::GetSoundSystem().LoadSound("WAVE/Sound.wav", false); + hit_sound_id = CrystalPoint::GetSoundSystem().LoadSound("WAVE/enemy.wav", false); + music = CrystalPoint::GetSoundSystem().GetSound(hit_sound_id); attack = false; } @@ -72,9 +72,14 @@ void Enemy::collide(const Entity * entity) void Enemy::update(float delta) { + music->SetPos(position, Vec3f()); + if (hasTarget) { - + if (music->IsPlaying() == false) + { + music->Play(); + } //just 2d walking float dx, dz, length; @@ -98,15 +103,14 @@ void Enemy::update(float delta) else { attack = true; + if (music->IsPlaying() == true) + { +// music->Pause(); + music->Stop(); + } } rotation.y = atan2f(dx, dz) * 180 / M_PI; } - if (false) - { - Sound* sound = CrystalPoint::GetSoundSystem().GetSound(hit_sound_id); - sound->SetPos(position, Vec3f()); - sound->Play(); - } } \ No newline at end of file diff --git a/Enemy.h b/Enemy.h index 4908738..d1376c8 100644 --- a/Enemy.h +++ b/Enemy.h @@ -3,6 +3,7 @@ #include "Entity.h" #include #include "Vector.h" +#include "CrystalPoint.h" class Enemy : public Entity { @@ -10,6 +11,8 @@ public: Enemy(const std::string &fileName,const Vec3f &position,Vec3f &rotation,const float &scale); ~Enemy(); + Sound* music; + bool hasTarget; Vec3f target; float speed,radius; diff --git a/HeightMap.cpp b/HeightMap.cpp index 99e4924..61aef40 100644 --- a/HeightMap.cpp +++ b/HeightMap.cpp @@ -1,6 +1,6 @@ #include "HeightMap.h" #include "stb_image.h" -#include "vector.h" +#include "Vector.h" #include "LevelObject.h" @@ -127,6 +127,7 @@ float HeightMap::GetHeight(float x, float y) float labda3 = 1 - labda1 - labda2; Vertex z = a * labda1 + b * labda2 + c * labda3; +// Vertex z = (a * labda1) + (b * labda2) ; return z.y; } diff --git a/Interface.cpp b/Interface.cpp index c5ee6ba..0f912de 100644 --- a/Interface.cpp +++ b/Interface.cpp @@ -1,13 +1,11 @@ #include "Interface.h" -#include +#include #include "CrystalPoint.h" #include #include "Player.h" - -//Prototype -void glutBitmapString(std::string str, int x, int y); +#include "Util.h" Interface::Interface() { @@ -87,7 +85,7 @@ void Interface::draw() //Text: level glColor4f(1.0f, 1.0f, 0.1f, 1.0); - glutBitmapString("Level: " + std::to_string(player->level), 490, 900); + Util::glutBitmapString("Level: " + std::to_string(player->level), 490, 900); for (int i = 0; i < maxCrystals; i++) { @@ -118,13 +116,4 @@ void Interface::draw() void Interface::update(float deltaTime) { -} - -void glutBitmapString(std::string str, int x, int y) -{ - glRasterPos2f(x, y); - for (int i = 0; i < str.size(); i++) - { - glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str[i]); - } } \ No newline at end of file diff --git a/Main.cpp b/Main.cpp index b7c7c06..f593110 100644 --- a/Main.cpp +++ b/Main.cpp @@ -4,6 +4,11 @@ #include #include "Vector.h" +#define STB_IMAGE_IMPLEMENTATION +#include "stb_image.h" + +#include "Cursor.h" + void configureOpenGL(void); CrystalPoint* app; @@ -50,6 +55,17 @@ int main(int argc, char* argv[]) glutPassiveMotionFunc(mousemotion); glutMotionFunc(mousemotion); + auto mouseclick = [](int button, int state, + int x, int y) + { + if (button == GLUT_LEFT_BUTTON) + Cursor::getInstance()->state = state; + + //std::cout << "Left button is down" << std::endl; + }; + + glutMouseFunc(mouseclick); + CrystalPoint::height = GLUT_WINDOW_HEIGHT; CrystalPoint::width = GLUT_WINDOW_WIDTH; @@ -66,7 +82,8 @@ void configureOpenGL() glutInitWindowSize(800, 600); //glutInitWindowPosition(glutGet(GLUT_WINDOW_WIDTH) / 2 - 800/2, glutGet(GLUT_WINDOW_HEIGHT) / 2 - 600/2); glutCreateWindow("Crystal Point"); - //glutFullScreen(); + glutFullScreen(); + //Depth testing glEnable(GL_DEPTH_TEST); diff --git a/Menu.cpp b/Menu.cpp new file mode 100644 index 0000000..0829976 --- /dev/null +++ b/Menu.cpp @@ -0,0 +1,59 @@ +#include +#include "Menu.h" +#include "CrystalPoint.h" + +Menu::Menu() +{ + cursor = Cursor::getInstance(); +} + + +Menu::~Menu() +{ +} + +void Menu::draw(void) +{ + //Switch view to Ortho + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, CrystalPoint::width, CrystalPoint::height, 0, -10, 10); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glDisable(GL_LIGHTING); + glDisable(GL_DEPTH_TEST); + glDisable(GL_TEXTURE_2D); + + glColor4f(60/255.0f, 60/255.0f, 60/255.0f, 0.8f); + glBegin(GL_QUADS); + glVertex2f(0,0); + glVertex2f(0, CrystalPoint::height); + glVertex2f(CrystalPoint::width, CrystalPoint::height); + glVertex2f(CrystalPoint::width, 0); + glEnd(); + + + for (MenuElement* e : elements) + { + e->draw(); + } + + cursor->draw(); + + glEnable(GL_LIGHTING); + glEnable(GL_DEPTH_TEST); +} + +void Menu::update() +{ + for (MenuElement* e : elements) + { + e->update(cursor->mousePosition.x, cursor->mousePosition.y); + } +} + +void Menu::AddMenuElement(MenuElement * e) +{ + elements.push_back(e); +} diff --git a/Menu.h b/Menu.h new file mode 100644 index 0000000..afed8ee --- /dev/null +++ b/Menu.h @@ -0,0 +1,20 @@ +#pragma once +#include +#include "MenuElement.h" +#include "Cursor.h" + +class Menu +{ +private: + std::vector elements; + Cursor* cursor; +public: + Menu(); + ~Menu(); + + void draw(void); + void update(void); + + void AddMenuElement(MenuElement* e); +}; + diff --git a/MenuElement.cpp b/MenuElement.cpp new file mode 100644 index 0000000..e5bc349 --- /dev/null +++ b/MenuElement.cpp @@ -0,0 +1,12 @@ +#include "MenuElement.h" + +MenuElement::MenuElement(Vec2f position) +{ + hover = false; + this->position = position; +} + + +MenuElement::~MenuElement() +{ +} diff --git a/MenuElement.h b/MenuElement.h new file mode 100644 index 0000000..4f09c21 --- /dev/null +++ b/MenuElement.h @@ -0,0 +1,17 @@ +#pragma once +#include "Vector.h" +#include + +class MenuElement +{ +protected: + bool hover; + Vec2f position; +public: + MenuElement(Vec2f position); + ~MenuElement(); + + virtual void draw(void) {}; + virtual void update(int x, int y) {}; +}; + diff --git a/Model.cpp b/Model.cpp index 48c91a5..e2eaf91 100644 --- a/Model.cpp +++ b/Model.cpp @@ -1,6 +1,5 @@ #include "Model.h" -#define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include @@ -8,6 +7,7 @@ #include #include #include +#include //Prototypes std::vector split(std::string str, std::string sep); @@ -138,7 +138,7 @@ Model::Model(std::string fileName) radius = fmax(radius, (center.x - v.x) * (center.x - v.x) + (center.z - v.z) * (center.z - v.z)); radius = sqrt(radius); - for each(ObjGroup *group in groups) + for (ObjGroup *group : groups) { Optimise(group); } @@ -148,7 +148,7 @@ void Model::Optimise(ObjGroup *t) { for (Face &face : t->faces) { - for each(auto &vertex in face.vertices) + for (auto &vertex : face.vertices) { t->VertexArray.push_back(Vertex(vertices[vertex.position].x, vertices[vertex.position].y, vertices[vertex.position].z, normals[vertex.normal].x, normals[vertex.normal].y, normals[vertex.normal].z, diff --git a/Player.cpp b/Player.cpp index 10f1b2d..32b7005 100644 --- a/Player.cpp +++ b/Player.cpp @@ -15,6 +15,9 @@ Player::Player() leftWeapon = new Weapon("models/weapons/ZwaardMetTextures/TextureZwaard.obj", 1, position, rotation, Vec3f(4.5, -8, -1), Vec3f(-2.0f, 6.0f, -2.1f), Vec2f(170, 70), Vec2f(20, -80)); leftWeapon->rotateWeapon(Vec3f(150, 0, 60)); + + rightWeapon = new Weapon("models/weapons/ZwaardMetTextures/TextureZwaard.obj", 1, position, rotation, Vec3f(3, -8, -1), Vec3f(-2.0f, 6.0f, -2.1f), Vec2f(170, 70), Vec2f(20, -80)); + rightWeapon->rotateWeapon(Vec3f(150, 0, 60)); } Player* Player::getInstance() @@ -64,4 +67,5 @@ void Player::setPosition(float angle, float fac, bool height) void Player::draw() { leftWeapon->draw(); + rightWeapon->draw(); } \ No newline at end of file diff --git a/Skybox.cpp b/Skybox.cpp index bd91a23..8a9b958 100644 --- a/Skybox.cpp +++ b/Skybox.cpp @@ -1,6 +1,7 @@ #include "cmath" #include +#include "Util.h" #include "stb_image.h" #include "Skybox.h" #include @@ -25,12 +26,12 @@ Skybox::~Skybox() void Skybox::init() { - skybox[SKY_LEFT] = loadTexture(folder + "left.png"); - skybox[SKY_BACK] = loadTexture(folder + "back.png"); - skybox[SKY_RIGHT] = loadTexture(folder + "right.png"); - skybox[SKY_FRONT] = loadTexture(folder + "front.png"); - skybox[SKY_TOP] = loadTexture(folder + "top.png"); - skybox[SKY_BOTTOM] = loadTexture(folder + "bottom.png"); + skybox[SKY_LEFT] = Util::loadTexture(folder + "left.png"); + skybox[SKY_BACK] = Util::loadTexture(folder + "back.png"); + skybox[SKY_RIGHT] = Util::loadTexture(folder + "right.png"); + skybox[SKY_FRONT] = Util::loadTexture(folder + "front.png"); + skybox[SKY_TOP] = Util::loadTexture(folder + "top.png"); + skybox[SKY_BOTTOM] = Util::loadTexture(folder + "bottom.png"); } void Skybox::draw() diff --git a/Skybox.h b/Skybox.h index 84c5a98..0f0cbbf 100644 --- a/Skybox.h +++ b/Skybox.h @@ -14,6 +14,8 @@ public: void init(); void draw(); + void update(float deltaTime, int, int); GLuint loadTexture(const std::string &fileName); + }; diff --git a/Sound.cpp b/Sound.cpp index cc990da..a3cc983 100644 --- a/Sound.cpp +++ b/Sound.cpp @@ -1,14 +1,22 @@ #include "Sound.h" #include +#ifdef WIN32 #include #include +#else +#include +typedef unsigned long DWORD; +typedef unsigned short WORD; +typedef unsigned int UNINT32; +typedef unsigned char BYTE; +#endif + Sound::Sound(const char* inWavPath, bool inLooping): buffer_id(0), source_id(0), is_looping(inLooping) - { const char* path = inWavPath; @@ -137,3 +145,12 @@ void Sound::Stop() alSourceStop(source_id); } +bool Sound::IsPlaying() +{ + ALenum state; + + alGetSourcei(source_id, AL_SOURCE_STATE, &state); + + return (state == AL_PLAYING); +} + diff --git a/Sound.h b/Sound.h index 74e2f9f..02fe227 100644 --- a/Sound.h +++ b/Sound.h @@ -1,6 +1,6 @@ #pragma once -#include "vector.h" +#include "Vector.h" class Sound { @@ -13,6 +13,7 @@ public: void Play(); void Pause(); void Stop(); + bool IsPlaying(); private: unsigned int buffer_id; diff --git a/SoundSystem.cpp b/SoundSystem.cpp index bd207be..f57a526 100644 --- a/SoundSystem.cpp +++ b/SoundSystem.cpp @@ -1,11 +1,5 @@ #include "SoundSystem.h" -#include -#include -#include - - - SoundSystem::SoundSystem(): device(nullptr), context(nullptr) diff --git a/SoundSystem.h b/SoundSystem.h index d6908ce..b9e289b 100644 --- a/SoundSystem.h +++ b/SoundSystem.h @@ -1,9 +1,16 @@ #pragma once #include + +#ifdef WIN32 #include #include -#include "vector.h" +#else +#include +#include +#endif + +#include "Vector.h" #include "Sound.h" diff --git a/Text.cpp b/Text.cpp new file mode 100644 index 0000000..67afd42 --- /dev/null +++ b/Text.cpp @@ -0,0 +1,31 @@ +#include "Text.h" + + +Text::Text(const std::string &text, Vec2f position) : MenuElement(position) +{ + this->text = text; + color = Vec3f(50, 150, 150); + textHeight = 14; + textWidth = Util::glutTextWidth(text); +} + + +Text::~Text() +{ +} + +void Text::draw() +{ + glColor4f(color.x/255.0f, color.y/255.0f, color.z/255.0f, 1.0f); + Util::glutBitmapString(text, position.x-1, position.y+textHeight); +} + +void Text::update(int x, int y) +{ + //Do nothing +} + +void Text::setColor(Vec3f color) +{ + this->color = color; +} diff --git a/Text.h b/Text.h new file mode 100644 index 0000000..b24bb25 --- /dev/null +++ b/Text.h @@ -0,0 +1,23 @@ +#pragma once +#include "MenuElement.h" +#include "Vector.h" +#include "Util.h" + +class Text : public MenuElement +{ +private: + std::string text; + Vec3f color; +protected: + int textWidth; + int textHeight; +public: + Text(const std::string &text, Vec2f position); + ~Text(); + + virtual void draw(); + virtual void update(int x, int y); + + void setColor(Vec3f color); +}; + diff --git a/Util.cpp b/Util.cpp new file mode 100644 index 0000000..5f052de --- /dev/null +++ b/Util.cpp @@ -0,0 +1,65 @@ +#include "Util.h" +#include "stb_image.h" + +Util::Util() +{ + +} + + +Util::~Util() +{ +} + +GLuint Util::loadTexture(const std::string &filename) +{ + int width, height, bpp; + + stbi_set_flip_vertically_on_load(true); + unsigned char* imgData = stbi_load(filename.c_str(), &width, &height, &bpp, 4); + GLuint num; + glGenTextures(1, &num); + glBindTexture(GL_TEXTURE_2D, num); + + glTexImage2D(GL_TEXTURE_2D, + 0, //level + GL_RGBA, //internal format + width, //width + height, //height + 0, //border + GL_RGBA, //data format + GL_UNSIGNED_BYTE, //data type + imgData); //data + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); + + stbi_image_free(imgData); + return num; +} + +void Util::glutBitmapString(std::string str, int x, int y) +{ + glRasterPos2f(x, y); + for (int i = 0; i < str.size(); i++) + { + glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str[i]); + } +} + +int Util::glutTextWidth(const std::string str) +{ + int total = 0; + for (int i = 0; i < str.size(); i++) + { + total += glutBitmapWidth(GLUT_BITMAP_HELVETICA_18, str[i]); + } + return total; +} + +//int Util::glutTextHeight() +//{ +// return glutBitmapHeight(GLUT_BITMAP_HELVETICA_18); +//} + diff --git a/Util.h b/Util.h new file mode 100644 index 0000000..089ab7c --- /dev/null +++ b/Util.h @@ -0,0 +1,16 @@ +#pragma once +#include +#include + +class Util +{ +private: + Util(); + ~Util(); +public: + static GLuint loadTexture(const std::string &filename); + static void glutBitmapString(std::string str, int x, int y); + static int glutTextWidth(const std::string str); + //static int glutTextHeight(); +}; + diff --git a/Vertex.cpp b/Vertex.cpp index 8afd8a1..35591cf 100644 --- a/Vertex.cpp +++ b/Vertex.cpp @@ -18,22 +18,22 @@ Vertex::~Vertex() { } -Vertex Vertex::operator/(float &other) +Vertex Vertex::operator/(const float &other) const { return Vertex(x / other, y / other, z / other, normalX, normalY, normalZ, texX, texY); } -Vertex Vertex::operator*(Vertex & other) +Vertex Vertex::operator*(const Vertex & other) const { return Vertex(x*other.x, y*other.y, z*other.z, normalX, normalY, normalZ, texX, texY); } -Vertex Vertex::operator*(float & other) +Vertex Vertex::operator*(const float & other) const { return Vertex(x*other, y*other, z*other, normalX, normalY, normalZ, texX, texY); } -Vertex Vertex::operator+(Vertex & other) +Vertex Vertex::operator+(const Vertex & other) const { return Vertex(x+other.x, y+other.y, z+other.z, normalX, normalY, normalZ, texX, texY); } diff --git a/Vertex.h b/Vertex.h index 3411000..ff3b2cc 100644 --- a/Vertex.h +++ b/Vertex.h @@ -16,9 +16,9 @@ public: float texX; float texY; - Vertex operator/(float &other); - Vertex operator*(Vertex &other); - Vertex operator*(float &other); - Vertex operator+(Vertex &other); + Vertex operator/(const float &other) const; + Vertex operator*(const Vertex &other) const; + Vertex operator*(const float &other) const; + Vertex operator+(const Vertex &other) const; }; diff --git a/WAVE/Sound.wav b/WAVE/Sound.wav deleted file mode 100644 index 74ccfd2..0000000 Binary files a/WAVE/Sound.wav and /dev/null differ diff --git a/WAVE/bond.wav b/WAVE/bond.wav deleted file mode 100644 index c478afe..0000000 Binary files a/WAVE/bond.wav and /dev/null differ diff --git a/WAVE/enemy.wav b/WAVE/enemy.wav new file mode 100644 index 0000000..89e9dae Binary files /dev/null and b/WAVE/enemy.wav differ diff --git a/WAVE/test1.wav b/WAVE/test1.wav new file mode 100644 index 0000000..e8e4fb8 Binary files /dev/null and b/WAVE/test1.wav differ diff --git a/WAVE/test2.wav b/WAVE/test2.wav new file mode 100644 index 0000000..364ff42 Binary files /dev/null and b/WAVE/test2.wav differ diff --git a/Weapon.cpp b/Weapon.cpp index 5413758..7a26355 100644 --- a/Weapon.cpp +++ b/Weapon.cpp @@ -71,14 +71,14 @@ void Weapon::draw(){ weaponmodel->draw(); //Test code for finding anker point -/* glColor3ub(255, 255, 0); + glColor3ub(255, 255, 0); glTranslatef(ankerPoint.x, ankerPoint.y, ankerPoint.z); glBegin(GL_LINES); glVertex2f(0, 4); glVertex2f(0, -4); glVertex2f(4, 0); glVertex2f(-4, 0); - glEnd();*/ + glEnd(); glPopMatrix(); diff --git a/World.cpp b/World.cpp index 00d6bf9..62801ce 100644 --- a/World.cpp +++ b/World.cpp @@ -3,7 +3,6 @@ #include "Entity.h" #include "json.h" #include "Model.h" -#include "CrystalPoint.h" #include #include #include @@ -179,9 +178,7 @@ World::World(const std::string &fileName): if (!v["world"]["music"].isNull()) { music_id = CrystalPoint::GetSoundSystem().LoadSound(v["world"]["music"].asString().c_str(), true); - Sound* music = CrystalPoint::GetSoundSystem().GetSound(music_id); - music->SetPos(Vec3f(), Vec3f()); - music->Play(); + music = CrystalPoint::GetSoundSystem().GetSound(music_id); } if (!v["portal"].isNull()) @@ -214,7 +211,10 @@ World::World(const std::string &fileName): World::~World() { delete heightmap; + music->Stop(); + delete music; delete skybox; + delete portal; } std::pair World::getObjectFromValue(int val) @@ -235,7 +235,7 @@ float World::getHeight(float x, float y) void World::draw() { - player->setCamera(); + float lightPosition[4] = { 0, 2, 1, 0 }; glLightfv(GL_LIGHT0, GL_POSITION, lightPosition); @@ -244,6 +244,9 @@ void World::draw() skybox->draw(); + player->setCamera(); + player->draw(); + heightmap->Draw(); for (auto &enemy : enemies) @@ -257,6 +260,12 @@ void World::draw() void World::update(float elapsedTime) { + music->SetPos(player->position, Vec3f()); + + if (music->IsPlaying() == false) + { + music->Play(); + } for (auto &entity : entities) entity->update(elapsedTime); diff --git a/World.h b/World.h index f12d1e2..a33385f 100644 --- a/World.h +++ b/World.h @@ -8,6 +8,7 @@ #include "Interface.h" #include "Crystal.h" #include "Skybox.h" +#include "CrystalPoint.h" #include "Portal.h" class Entity; @@ -16,6 +17,7 @@ class World { private: std::vector>> objecttemplates; + Sound* music; Player* player; HeightMap* heightmap; diff --git a/lib/serial/include/serial.h b/lib/serial/include/serial.h index 04784e9..c777a13 100644 --- a/lib/serial/include/serial.h +++ b/lib/serial/include/serial.h @@ -52,41 +52,41 @@ namespace serial { /*! * Enumeration defines the possible bytesizes for the serial port. */ -typedef enum { - fivebits = 5, - sixbits = 6, - sevenbits = 7, - eightbits = 8 -} bytesize_t; + typedef enum { + fivebits = 5, + sixbits = 6, + sevenbits = 7, + eightbits = 8 + } bytesize_t; /*! * Enumeration defines the possible parity types for the serial port. */ -typedef enum { - parity_none = 0, - parity_odd = 1, - parity_even = 2, - parity_mark = 3, - parity_space = 4 -} parity_t; + typedef enum { + parity_none = 0, + parity_odd = 1, + parity_even = 2, + parity_mark = 3, + parity_space = 4 + } parity_t; /*! * Enumeration defines the possible stopbit types for the serial port. */ -typedef enum { - stopbits_one = 1, - stopbits_two = 2, - stopbits_one_point_five -} stopbits_t; + typedef enum { + stopbits_one = 1, + stopbits_two = 2, + stopbits_one_point_five + } stopbits_t; /*! * Enumeration defines the possible flowcontrol types for the serial port. */ -typedef enum { - flowcontrol_none = 0, - flowcontrol_software, - flowcontrol_hardware -} flowcontrol_t; + typedef enum { + flowcontrol_none = 0, + flowcontrol_software, + flowcontrol_hardware + } flowcontrol_t; /*! * Structure for setting the timeout of the serial port, times are @@ -94,668 +94,668 @@ typedef enum { * * In order to disable the interbyte timeout, set it to Timeout::max(). */ -struct Timeout { + struct Timeout { #ifdef max # undef max #endif - static uint32_t max() {return std::numeric_limits::max();} - /*! - * Convenience function to generate Timeout structs using a - * single absolute timeout. - * - * \param timeout A long that defines the time in milliseconds until a - * timeout occurs after a call to read or write is made. - * - * \return Timeout struct that represents this simple timeout provided. - */ - static Timeout simpleTimeout(uint32_t timeout) { - return Timeout(max(), timeout, 0, timeout, 0); - } + static uint32_t max() {return std::numeric_limits::max();} + /*! + * Convenience function to generate Timeout structs using a + * single absolute timeout. + * + * \param timeout A long that defines the time in milliseconds until a + * timeout occurs after a call to read or write is made. + * + * \return Timeout struct that represents this simple timeout provided. + */ + static Timeout simpleTimeout(uint32_t timeout) { + return Timeout(max(), timeout, 0, timeout, 0); + } - /*! Number of milliseconds between bytes received to timeout on. */ - uint32_t inter_byte_timeout; - /*! A constant number of milliseconds to wait after calling read. */ - uint32_t read_timeout_constant; - /*! A multiplier against the number of requested bytes to wait after - * calling read. - */ - uint32_t read_timeout_multiplier; - /*! A constant number of milliseconds to wait after calling write. */ - uint32_t write_timeout_constant; - /*! A multiplier against the number of requested bytes to wait after - * calling write. - */ - uint32_t write_timeout_multiplier; + /*! Number of milliseconds between bytes received to timeout on. */ + uint32_t inter_byte_timeout; + /*! A constant number of milliseconds to wait after calling read. */ + uint32_t read_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling read. + */ + uint32_t read_timeout_multiplier; + /*! A constant number of milliseconds to wait after calling write. */ + uint32_t write_timeout_constant; + /*! A multiplier against the number of requested bytes to wait after + * calling write. + */ + uint32_t write_timeout_multiplier; - explicit Timeout (uint32_t inter_byte_timeout_=0, - uint32_t read_timeout_constant_=0, - uint32_t read_timeout_multiplier_=0, - uint32_t write_timeout_constant_=0, - uint32_t write_timeout_multiplier_=0) - : inter_byte_timeout(inter_byte_timeout_), - read_timeout_constant(read_timeout_constant_), - read_timeout_multiplier(read_timeout_multiplier_), - write_timeout_constant(write_timeout_constant_), - write_timeout_multiplier(write_timeout_multiplier_) - {} -}; + explicit Timeout (uint32_t inter_byte_timeout_=0, + uint32_t read_timeout_constant_=0, + uint32_t read_timeout_multiplier_=0, + uint32_t write_timeout_constant_=0, + uint32_t write_timeout_multiplier_=0) + : inter_byte_timeout(inter_byte_timeout_), + read_timeout_constant(read_timeout_constant_), + read_timeout_multiplier(read_timeout_multiplier_), + write_timeout_constant(write_timeout_constant_), + write_timeout_multiplier(write_timeout_multiplier_) + {} + }; /*! * Class that provides a portable serial port interface. */ -class Serial { -public: - /*! - * Creates a Serial object and opens the port if a port is specified, - * otherwise it remains closed until serial::Serial::open is called. - * - * \param port A std::string containing the address of the serial port, - * which would be something like 'COM1' on Windows and '/dev/ttyS0' - * on Linux. - * - * \param baudrate An unsigned 32-bit integer that represents the baudrate - * - * \param timeout A serial::Timeout struct that defines the timeout - * conditions for the serial port. \see serial::Timeout - * - * \param bytesize Size of each byte in the serial transmission of data, - * default is eightbits, possible values are: fivebits, sixbits, sevenbits, - * eightbits - * - * \param parity Method of parity, default is parity_none, possible values - * are: parity_none, parity_odd, parity_even - * - * \param stopbits Number of stop bits used, default is stopbits_one, - * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two - * - * \param flowcontrol Type of flowcontrol used, default is - * flowcontrol_none, possible values are: flowcontrol_none, - * flowcontrol_software, flowcontrol_hardware - * - * \throw serial::PortNotOpenedException - * \throw serial::IOException - * \throw std::invalid_argument - */ - Serial (const std::string &port = "", - uint32_t baudrate = 9600, - Timeout timeout = Timeout(), - bytesize_t bytesize = eightbits, - parity_t parity = parity_none, - stopbits_t stopbits = stopbits_one, - flowcontrol_t flowcontrol = flowcontrol_none); + class Serial { + public: + /*! + * Creates a Serial object and opens the port if a port is specified, + * otherwise it remains closed until serial::Serial::open is called. + * + * \param port A std::string containing the address of the serial port, + * which would be something like 'COM1' on Windows and '/dev/ttyS0' + * on Linux. + * + * \param baudrate An unsigned 32-bit integer that represents the baudrate + * + * \param timeout A serial::Timeout struct that defines the timeout + * conditions for the serial port. \see serial::Timeout + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \param flowcontrol Type of flowcontrol used, default is + * flowcontrol_none, possible values are: flowcontrol_none, + * flowcontrol_software, flowcontrol_hardware + * + * \throw serial::PortNotOpenedException + * \throw serial::IOException + * \throw std::invalid_argument + */ + Serial (const std::string &port = "", + uint32_t baudrate = 9600, + Timeout timeout = Timeout(), + bytesize_t bytesize = eightbits, + parity_t parity = parity_none, + stopbits_t stopbits = stopbits_one, + flowcontrol_t flowcontrol = flowcontrol_none); - /*! Destructor */ - virtual ~Serial (); + /*! Destructor */ + virtual ~Serial (); - /*! - * Opens the serial port as long as the port is set and the port isn't - * already open. - * - * If the port is provided to the constructor then an explicit call to open - * is not needed. - * - * \see Serial::Serial - * - * \throw std::invalid_argument - * \throw serial::SerialException - * \throw serial::IOException - */ - void - open (); + /*! + * Opens the serial port as long as the port is set and the port isn't + * already open. + * + * If the port is provided to the constructor then an explicit call to open + * is not needed. + * + * \see Serial::Serial + * + * \throw std::invalid_argument + * \throw serial::SerialException + * \throw serial::IOException + */ + void + open (); - /*! Gets the open status of the serial port. - * - * \return Returns true if the port is open, false otherwise. - */ - bool - isOpen () const; + /*! Gets the open status of the serial port. + * + * \return Returns true if the port is open, false otherwise. + */ + bool + isOpen () const; - /*! Closes the serial port. */ - void - close (); + /*! Closes the serial port. */ + void + close (); - /*! Return the number of characters in the buffer. */ - size_t - available (); + /*! Return the number of characters in the buffer. */ + size_t + available (); - /*! Block until there is serial data to read or read_timeout_constant - * number of milliseconds have elapsed. The return value is true when - * the function exits with the port in a readable state, false otherwise - * (due to timeout or select interruption). */ - bool - waitReadable (); + /*! Block until there is serial data to read or read_timeout_constant + * number of milliseconds have elapsed. The return value is true when + * the function exits with the port in a readable state, false otherwise + * (due to timeout or select interruption). */ + bool + waitReadable (); - /*! Block for a period of time corresponding to the transmission time of - * count characters at present serial settings. This may be used in con- - * junction with waitReadable to read larger blocks of data from the - * port. */ - void - waitByteTimes (size_t count); + /*! Block for a period of time corresponding to the transmission time of + * count characters at present serial settings. This may be used in con- + * junction with waitReadable to read larger blocks of data from the + * port. */ + void + waitByteTimes (size_t count); - /*! Read a given amount of bytes from the serial port into a given buffer. - * - * The read function will return in one of three cases: - * * The number of requested bytes was read. - * * In this case the number of bytes requested will match the size_t - * returned by read. - * * A timeout occurred, in this case the number of bytes read will not - * match the amount requested, but no exception will be thrown. One of - * two possible timeouts occurred: - * * The inter byte timeout expired, this means that number of - * milliseconds elapsed between receiving bytes from the serial port - * exceeded the inter byte timeout. - * * The total timeout expired, which is calculated by multiplying the - * read timeout multiplier by the number of requested bytes and then - * added to the read timeout constant. If that total number of - * milliseconds elapses after the initial call to read a timeout will - * occur. - * * An exception occurred, in this case an actual exception will be thrown. - * - * \param buffer An uint8_t array of at least the requested size. - * \param size A size_t defining how many bytes to be read. - * - * \return A size_t representing the number of bytes read as a result of the - * call to read. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - */ - size_t - read (uint8_t *buffer, size_t size); + /*! Read a given amount of bytes from the serial port into a given buffer. + * + * The read function will return in one of three cases: + * * The number of requested bytes was read. + * * In this case the number of bytes requested will match the size_t + * returned by read. + * * A timeout occurred, in this case the number of bytes read will not + * match the amount requested, but no exception will be thrown. One of + * two possible timeouts occurred: + * * The inter byte timeout expired, this means that number of + * milliseconds elapsed between receiving bytes from the serial port + * exceeded the inter byte timeout. + * * The total timeout expired, which is calculated by multiplying the + * read timeout multiplier by the number of requested bytes and then + * added to the read timeout constant. If that total number of + * milliseconds elapses after the initial call to read a timeout will + * occur. + * * An exception occurred, in this case an actual exception will be thrown. + * + * \param buffer An uint8_t array of at least the requested size. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (uint8_t *buffer, size_t size); - /*! Read a given amount of bytes from the serial port into a give buffer. - * - * \param buffer A reference to a std::vector of uint8_t. - * \param size A size_t defining how many bytes to be read. - * - * \return A size_t representing the number of bytes read as a result of the - * call to read. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - */ - size_t - read (std::vector &buffer, size_t size = 1); + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::vector of uint8_t. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::vector &buffer, size_t size = 1); - /*! Read a given amount of bytes from the serial port into a give buffer. - * - * \param buffer A reference to a std::string. - * \param size A size_t defining how many bytes to be read. - * - * \return A size_t representing the number of bytes read as a result of the - * call to read. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - */ - size_t - read (std::string &buffer, size_t size = 1); + /*! Read a given amount of bytes from the serial port into a give buffer. + * + * \param buffer A reference to a std::string. + * \param size A size_t defining how many bytes to be read. + * + * \return A size_t representing the number of bytes read as a result of the + * call to read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + read (std::string &buffer, size_t size = 1); - /*! Read a given amount of bytes from the serial port and return a string - * containing the data. - * - * \param size A size_t defining how many bytes to be read. - * - * \return A std::string containing the data read from the port. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - */ - std::string - read (size_t size = 1); + /*! Read a given amount of bytes from the serial port and return a string + * containing the data. + * + * \param size A size_t defining how many bytes to be read. + * + * \return A std::string containing the data read from the port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + read (size_t size = 1); - /*! Reads in a line or until a given delimiter has been processed. - * - * Reads from the serial port until a single line has been read. - * - * \param buffer A std::string reference used to store the data. - * \param size A maximum length of a line, defaults to 65536 (2^16) - * \param eol A string to match against for the EOL. - * - * \return A size_t representing the number of bytes read. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - */ - size_t - readline (std::string &buffer, size_t size = 65536, std::string eol = "\n"); + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param buffer A std::string reference used to store the data. + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A size_t representing the number of bytes read. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + size_t + readline (std::string &buffer, size_t size = 65536, std::string eol = "\n"); - /*! Reads in a line or until a given delimiter has been processed. - * - * Reads from the serial port until a single line has been read. - * - * \param size A maximum length of a line, defaults to 65536 (2^16) - * \param eol A string to match against for the EOL. - * - * \return A std::string containing the line. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - */ - std::string - readline (size_t size = 65536, std::string eol = "\n"); + /*! Reads in a line or until a given delimiter has been processed. + * + * Reads from the serial port until a single line has been read. + * + * \param size A maximum length of a line, defaults to 65536 (2^16) + * \param eol A string to match against for the EOL. + * + * \return A std::string containing the line. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::string + readline (size_t size = 65536, std::string eol = "\n"); - /*! Reads in multiple lines until the serial port times out. - * - * This requires a timeout > 0 before it can be run. It will read until a - * timeout occurs and return a list of strings. - * - * \param size A maximum length of combined lines, defaults to 65536 (2^16) - * - * \param eol A string to match against for the EOL. - * - * \return A vector containing the lines. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - */ - std::vector - readlines (size_t size = 65536, std::string eol = "\n"); + /*! Reads in multiple lines until the serial port times out. + * + * This requires a timeout > 0 before it can be run. It will read until a + * timeout occurs and return a list of strings. + * + * \param size A maximum length of combined lines, defaults to 65536 (2^16) + * + * \param eol A string to match against for the EOL. + * + * \return A vector containing the lines. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + */ + std::vector + readlines (size_t size = 65536, std::string eol = "\n"); - /*! Write a string to the serial port. - * - * \param data A const reference containing the data to be written - * to the serial port. - * - * \param size A size_t that indicates how many bytes should be written from - * the given data buffer. - * - * \return A size_t representing the number of bytes actually written to - * the serial port. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - * \throw serial::IOException - */ - size_t - write (const uint8_t *data, size_t size); + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \param size A size_t that indicates how many bytes should be written from + * the given data buffer. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const uint8_t *data, size_t size); - /*! Write a string to the serial port. - * - * \param data A const reference containing the data to be written - * to the serial port. - * - * \return A size_t representing the number of bytes actually written to - * the serial port. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - * \throw serial::IOException - */ - size_t - write (const std::vector &data); + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::vector &data); - /*! Write a string to the serial port. - * - * \param data A const reference containing the data to be written - * to the serial port. - * - * \return A size_t representing the number of bytes actually written to - * the serial port. - * - * \throw serial::PortNotOpenedException - * \throw serial::SerialException - * \throw serial::IOException - */ - size_t - write (const std::string &data); + /*! Write a string to the serial port. + * + * \param data A const reference containing the data to be written + * to the serial port. + * + * \return A size_t representing the number of bytes actually written to + * the serial port. + * + * \throw serial::PortNotOpenedException + * \throw serial::SerialException + * \throw serial::IOException + */ + size_t + write (const std::string &data); - /*! Sets the serial port identifier. - * - * \param port A const std::string reference containing the address of the - * serial port, which would be something like 'COM1' on Windows and - * '/dev/ttyS0' on Linux. - * - * \throw std::invalid_argument - */ - void - setPort (const std::string &port); + /*! Sets the serial port identifier. + * + * \param port A const std::string reference containing the address of the + * serial port, which would be something like 'COM1' on Windows and + * '/dev/ttyS0' on Linux. + * + * \throw std::invalid_argument + */ + void + setPort (const std::string &port); - /*! Gets the serial port identifier. - * - * \see Serial::setPort - * - * \throw std::invalid_argument - */ - std::string - getPort () const; + /*! Gets the serial port identifier. + * + * \see Serial::setPort + * + * \throw std::invalid_argument + */ + std::string + getPort () const; - /*! Sets the timeout for reads and writes using the Timeout struct. - * - * There are two timeout conditions described here: - * * The inter byte timeout: - * * The inter_byte_timeout component of serial::Timeout defines the - * maximum amount of time, in milliseconds, between receiving bytes on - * the serial port that can pass before a timeout occurs. Setting this - * to zero will prevent inter byte timeouts from occurring. - * * Total time timeout: - * * The constant and multiplier component of this timeout condition, - * for both read and write, are defined in serial::Timeout. This - * timeout occurs if the total time since the read or write call was - * made exceeds the specified time in milliseconds. - * * The limit is defined by multiplying the multiplier component by the - * number of requested bytes and adding that product to the constant - * component. In this way if you want a read call, for example, to - * timeout after exactly one second regardless of the number of bytes - * you asked for then set the read_timeout_constant component of - * serial::Timeout to 1000 and the read_timeout_multiplier to zero. - * This timeout condition can be used in conjunction with the inter - * byte timeout condition with out any problems, timeout will simply - * occur when one of the two timeout conditions is met. This allows - * users to have maximum control over the trade-off between - * responsiveness and efficiency. - * - * Read and write functions will return in one of three cases. When the - * reading or writing is complete, when a timeout occurs, or when an - * exception occurs. - * - * \param timeout A serial::Timeout struct containing the inter byte - * timeout, and the read and write timeout constants and multipliers. - * - * \see serial::Timeout - */ - void - setTimeout (Timeout &timeout); + /*! Sets the timeout for reads and writes using the Timeout struct. + * + * There are two timeout conditions described here: + * * The inter byte timeout: + * * The inter_byte_timeout component of serial::Timeout defines the + * maximum amount of time, in milliseconds, between receiving bytes on + * the serial port that can pass before a timeout occurs. Setting this + * to zero will prevent inter byte timeouts from occurring. + * * Total time timeout: + * * The constant and multiplier component of this timeout condition, + * for both read and write, are defined in serial::Timeout. This + * timeout occurs if the total time since the read or write call was + * made exceeds the specified time in milliseconds. + * * The limit is defined by multiplying the multiplier component by the + * number of requested bytes and adding that product to the constant + * component. In this way if you want a read call, for example, to + * timeout after exactly one second regardless of the number of bytes + * you asked for then set the read_timeout_constant component of + * serial::Timeout to 1000 and the read_timeout_multiplier to zero. + * This timeout condition can be used in conjunction with the inter + * byte timeout condition with out any problems, timeout will simply + * occur when one of the two timeout conditions is met. This allows + * users to have maximum control over the trade-off between + * responsiveness and efficiency. + * + * Read and write functions will return in one of three cases. When the + * reading or writing is complete, when a timeout occurs, or when an + * exception occurs. + * + * \param timeout A serial::Timeout struct containing the inter byte + * timeout, and the read and write timeout constants and multipliers. + * + * \see serial::Timeout + */ + void + setTimeout (Timeout &timeout); - /*! Sets the timeout for reads and writes. */ - void - setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant, - uint32_t read_timeout_multiplier, uint32_t write_timeout_constant, - uint32_t write_timeout_multiplier) - { - Timeout timeout(inter_byte_timeout, read_timeout_constant, - read_timeout_multiplier, write_timeout_constant, - write_timeout_multiplier); - return setTimeout(timeout); - } + /*! Sets the timeout for reads and writes. */ + void + setTimeout (uint32_t inter_byte_timeout, uint32_t read_timeout_constant, + uint32_t read_timeout_multiplier, uint32_t write_timeout_constant, + uint32_t write_timeout_multiplier) + { + Timeout timeout(inter_byte_timeout, read_timeout_constant, + read_timeout_multiplier, write_timeout_constant, + write_timeout_multiplier); + return setTimeout(timeout); + } - /*! Gets the timeout for reads in seconds. - * - * \return A Timeout struct containing the inter_byte_timeout, and read - * and write timeout constants and multipliers. - * - * \see Serial::setTimeout - */ - Timeout - getTimeout () const; + /*! Gets the timeout for reads in seconds. + * + * \return A Timeout struct containing the inter_byte_timeout, and read + * and write timeout constants and multipliers. + * + * \see Serial::setTimeout + */ + Timeout + getTimeout () const; - /*! Sets the baudrate for the serial port. - * - * Possible baudrates depends on the system but some safe baudrates include: - * 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000, - * 57600, 115200 - * Some other baudrates that are supported by some comports: - * 128000, 153600, 230400, 256000, 460800, 921600 - * - * \param baudrate An integer that sets the baud rate for the serial port. - * - * \throw std::invalid_argument - */ - void - setBaudrate (uint32_t baudrate); + /*! Sets the baudrate for the serial port. + * + * Possible baudrates depends on the system but some safe baudrates include: + * 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 56000, + * 57600, 115200 + * Some other baudrates that are supported by some comports: + * 128000, 153600, 230400, 256000, 460800, 921600 + * + * \param baudrate An integer that sets the baud rate for the serial port. + * + * \throw std::invalid_argument + */ + void + setBaudrate (uint32_t baudrate); - /*! Gets the baudrate for the serial port. - * - * \return An integer that sets the baud rate for the serial port. - * - * \see Serial::setBaudrate - * - * \throw std::invalid_argument - */ - uint32_t - getBaudrate () const; + /*! Gets the baudrate for the serial port. + * + * \return An integer that sets the baud rate for the serial port. + * + * \see Serial::setBaudrate + * + * \throw std::invalid_argument + */ + uint32_t + getBaudrate () const; - /*! Sets the bytesize for the serial port. - * - * \param bytesize Size of each byte in the serial transmission of data, - * default is eightbits, possible values are: fivebits, sixbits, sevenbits, - * eightbits - * - * \throw std::invalid_argument - */ - void - setBytesize (bytesize_t bytesize); + /*! Sets the bytesize for the serial port. + * + * \param bytesize Size of each byte in the serial transmission of data, + * default is eightbits, possible values are: fivebits, sixbits, sevenbits, + * eightbits + * + * \throw std::invalid_argument + */ + void + setBytesize (bytesize_t bytesize); - /*! Gets the bytesize for the serial port. - * - * \see Serial::setBytesize - * - * \throw std::invalid_argument - */ - bytesize_t - getBytesize () const; + /*! Gets the bytesize for the serial port. + * + * \see Serial::setBytesize + * + * \throw std::invalid_argument + */ + bytesize_t + getBytesize () const; - /*! Sets the parity for the serial port. - * - * \param parity Method of parity, default is parity_none, possible values - * are: parity_none, parity_odd, parity_even - * - * \throw std::invalid_argument - */ - void - setParity (parity_t parity); + /*! Sets the parity for the serial port. + * + * \param parity Method of parity, default is parity_none, possible values + * are: parity_none, parity_odd, parity_even + * + * \throw std::invalid_argument + */ + void + setParity (parity_t parity); - /*! Gets the parity for the serial port. - * - * \see Serial::setParity - * - * \throw std::invalid_argument - */ - parity_t - getParity () const; + /*! Gets the parity for the serial port. + * + * \see Serial::setParity + * + * \throw std::invalid_argument + */ + parity_t + getParity () const; - /*! Sets the stopbits for the serial port. - * - * \param stopbits Number of stop bits used, default is stopbits_one, - * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two - * - * \throw std::invalid_argument - */ - void - setStopbits (stopbits_t stopbits); + /*! Sets the stopbits for the serial port. + * + * \param stopbits Number of stop bits used, default is stopbits_one, + * possible values are: stopbits_one, stopbits_one_point_five, stopbits_two + * + * \throw std::invalid_argument + */ + void + setStopbits (stopbits_t stopbits); - /*! Gets the stopbits for the serial port. - * - * \see Serial::setStopbits - * - * \throw std::invalid_argument - */ - stopbits_t - getStopbits () const; + /*! Gets the stopbits for the serial port. + * + * \see Serial::setStopbits + * + * \throw std::invalid_argument + */ + stopbits_t + getStopbits () const; - /*! Sets the flow control for the serial port. - * - * \param flowcontrol Type of flowcontrol used, default is flowcontrol_none, - * possible values are: flowcontrol_none, flowcontrol_software, - * flowcontrol_hardware - * - * \throw std::invalid_argument - */ - void - setFlowcontrol (flowcontrol_t flowcontrol); + /*! Sets the flow control for the serial port. + * + * \param flowcontrol Type of flowcontrol used, default is flowcontrol_none, + * possible values are: flowcontrol_none, flowcontrol_software, + * flowcontrol_hardware + * + * \throw std::invalid_argument + */ + void + setFlowcontrol (flowcontrol_t flowcontrol); - /*! Gets the flow control for the serial port. - * - * \see Serial::setFlowcontrol - * - * \throw std::invalid_argument - */ - flowcontrol_t - getFlowcontrol () const; + /*! Gets the flow control for the serial port. + * + * \see Serial::setFlowcontrol + * + * \throw std::invalid_argument + */ + flowcontrol_t + getFlowcontrol () const; - /*! Flush the input and output buffers */ - void - flush (); + /*! Flush the input and output buffers */ + void + flush (); - /*! Flush only the input buffer */ - void - flushInput (); + /*! Flush only the input buffer */ + void + flushInput (); - /*! Flush only the output buffer */ - void - flushOutput (); + /*! Flush only the output buffer */ + void + flushOutput (); - /*! Sends the RS-232 break signal. See tcsendbreak(3). */ - void - sendBreak (int duration); + /*! Sends the RS-232 break signal. See tcsendbreak(3). */ + void + sendBreak (int duration); - /*! Set the break condition to a given level. Defaults to true. */ - void - setBreak (bool level = true); + /*! Set the break condition to a given level. Defaults to true. */ + void + setBreak (bool level = true); - /*! Set the RTS handshaking line to the given level. Defaults to true. */ - void - setRTS (bool level = true); + /*! Set the RTS handshaking line to the given level. Defaults to true. */ + void + setRTS (bool level = true); - /*! Set the DTR handshaking line to the given level. Defaults to true. */ - void - setDTR (bool level = true); + /*! Set the DTR handshaking line to the given level. Defaults to true. */ + void + setDTR (bool level = true); - /*! - * Blocks until CTS, DSR, RI, CD changes or something interrupts it. - * - * Can throw an exception if an error occurs while waiting. - * You can check the status of CTS, DSR, RI, and CD once this returns. - * Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a - * resolution of less than +-1ms and as good as +-0.2ms. Otherwise a - * polling method is used which can give +-2ms. - * - * \return Returns true if one of the lines changed, false if something else - * occurred. - * - * \throw SerialException - */ - bool - waitForChange (); + /*! + * Blocks until CTS, DSR, RI, CD changes or something interrupts it. + * + * Can throw an exception if an error occurs while waiting. + * You can check the status of CTS, DSR, RI, and CD once this returns. + * Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a + * resolution of less than +-1ms and as good as +-0.2ms. Otherwise a + * polling method is used which can give +-2ms. + * + * \return Returns true if one of the lines changed, false if something else + * occurred. + * + * \throw SerialException + */ + bool + waitForChange (); - /*! Returns the current status of the CTS line. */ - bool - getCTS (); + /*! Returns the current status of the CTS line. */ + bool + getCTS (); - /*! Returns the current status of the DSR line. */ - bool - getDSR (); + /*! Returns the current status of the DSR line. */ + bool + getDSR (); - /*! Returns the current status of the RI line. */ - bool - getRI (); + /*! Returns the current status of the RI line. */ + bool + getRI (); - /*! Returns the current status of the CD line. */ - bool - getCD (); + /*! Returns the current status of the CD line. */ + bool + getCD (); -private: - // Disable copy constructors - Serial(const Serial&); - Serial& operator=(const Serial&); + private: + // Disable copy constructors + Serial(const Serial&); + Serial& operator=(const Serial&); - // Pimpl idiom, d_pointer - class SerialImpl; - SerialImpl *pimpl_; + // Pimpl idiom, d_pointer + class SerialImpl; + SerialImpl *pimpl_; - // Scoped Lock Classes - class ScopedReadLock; - class ScopedWriteLock; + // Scoped Lock Classes + class ScopedReadLock; + class ScopedWriteLock; - // Read common function - size_t - read_ (uint8_t *buffer, size_t size); - // Write common function - size_t - write_ (const uint8_t *data, size_t length); + // Read common function + size_t + read_ (uint8_t *buffer, size_t size); + // Write common function + size_t + write_ (const uint8_t *data, size_t length); -}; + }; -class SerialException : public std::exception -{ - // Disable copy constructors - SerialException& operator=(const SerialException&); - std::string e_what_; -public: - SerialException (const char *description) { - std::stringstream ss; - ss << "SerialException " << description << " failed."; - e_what_ = ss.str(); - } - SerialException (const SerialException& other) : e_what_(other.e_what_) {} - virtual ~SerialException() throw() {} - virtual const char* what () const throw () { - return e_what_.c_str(); - } -}; + class SerialException : public std::exception + { + // Disable copy constructors + SerialException& operator=(const SerialException&); + std::string e_what_; + public: + SerialException (const char *description) { + std::stringstream ss; + ss << "SerialException " << description << " failed."; + e_what_ = ss.str(); + } + SerialException (const SerialException& other) : e_what_(other.e_what_) {} + virtual ~SerialException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } + }; -class IOException : public std::exception -{ - // Disable copy constructors - IOException& operator=(const IOException&); - std::string file_; - int line_; - std::string e_what_; - int errno_; -public: - explicit IOException (std::string file, int line, int errnum) - : file_(file), line_(line), errno_(errnum) { - std::stringstream ss; + class IOException : public std::exception + { + // Disable copy constructors + IOException& operator=(const IOException&); + std::string file_; + int line_; + std::string e_what_; + int errno_; + public: + explicit IOException (std::string file, int line, int errnum) + : file_(file), line_(line), errno_(errnum) { + std::stringstream ss; #if defined(_WIN32) && !defined(__MINGW32__) - char error_str [1024]; + char error_str [1024]; strerror_s(error_str, 1024, errnum); #else - char * error_str = strerror(errnum); + char * error_str = strerror(errnum); #endif - ss << "IO Exception (" << errno_ << "): " << error_str; - ss << ", file " << file_ << ", line " << line_ << "."; - e_what_ = ss.str(); - } - explicit IOException (std::string file, int line, const char * description) - : file_(file), line_(line), errno_(0) { - std::stringstream ss; - ss << "IO Exception: " << description; - ss << ", file " << file_ << ", line " << line_ << "."; - e_what_ = ss.str(); - } - virtual ~IOException() throw() {} - IOException (const IOException& other) : line_(other.line_), e_what_(other.e_what_), errno_(other.errno_) {} + ss << "IO Exception (" << errno_ << "): " << error_str; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + explicit IOException (std::string file, int line, const char * description) + : file_(file), line_(line), errno_(0) { + std::stringstream ss; + ss << "IO Exception: " << description; + ss << ", file " << file_ << ", line " << line_ << "."; + e_what_ = ss.str(); + } + virtual ~IOException() throw() {} + IOException (const IOException& other) : line_(other.line_), e_what_(other.e_what_), errno_(other.errno_) {} - int getErrorNumber () { return errno_; } + int getErrorNumber () { return errno_; } - virtual const char* what () const throw () { - return e_what_.c_str(); - } -}; + virtual const char* what () const throw () { + return e_what_.c_str(); + } + }; -class PortNotOpenedException : public std::exception -{ - // Disable copy constructors - const PortNotOpenedException& operator=(PortNotOpenedException); - std::string e_what_; -public: - PortNotOpenedException (const char * description) { - std::stringstream ss; - ss << "PortNotOpenedException " << description << " failed."; - e_what_ = ss.str(); - } - PortNotOpenedException (const PortNotOpenedException& other) : e_what_(other.e_what_) {} - virtual ~PortNotOpenedException() throw() {} - virtual const char* what () const throw () { - return e_what_.c_str(); - } -}; + class PortNotOpenedException : public std::exception + { + // Disable copy constructors + const PortNotOpenedException& operator=(PortNotOpenedException); + std::string e_what_; + public: + PortNotOpenedException (const char * description) { + std::stringstream ss; + ss << "PortNotOpenedException " << description << " failed."; + e_what_ = ss.str(); + } + PortNotOpenedException (const PortNotOpenedException& other) : e_what_(other.e_what_) {} + virtual ~PortNotOpenedException() throw() {} + virtual const char* what () const throw () { + return e_what_.c_str(); + } + }; /*! * Structure that describes a serial device. */ -struct PortInfo { + struct PortInfo { - /*! Address of the serial port (this can be passed to the constructor of Serial). */ - std::string port; + /*! Address of the serial port (this can be passed to the constructor of Serial). */ + std::string port; - /*! Human readable description of serial device if available. */ - std::string description; + /*! Human readable description of serial device if available. */ + std::string description; - /*! Hardware ID (e.g. VID:PID of USB serial devices) or "n/a" if not available. */ - std::string hardware_id; + /*! Hardware ID (e.g. VID:PID of USB serial devices) or "n/a" if not available. */ + std::string hardware_id; -}; + }; /* Lists the serial ports available on the system * @@ -764,9 +764,9 @@ struct PortInfo { * * \return vector of serial::PortInfo. */ -std::vector -list_ports(); + std::vector + list_ports(); } // namespace serial -#endif +#endif \ No newline at end of file diff --git a/lib/serial/src/serial.cc b/lib/serial/src/serial.cc index 6224f02..2a7a108 100644 --- a/lib/serial/src/serial.cc +++ b/lib/serial/src/serial.cc @@ -35,40 +35,40 @@ using serial::flowcontrol_t; class Serial::ScopedReadLock { public: - ScopedReadLock(SerialImpl *pimpl) : pimpl_(pimpl) { - this->pimpl_->readLock(); - } - ~ScopedReadLock() { - this->pimpl_->readUnlock(); - } + ScopedReadLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->readLock(); + } + ~ScopedReadLock() { + this->pimpl_->readUnlock(); + } private: - // Disable copy constructors - ScopedReadLock(const ScopedReadLock&); - const ScopedReadLock& operator=(ScopedReadLock); + // Disable copy constructors + ScopedReadLock(const ScopedReadLock&); + const ScopedReadLock& operator=(ScopedReadLock); - SerialImpl *pimpl_; + SerialImpl *pimpl_; }; class Serial::ScopedWriteLock { public: - ScopedWriteLock(SerialImpl *pimpl) : pimpl_(pimpl) { - this->pimpl_->writeLock(); - } - ~ScopedWriteLock() { - this->pimpl_->writeUnlock(); - } + ScopedWriteLock(SerialImpl *pimpl) : pimpl_(pimpl) { + this->pimpl_->writeLock(); + } + ~ScopedWriteLock() { + this->pimpl_->writeUnlock(); + } private: - // Disable copy constructors - ScopedWriteLock(const ScopedWriteLock&); - const ScopedWriteLock& operator=(ScopedWriteLock); - SerialImpl *pimpl_; + // Disable copy constructors + ScopedWriteLock(const ScopedWriteLock&); + const ScopedWriteLock& operator=(ScopedWriteLock); + SerialImpl *pimpl_; }; Serial::Serial (const string &port, uint32_t baudrate, serial::Timeout timeout, bytesize_t bytesize, parity_t parity, stopbits_t stopbits, flowcontrol_t flowcontrol) - : pimpl_(new SerialImpl (port, baudrate, bytesize, parity, - stopbits, flowcontrol)) + : pimpl_(new SerialImpl (port, baudrate, bytesize, parity, + stopbits, flowcontrol)) { pimpl_->setTimeout(timeout); } @@ -164,7 +164,7 @@ Serial::readline (string &buffer, size_t size, string eol) ScopedReadLock lock(this->pimpl_); size_t eol_len = eol.length (); uint8_t *buffer_ = static_cast - (alloca (size * sizeof (uint8_t))); + (alloca (size * sizeof (uint8_t))); size_t read_so_far = 0; while (true) { @@ -174,7 +174,7 @@ Serial::readline (string &buffer, size_t size, string eol) break; // Timeout occured on reading 1 byte } if (string (reinterpret_cast - (buffer_ + read_so_far - eol_len), eol_len) == eol) { + (buffer_ + read_so_far - eol_len), eol_len) == eol) { break; // EOL found } if (read_so_far == size) { @@ -200,7 +200,7 @@ Serial::readlines (size_t size, string eol) std::vector lines; size_t eol_len = eol.length (); uint8_t *buffer_ = static_cast - (alloca (size * sizeof (uint8_t))); + (alloca (size * sizeof (uint8_t))); size_t read_so_far = 0; size_t start_of_line = 0; while (read_so_far < size) { @@ -209,24 +209,24 @@ Serial::readlines (size_t size, string eol) if (bytes_read == 0) { if (start_of_line != read_so_far) { lines.push_back ( - string (reinterpret_cast (buffer_ + start_of_line), - read_so_far - start_of_line)); + string (reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); } break; // Timeout occured on reading 1 byte } if (string (reinterpret_cast - (buffer_ + read_so_far - eol_len), eol_len) == eol) { + (buffer_ + read_so_far - eol_len), eol_len) == eol) { // EOL found lines.push_back( - string(reinterpret_cast (buffer_ + start_of_line), - read_so_far - start_of_line)); + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); start_of_line = read_so_far; } if (read_so_far == size) { if (start_of_line != read_so_far) { lines.push_back( - string(reinterpret_cast (buffer_ + start_of_line), - read_so_far - start_of_line)); + string(reinterpret_cast (buffer_ + start_of_line), + read_so_far - start_of_line)); } break; // Reached the maximum read length } @@ -412,4 +412,4 @@ bool Serial::getRI () bool Serial::getCD () { return pimpl_->getCD (); -} +} \ No newline at end of file diff --git a/worlds/rock.json b/worlds/rock.json index 55f5132..08d3311 100644 --- a/worlds/rock.json +++ b/worlds/rock.json @@ -3,6 +3,7 @@ "heightmap": "worlds/rockHeightmap.png", "texture": "worlds/rockStone2.png", "skybox": "skyboxes/water/", + "music": "WAVE/test2.wav", "object-templates": [ { "color": 50, diff --git a/worlds/small.json b/worlds/small.json index af4cecf..606c410 100644 --- a/worlds/small.json +++ b/worlds/small.json @@ -9,7 +9,7 @@ "collision": true } ], - "music": "WAVE/bond.wav" + "music": "WAVE/test1.wav" }, "player": { "startposition": [ 20, 5, 20 ]