From 3dd5a4814f852a428941d5e3d5b89b92d3b28376 Mon Sep 17 00:00:00 2001 From: Nick Gasson Date: Sat, 26 Jun 2010 23:53:08 +0100 Subject: [PATCH] Convert camelCase identifiers to underscores --- include/BezierCurve.hpp | 6 +- include/Colour.hpp | 6 +- include/GameScreens.hpp | 8 +- include/IBillboard.hpp | 16 +- include/IConfig.hpp | 12 +- include/IController.hpp | 6 +- include/IFog.hpp | 4 +- include/IGraphics.hpp | 14 +- include/ILight.hpp | 2 +- include/ILogger.hpp | 14 +- include/IMap.hpp | 66 +- include/IMesh.hpp | 22 +- include/IMessageArea.hpp | 2 +- include/IModel.hpp | 6 +- include/IPickBuffer.hpp | 4 +- include/IQuadTree.hpp | 14 +- include/IResource.hpp | 34 +- include/IRollingStock.hpp | 4 +- include/IScenery.hpp | 12 +- include/ISceneryPicker.hpp | 4 +- include/IScreen.hpp | 18 +- include/ISkyBox.hpp | 4 +- include/ISmokeTrail.hpp | 10 +- include/IStation.hpp | 12 +- include/ITexture.hpp | 4 +- include/ITrackSegment.hpp | 52 +- include/ITrain.hpp | 6 +- include/IWindow.hpp | 6 +- include/IXMLParser.hpp | 50 +- include/IXMLSerialisable.hpp | 2 +- include/IterateTrack.hpp | 4 +- include/Maths.hpp | 42 +- include/Matrix.hpp | 6 +- include/MovingAverage.hpp | 12 +- include/OpenGLHelper.hpp | 8 +- include/ResourceCache.hpp | 24 +- include/TrackCommon.hpp | 42 +- include/XMLBuilder.hpp | 22 +- include/gui/ContainerWidget.hpp | 14 +- include/gui/IFont.hpp | 4 +- include/gui/ILayout.hpp | 4 +- include/gui/Label.hpp | 4 +- include/gui/RenderContext.hpp | 4 +- include/gui/Theme.hpp | 6 +- include/gui/ThrottleMeter.hpp | 6 +- include/gui/ToggleBar.hpp | 6 +- include/gui/ToggleButton.hpp | 2 +- include/gui/Widget.hpp | 10 +- include/gui/Window.hpp | 4 +- src/Billboard.cpp | 208 ++--- src/Building.cpp | 70 +- src/Config.cpp | 120 +-- src/CrossoverTrack.cpp | 124 +-- src/CurvedTrack.cpp | 238 +++--- src/Editor.cpp | 516 ++++++------- src/Engine.cpp | 138 ++-- src/Fog.cpp | 10 +- src/Frustum.cpp | 24 +- src/Game.cpp | 256 +++---- src/IterateTrack.cpp | 26 +- src/Light.cpp | 8 +- src/Logger.cpp | 26 +- src/Main.cpp | 34 +- src/Map.cpp | 1251 ++++++++++++++++--------------- src/Maths.cpp | 16 +- src/Mesh.cpp | 248 +++--- src/MessageArea.cpp | 10 +- src/Model.cpp | 128 ++-- src/OpenGLHelper.cpp | 52 +- src/Points.cpp | 442 +++++------ src/QuadTree.cpp | 134 ++-- src/Resource.cpp | 124 +-- src/SBend.cpp | 156 ++-- src/SDLWindow.cpp | 216 +++--- src/SceneryPicker.cpp | 104 +-- src/SkyBox.cpp | 38 +- src/SlopeTrack.cpp | 150 ++-- src/SmokeTrail.cpp | 82 +- src/Station.cpp | 38 +- src/StraightTrack.cpp | 180 ++--- src/Texture.cpp | 58 +- src/TrackCommon.cpp | 272 +++---- src/Train.cpp | 184 ++--- src/Tree.cpp | 74 +- src/UIDemo.cpp | 18 +- src/Waggon.cpp | 28 +- src/XMLParser.cpp | 106 +-- src/gui/Button.cpp | 2 +- src/gui/Canvas3D.cpp | 2 +- src/gui/ContainerWidget.cpp | 30 +- src/gui/Font.cpp | 32 +- src/gui/FromBottom.cpp | 10 +- src/gui/ImageButton.cpp | 2 +- src/gui/Label.cpp | 8 +- src/gui/Layout.cpp | 54 +- src/gui/RenderContext.cpp | 16 +- src/gui/Theme.cpp | 18 +- src/gui/ThrottleMeter.cpp | 38 +- src/gui/ToggleBar.cpp | 24 +- src/gui/ToggleButton.cpp | 6 +- src/gui/Widget.cpp | 16 +- src/gui/Window.cpp | 28 +- 102 files changed, 3420 insertions(+), 3417 deletions(-) diff --git a/include/BezierCurve.hpp b/include/BezierCurve.hpp index 4f64f67..c9593b2 100644 --- a/include/BezierCurve.hpp +++ b/include/BezierCurve.hpp @@ -62,7 +62,7 @@ struct BezierCurve { Vector operator()(T t) const { - return makeVector + return make_vector (// X p[0].x * (1 - t) * (1 - t) * (1 - t) + p[1].x * 3 * t * (1 - t) * (1 - t) @@ -86,7 +86,7 @@ struct BezierCurve { // The derivative with respect to t at a point Vector deriv(T t) const { - return makeVector + return make_vector (// X p[0].x * -3 * (1 - t) * (1 - t) + p[1].x * (3 - 12*t + 9*t*t) @@ -125,7 +125,7 @@ struct BezierCurve { // Generate Bezier curves template -BezierCurve makeBezierCurve(Vector p1, Vector p2, +BezierCurve make_bezier_curve(Vector p1, Vector p2, Vector p3, Vector p4) { return BezierCurve(p1, p2, p3, p4); diff --git a/include/Colour.hpp b/include/Colour.hpp index 618af7f..5f8fe17 100644 --- a/include/Colour.hpp +++ b/include/Colour.hpp @@ -24,7 +24,7 @@ struct Colour { float r, g, b, a; }; -inline Colour makeColour(float r, float g, float b, float a=1.0f) +inline Colour make_colour(float r, float g, float b, float a=1.0f) { Colour c = { r, g, b, a }; return c; @@ -32,7 +32,7 @@ inline Colour makeColour(float r, float g, float b, float a=1.0f) inline Colour makeRGB(int r, int g, int b, int a=255) { - return makeColour( + return make_colour( static_cast(r) / 255.0f, static_cast(g) / 255.0f, static_cast(b) / 255.0f, @@ -40,7 +40,7 @@ inline Colour makeRGB(int r, int g, int b, int a=255) } namespace colour { - const Colour WHITE = makeColour(1.0f, 1.0f, 1.0f); + const Colour WHITE = make_colour(1.0f, 1.0f, 1.0f); } #endif diff --git a/include/GameScreens.hpp b/include/GameScreens.hpp index e5f1932..b736c85 100644 --- a/include/GameScreens.hpp +++ b/include/GameScreens.hpp @@ -24,15 +24,15 @@ // Create the various screens // These may be called multiple times -IScreenPtr makeEditorScreen(IMapPtr aMap); -IScreenPtr makeGameScreen(IMapPtr aMap); +IScreenPtr make_editor_screen(IMapPtr a_map); +IScreenPtr make_game_screen(IMapPtr a_map); IScreenPtr makeUIDemo(); IScreenPtr makeLTreeDemo(); // Access to the window the game is running in -IWindowPtr getGameWindow(); +IWindowPtr get_game_window(); // Add editor GUI controls -void addEditorGUI(); +void add_editorGUI(); #endif diff --git a/include/IBillboard.hpp b/include/IBillboard.hpp index d2dea24..e6c800a 100644 --- a/include/IBillboard.hpp +++ b/include/IBillboard.hpp @@ -28,25 +28,25 @@ struct IBillboard { virtual void render() const = 0; - virtual void setPosition(float x, float y, float z) = 0; - virtual void setScale(float aScale) = 0; - virtual void setColour(float r, float g, float b, float a) = 0; + virtual void set_position(float x, float y, float z) = 0; + virtual void set_scale(float a_scale) = 0; + virtual void set_colour(float r, float g, float b, float a) = 0; }; typedef std::tr1::shared_ptr IBillboardPtr; -IBillboardPtr makeCylindricalBillboard(ITexturePtr aTexture); -IBillboardPtr makeSphericalBillboard(ITexturePtr aTexture); +IBillboardPtr make_cylindrical_billboard(ITexturePtr a_texture); +IBillboardPtr make_spherical_billboard(ITexturePtr a_texture); // This should be called once per frame to render all billboards // in the correct orientation -void setBillboardCameraOrigin(Vector aPosition); +void set_billboard_cameraOrigin(Vector a_position); // Billboards normally need to be depth sorted // This calculates the distance of a point to the camera -float distanceToCamera(Vector aPosition); +float distance_to_camera(Vector a_position); // Draw all billboards saved during this frame -void renderBillboards(); +void render_billboards(); #endif diff --git a/include/IConfig.hpp b/include/IConfig.hpp index 7adda8b..1b69039 100644 --- a/include/IConfig.hpp +++ b/include/IConfig.hpp @@ -28,24 +28,24 @@ struct IConfig { typedef boost::any Option; - virtual const Option& get(const string& aKey) const = 0; + virtual const Option& get(const string& a_key) const = 0; virtual void flush() = 0; template - T get(const string& aKey) const + T get(const string& a_key) const { - return boost::any_cast(get(aKey)); + return boost::any_cast(get(a_key)); } template - void get(const string& aKey, T& t) const + void get(const string& a_key, T& t) const { - t = boost::any_cast(get(aKey)); + t = boost::any_cast(get(a_key)); } }; typedef shared_ptr IConfigPtr; -IConfigPtr getConfig(); +IConfigPtr get_config(); #endif diff --git a/include/IController.hpp b/include/IController.hpp index c6ead1d..02b6f62 100644 --- a/include/IController.hpp +++ b/include/IController.hpp @@ -34,12 +34,12 @@ enum Action { struct IController { virtual ~IController() {} - virtual void actOn(Action anAction) = 0; + virtual void act_on(Action an_action) = 0; // Get current values for the display virtual int throttle() const = 0; - virtual bool brakeOn() const = 0; - virtual bool reverseOn() const = 0; + virtual bool brake_on() const = 0; + virtual bool reverse_on() const = 0; virtual double pressure() const = 0; virtual double temp() const = 0; diff --git a/include/IFog.hpp b/include/IFog.hpp index ca73d35..1d2d2f1 100644 --- a/include/IFog.hpp +++ b/include/IFog.hpp @@ -30,10 +30,10 @@ struct IFog { typedef std::tr1::shared_ptr IFogPtr; // Construct a generic fog -IFogPtr makeFog(float r, float g, float b, +IFogPtr make_fog(float r, float g, float b, float density, float start, float end); // Construct a fog from the current clear colour -IFogPtr makeFog(float density, float start, float end); +IFogPtr make_fog(float density, float start, float end); #endif diff --git a/include/IGraphics.hpp b/include/IGraphics.hpp index 701d405..9e3a36a 100644 --- a/include/IGraphics.hpp +++ b/include/IGraphics.hpp @@ -26,15 +26,15 @@ struct IGraphics { virtual ~IGraphics() {} // Camera - virtual bool cuboidInViewFrustum(float x, float y, float z, + virtual bool cuboid_in_viewFrustum(float x, float y, float z, float sizeX, float sizeY, float sizeZ) = 0; - virtual bool cubeInViewFrustum(float x, float y, float z, + virtual bool cube_in_viewFrustum(float x, float y, float z, float size) = 0; - virtual bool pointInViewFrustum(float x, float y, float z) = 0; - virtual void setCamera(const Vector& aPos, - const Vector& aRotation) = 0; - virtual void lookAt(const Vector anEyePoint, - const Vector aTargetPoint) = 0; + virtual bool point_in_viewFrustum(float x, float y, float z) = 0; + virtual void set_camera(const Vector& a_pos, + const Vector& a_rotation) = 0; + virtual void look_at(const Vector an_eye_point, + const Vector a_target_point) = 0; }; typedef std::tr1::shared_ptr IGraphicsPtr; diff --git a/include/ILight.hpp b/include/ILight.hpp index f0896a5..e8dbf58 100644 --- a/include/ILight.hpp +++ b/include/ILight.hpp @@ -31,6 +31,6 @@ struct ILight { typedef std::tr1::shared_ptr ILightPtr; // A weak non-directional light -ILightPtr makeSunLight(); +ILightPtr make_sun_light(); #endif diff --git a/include/ILogger.hpp b/include/ILogger.hpp index 2f973e5..5c4a9c6 100644 --- a/include/ILogger.hpp +++ b/include/ILogger.hpp @@ -24,7 +24,7 @@ // Stream surrogate for writing log data to struct PrintLine { - PrintLine(std::ostream& aStream); + PrintLine(std::ostream& a_stream); ~PrintLine(); std::ostream& stream; }; @@ -32,11 +32,11 @@ struct PrintLine { typedef std::tr1::shared_ptr PrintLinePtr; template -inline PrintLinePtr operator<<(PrintLinePtr aPrintLine, const T& aThing) +inline PrintLinePtr operator<<(PrintLinePtr a_print_line, const T& a_thing) { using namespace std; - aPrintLine->stream << aThing; - return aPrintLine; + a_print_line->stream << a_thing; + return a_print_line; } // Types of log levels @@ -48,16 +48,16 @@ enum LogMsgType { struct ILogger { virtual ~ILogger() {} - virtual PrintLinePtr writeMsg(LogMsgType type = LOG_NORMAL) = 0; + virtual PrintLinePtr write_msg(LogMsgType type = LOG_NORMAL) = 0; }; typedef std::tr1::shared_ptr ILoggerPtr; -ILoggerPtr getLogger(); +ILoggerPtr get_logger(); inline PrintLinePtr log(LogMsgType type = LOG_NORMAL) { - return getLogger()->writeMsg(type); + return get_logger()->write_msg(type); } inline PrintLinePtr warn() { return log(LOG_WARN); } diff --git a/include/IMap.hpp b/include/IMap.hpp index 8bf7f9b..8966695 100644 --- a/include/IMap.hpp +++ b/include/IMap.hpp @@ -37,42 +37,42 @@ public: // Return the track segment at the given position // It is invalid to call this with a position that doesn't - // contain the *origin* of a track segment -- call isValidTrack + // contain the *origin* of a track segment -- call is_valid_track // first - virtual ITrackSegmentPtr trackAt(const Point& aPoint) const = 0; + virtual ITrackSegmentPtr track_at(const Point& a_point) const = 0; // True if the given position is the origin of a track segment - virtual bool isValidTrack(const Point& aPoint) const = 0; + virtual bool is_valid_track(const Point& a_point) const = 0; // Change the track segment at the given position // Set rebuild to true to update the display lists used to render // the map - virtual void setTrackAt(const Point& aPoint, - ITrackSegmentPtr aTrack) = 0; + virtual void set_track_at(const Point& a_point, + ITrackSegmentPtr a_track) = 0; // Return the station at this track location or a null pointer - virtual IStationPtr stationAt(Point aPoint) const = 0; + virtual IStationPtr station_at(Point a_point) const = 0; // Delete the contents of a tile - virtual void eraseTile(int x, int y) = 0; + virtual void erase_tile(int x, int y) = 0; // False if this tile has something in it (track, scenery, etc.) - virtual bool emptyTile(Point point) const = 0; + virtual bool empty_tile(Point point) const = 0; // The start location consists of both a position and // a direction vector virtual track::Connection start() const = 0; - virtual void render(IGraphicsPtr aContext) const = 0; + virtual void render(IGraphicsPtr a_context) const = 0; // Draw a coloured highlight over the given tile - virtual void highlightTile(Point point, Colour colour) const = 0; + virtual void highlight_tile(Point point, Colour colour) const = 0; // Given a pick name return the (x, y) co-ordinate - virtual Point pickPosition(unsigned aName) const = 0; + virtual Point pick_position(unsigned a_name) const = 0; // True if this names a valid tile - virtual bool isValidTileName(unsigned aName) const = 0; + virtual bool is_valid_tileName(unsigned a_name) const = 0; // Save the map to its resource virtual void save() = 0; @@ -82,61 +82,61 @@ public: // Change the start location // The second variant allows setting the direction as well - virtual void setStart(int x, int y) = 0; - virtual void setStart(int x, int y, int dirX, int dirY) = 0; + virtual void set_start(int x, int y) = 0; + virtual void set_start(int x, int y, int dirX, int dirY) = 0; // Toggle display of grid lines - virtual void setGrid(bool onOff) = 0; + virtual void set_grid(bool on_off) = 0; // Toggle pick mode on and off // This turns of display of everything but the terrain // and things that can be clicked on - virtual void setPickMode(bool onOff) = 0; + virtual void set_pick_mode(bool on_off) = 0; // Make a hill or valley in the given area - virtual void raiseArea(const Point& aStartPos, - const Point& aFinishPos) = 0; - virtual void lowerArea(const Point& aStartPos, - const Point& aFinishPos) = 0; + virtual void raise_area(const Point& a_start_pos, + const Point& a_finish_pos) = 0; + virtual void lower_area(const Point& a_start_pos, + const Point& a_finish_pos) = 0; // Make all tiles in the area the same height - virtual void levelArea(Point aStartPos, Point aFinishPos) = 0; + virtual void level_area(Point a_start_pos, Point a_finish_pos) = 0; // Smooth the gradient along a strip - virtual void smoothArea(Point start, Point finish) = 0; + virtual void smooth_area(Point start, Point finish) = 0; // Create a new station covering this area or extend an existing station - virtual IStationPtr extendStation(Point aStartPos, - Point aFinishPos) = 0; + virtual IStationPtr extend_station(Point a_start_pos, + Point a_finish_pos) = 0; // Get the height above ground at a particular point - virtual float heightAt(float x, float y) const = 0; - virtual float heightAt(Point where) const = 0; + virtual float height_at(float x, float y) const = 0; + virtual float height_at(Point where) const = 0; // Given a tile and an axis, return a vector indicating the slope // along that axis. `level' is set if the slope is the same across // the tile - virtual Vector slopeAt(Point where, + virtual Vector slope_at(Point where, track::Direction axis, bool& level) const = 0; - // Similar to slopeAt, but calculates slope of tile before and + // Similar to slope_at, but calculates slope of tile before and // after along `axis' - virtual Vector slopeBefore(Point where, + virtual Vector slope_before(Point where, track::Direction axis, bool &valid) const = 0; - virtual Vector slopeAfter(Point where, + virtual Vector slope_after(Point where, track::Direction axis, bool &valid) const = 0; // Place a tree, building, etc. at a location - virtual void addScenery(Point where, ISceneryPtr s) = 0; + virtual void add_scenery(Point where, ISceneryPtr s) = 0; }; typedef shared_ptr IMapPtr; // Make an empty map inside a resource -IMapPtr makeEmptyMap(const string& aResId, int aWidth, int aHeight); +IMapPtr make_empty_map(const string& a_res_id, int a_width, int a_height); // Load a map from a resource -IMapPtr loadMap(const string& aResId); +IMapPtr load_map(const string& a_res_id); #endif diff --git a/include/IMesh.hpp b/include/IMesh.hpp index caa7107..adce4f5 100644 --- a/include/IMesh.hpp +++ b/include/IMesh.hpp @@ -44,27 +44,27 @@ struct IMeshBuffer { virtual ~IMeshBuffer() {} - virtual size_t vertexCount() const = 0; + virtual size_t vertex_count() const = 0; virtual void add(const Vertex& vertex, const Normal& normal) = 0; virtual void add(const Vertex& vertex, const Normal& normal, - const TexCoord& aTexCoord) = 0; + const TexCoord& a_tex_coord) = 0; virtual void add(const Vertex& vertex, const Normal& normal, const Colour& colour) = 0; // Convenience functions - virtual void addQuad(Vertex a, Vertex b, Vertex c, Vertex d, + virtual void add_quad(Vertex a, Vertex b, Vertex c, Vertex d, Colour colour) = 0; - virtual void addQuad(Vertex a, Vertex b, Vertex c, Vertex d, + virtual void add_quad(Vertex a, Vertex b, Vertex c, Vertex d, Normal na, Normal nb, Normal nc, Normal nd, Colour colour) = 0; - virtual void bindMaterial(const Material& aMaterial) = 0; + virtual void bind_material(const Material& a_material) = 0; - virtual void printStats() const = 0; + virtual void print_stats() const = 0; virtual void merge(shared_ptr other, - Vector off, float yAngle=0.0f) = 0; + Vector off, float y_angle=0.0f) = 0; }; typedef shared_ptr IMeshBufferPtr; @@ -78,9 +78,9 @@ struct IMesh { typedef shared_ptr IMeshPtr; -IMeshPtr makeMesh(IMeshBufferPtr aBuffer); -IMeshBufferPtr makeMeshBuffer(); -void updateRenderStats(); -int getAverageTriangleCount(); +IMeshPtr make_mesh(IMeshBufferPtr a_buffer); +IMeshBufferPtr make_mesh_buffer(); +void update_render_stats(); +int get_average_triangleCount(); #endif diff --git a/include/IMessageArea.hpp b/include/IMessageArea.hpp index 1c79c05..ad0a7a4 100644 --- a/include/IMessageArea.hpp +++ b/include/IMessageArea.hpp @@ -38,6 +38,6 @@ struct IMessageArea { typedef shared_ptr IMessageAreaPtr; -IMessageAreaPtr makeMessageArea(); +IMessageAreaPtr make_message_area(); #endif diff --git a/include/IModel.hpp b/include/IModel.hpp index f4d23a2..b11f956 100644 --- a/include/IModel.hpp +++ b/include/IModel.hpp @@ -31,14 +31,14 @@ struct IModel { virtual void render() const = 0; virtual void cache() = 0; virtual void merge(IMeshBufferPtr buf, - Vector off, float yAngle=0.0f) const = 0; + Vector off, float y_angle=0.0f) const = 0; virtual Vector dimensions() const = 0; }; typedef shared_ptr IModelPtr; // Load a model from a WaveFront .obj file -IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, - float aScale = 1.0f); +IModelPtr load_model(IResourcePtr a_res, const string& a_file_name, + float a_scale = 1.0f); #endif diff --git a/include/IPickBuffer.hpp b/include/IPickBuffer.hpp index 9fb1d43..5eaa143 100644 --- a/include/IPickBuffer.hpp +++ b/include/IPickBuffer.hpp @@ -25,8 +25,8 @@ struct IPickBuffer { virtual ~IPickBuffer() {} - virtual IGraphicsPtr beginPick(int x, int y) = 0; - virtual unsigned endPick() = 0; + virtual IGraphicsPtr begin_pick(int x, int y) = 0; + virtual unsigned end_pick() = 0; }; typedef shared_ptr IPickBufferPtr; diff --git a/include/IQuadTree.hpp b/include/IQuadTree.hpp index 8924e5f..22e0204 100644 --- a/include/IQuadTree.hpp +++ b/include/IQuadTree.hpp @@ -26,10 +26,10 @@ struct ISectorRenderable { virtual ~ISectorRenderable() {} - virtual void renderSector(IGraphicsPtr aContext, int id, - Point botLeft, Point topRight) = 0; - virtual void postRenderSector(IGraphicsPtr aContext, int id, - Point botLeft, Point topRight) = 0; + virtual void render_sector(IGraphicsPtr a_context, int id, + Point bot_left, Point top_right) = 0; + virtual void post_render_sector(IGraphicsPtr a_context, int id, + Point bot_left, Point top_right) = 0; }; typedef shared_ptr ISectorRenderablePtr; @@ -38,14 +38,14 @@ typedef shared_ptr ISectorRenderablePtr; struct IQuadTree { virtual ~IQuadTree() {} - virtual void render(IGraphicsPtr aContext) = 0; - virtual int leafSize() const = 0; + virtual void render(IGraphicsPtr a_context) = 0; + virtual int leaf_size() const = 0; }; typedef shared_ptr IQuadTreePtr; // Produce a quad tree of given square dimension -IQuadTreePtr makeQuadTree(ISectorRenderablePtr aRenderable, +IQuadTreePtr make_quad_tree(ISectorRenderablePtr a_renderable, int width, int height); #endif diff --git a/include/IResource.hpp b/include/IResource.hpp index f5aa26d..0c72faa 100644 --- a/include/IResource.hpp +++ b/include/IResource.hpp @@ -32,37 +32,37 @@ struct IResource { virtual ~IResource() {} virtual string name() const = 0; - virtual string xmlFileName() const = 0; // REMOVE - // (Should be replaced by Handle openXmlFile() + virtual string xml_file_name() const = 0; // REMOVE + // (Should be replaced by Handle open_xml_file() // A handle for reading data out of files in resources class Handle { public: enum Mode { READ, WRITE }; - explicit Handle(const string& fileName, Mode mode = READ); + explicit Handle(const string& file_name, Mode mode = READ); ~Handle() { commit(); } - ifstream& rstream() { return *readStream; } - ofstream& wstream() { return *writeStream; } + ifstream& rstream() { return *read_stream; } + ofstream& wstream() { return *write_stream; } - string fileName() const { return fileName_; } + string file_name() const { return file_name_; } Mode mode() const { return mode_; } void commit(); void rollback(); private: - string tmpFileName() const; + string tmp_file_name() const; - shared_ptr readStream; - shared_ptr writeStream; - const string fileName_; + shared_ptr read_stream; + shared_ptr write_stream; + const string file_name_; const Mode mode_; bool aborted; }; - virtual Handle openFile(const string& aName) = 0; - virtual Handle writeFile(const string& aName) = 0; + virtual Handle open_file(const string& a_name) = 0; + virtual Handle write_file(const string& a_name) = 0; }; typedef shared_ptr IResourcePtr; @@ -71,10 +71,10 @@ typedef list ResourceList; typedef ResourceList::iterator ResourceListIt; // Generic interface to game resources -void initResources(); -void enumResources(const string& aClass, ResourceList& aList); -IResourcePtr findResource(const string& aResId, const string& aClass); -IResourcePtr makeNewResource(const string& aResId, const string& aClass); -bool resourceExists(const string& aResId, const string& aClass); +void init_resources(); +void enum_resources(const string& a_class, ResourceList& a_list); +IResourcePtr find_resource(const string& a_res_id, const string& a_class); +IResourcePtr make_new_resource(const string& a_res_id, const string& a_class); +bool resource_exists(const string& a_res_id, const string& a_class); #endif diff --git a/include/IRollingStock.hpp b/include/IRollingStock.hpp index c5b7daa..614200e 100644 --- a/include/IRollingStock.hpp +++ b/include/IRollingStock.hpp @@ -48,7 +48,7 @@ struct IRollingStock { typedef shared_ptr IRollingStockPtr; // Make various waggons and engines -IRollingStockPtr loadEngine(const string& aResId); -IRollingStockPtr loadWaggon(const string& aResId); +IRollingStockPtr load_engine(const string& a_res_id); +IRollingStockPtr load_waggon(const string& a_res_id); #endif diff --git a/include/IScenery.hpp b/include/IScenery.hpp index 9f458f8..78273e1 100644 --- a/include/IScenery.hpp +++ b/include/IScenery.hpp @@ -27,8 +27,8 @@ struct IScenery : IXMLSerialisable { virtual ~IScenery() {} virtual void render() const = 0; - virtual void setPosition(float x, float y, float z) = 0; - virtual void setAngle(float angle) = 0; + virtual void set_position(float x, float y, float z) = 0; + virtual void set_angle(float angle) = 0; virtual void merge(IMeshBufferPtr buf) = 0; virtual const string& name() const = 0; }; @@ -37,10 +37,10 @@ typedef shared_ptr ISceneryPtr; class AttributeSet; -ISceneryPtr loadTree(const string& name); -ISceneryPtr loadTree(const AttributeSet& attrs); +ISceneryPtr load_tree(const string& name); +ISceneryPtr load_tree(const AttributeSet& attrs); -ISceneryPtr loadBuilding(const string& aResId, float angle); -ISceneryPtr loadBuilding(const AttributeSet& attrs); +ISceneryPtr load_building(const string& a_res_id, float angle); +ISceneryPtr load_building(const AttributeSet& attrs); #endif diff --git a/include/ISceneryPicker.hpp b/include/ISceneryPicker.hpp index 7a36f4a..8eafc57 100644 --- a/include/ISceneryPicker.hpp +++ b/include/ISceneryPicker.hpp @@ -31,7 +31,7 @@ struct ISceneryPicker { typedef shared_ptr ISceneryPickerPtr; -ISceneryPickerPtr makeBuildingPicker(gui::ILayoutPtr layout); -ISceneryPickerPtr makeTreePicker(gui::ILayoutPtr layout); +ISceneryPickerPtr make_building_picker(gui::ILayoutPtr layout); +ISceneryPickerPtr make_tree_picker(gui::ILayoutPtr layout); #endif diff --git a/include/IScreen.hpp b/include/IScreen.hpp index 5657e44..5a961b4 100644 --- a/include/IScreen.hpp +++ b/include/IScreen.hpp @@ -34,23 +34,23 @@ struct IScreen { virtual ~IScreen() {} // Draw the 3D part of the screen - virtual void display(IGraphicsPtr aContext) const = 0; + virtual void display(IGraphicsPtr a_context) const = 0; // Draw the 2D part of the screen virtual void overlay() const = 0; // Update the state of the game // Delta delay is milliseconds since last frame - virtual void update(IPickBufferPtr aPickBuffer, int aDelta) = 0; + virtual void update(IPickBufferPtr a_pick_buffer, int a_delta) = 0; - virtual void onKeyDown(SDLKey aKey) = 0; - virtual void onKeyUp(SDLKey aKey) = 0; - virtual void onMouseMove(IPickBufferPtr aPickBuffer, int x, int y, + virtual void on_key_down(SDLKey a_key) = 0; + virtual void on_key_up(SDLKey a_key) = 0; + virtual void on_mouse_move(IPickBufferPtr a_pick_buffer, int x, int y, int xrel, int yrel) = 0; - virtual void onMouseClick(IPickBufferPtr aPickBuffer, int x, int y, - MouseButton aButton) = 0; - virtual void onMouseRelease(IPickBufferPtr aPickBuffer, int x, int y, - MouseButton aButton) = 0; + virtual void on_mouse_click(IPickBufferPtr a_pick_buffer, int x, int y, + MouseButton a_button) = 0; + virtual void on_mouse_release(IPickBufferPtr a_pick_buffer, int x, int y, + MouseButton a_button) = 0; }; typedef shared_ptr IScreenPtr; diff --git a/include/ISkyBox.hpp b/include/ISkyBox.hpp index a9144b3..ef3506f 100644 --- a/include/ISkyBox.hpp +++ b/include/ISkyBox.hpp @@ -24,11 +24,11 @@ struct ISkyBox { virtual ~ISkyBox() {} - virtual void apply(float anAngle=0.0f) const = 0; + virtual void apply(float an_angle=0.0f) const = 0; }; typedef shared_ptr ISkyBoxPtr; -ISkyBoxPtr makeSkyBox(const string& aBaseName); +ISkyBoxPtr make_sky_box(const string& a_base_name); #endif diff --git a/include/ISmokeTrail.hpp b/include/ISmokeTrail.hpp index d60f3a3..389d679 100644 --- a/include/ISmokeTrail.hpp +++ b/include/ISmokeTrail.hpp @@ -25,24 +25,24 @@ struct ISmokeTrail { virtual ~ISmokeTrail() {} // Move and generate new particles - virtual void update(int aDelta) = 0; + virtual void update(int a_delta) = 0; // Draw all the particles virtual void render() const = 0; // Change the position where new particles are generated - virtual void setPosition(float x, float y, float z) = 0; + virtual void set_position(float x, float y, float z) = 0; // Change the initial velocity of new particles - virtual void setVelocity(float x, float y, float z) = 0; + virtual void set_velocity(float x, float y, float z) = 0; // Change the rate at which particles are created // Delay is in milliseconds - virtual void setDelay(int aDelay) = 0; + virtual void set_delay(int a_delay) = 0; }; typedef shared_ptr ISmokeTrailPtr; -ISmokeTrailPtr makeSmokeTrail(); +ISmokeTrailPtr make_smoke_trail(); #endif diff --git a/include/IStation.hpp b/include/IStation.hpp index 720f0ab..aae5df7 100644 --- a/include/IStation.hpp +++ b/include/IStation.hpp @@ -40,22 +40,22 @@ struct IStation { // This is only used for the user's benefit and does not identify // the station in any way virtual const string& name() const = 0; - virtual void setName(const string& aName) = 0; + virtual void set_name(const string& a_name) = 0; // A station has an ID that uniquely identifies it // Setting is allowed to support the map loader virtual int id() const = 0; - virtual void setId(int anId) = 0; + virtual void set_id(int an_id) = 0; // A station has a random colour that is used to identify it when // the highlight is drawn - virtual Colour highlightColour() const = 0; - virtual bool highlightVisible() const = 0; - virtual void setHighlightVisible(bool onOff) = 0; + virtual Colour highlight_colour() const = 0; + virtual bool highlight_visible() const = 0; + virtual void set_highlight_visible(bool on_off) = 0; }; typedef shared_ptr IStationPtr; -IStationPtr makeStation(); +IStationPtr make_station(); #endif diff --git a/include/ITexture.hpp b/include/ITexture.hpp index 6dc23d2..67e1866 100644 --- a/include/ITexture.hpp +++ b/include/ITexture.hpp @@ -39,9 +39,9 @@ typedef shared_ptr ITexturePtr; // Load a texture and return a pointer to // A texture will only be loaded at most once no matter how many // times this is called -ITexturePtr loadTexture(const string& aFileName); +ITexturePtr load_texture(const string& a_file_name); // Load a texture from a resource -ITexturePtr loadTexture(IResourcePtr aRes, const string& aFileName); +ITexturePtr load_texture(IResourcePtr a_res, const string& a_file_name); #endif diff --git a/include/ITrackSegment.hpp b/include/ITrackSegment.hpp index 5e57844..a73cd85 100644 --- a/include/ITrackSegment.hpp +++ b/include/ITrackSegment.hpp @@ -45,7 +45,7 @@ namespace track { typedef function TransformFunc; typedef function GradientFunc; - inline float flatGradientFunc(const TravelToken& t, float d) { return 0.0f; } + inline float flat_gradient_func(const TravelToken& t, float d) { return 0.0f; } // Sums up all the information required to travel along a piece // of track @@ -66,7 +66,7 @@ namespace track { // Number of possible exits from this track segment given the direction // we are travelling in - int numExits; + int num_exits; // Wrappers for the above functions @@ -84,8 +84,8 @@ namespace track { // Orientations for straight track namespace axis { - const track::Direction X = makeVector(1, 0, 0); - const track::Direction Y = makeVector(0, 0, 1); + const track::Direction X = make_vector(1, 0, 0); + const track::Direction Y = make_vector(0, 0, 1); } struct ITrackSegment; @@ -103,38 +103,38 @@ struct ITrackSegment : IXMLSerialisable { virtual void merge(IMeshBufferPtr buf) const = 0; // Set the absolute position of the track in the world - virtual void setOrigin(int x, int y, float height) = 0; + virtual void set_origin(int x, int y, float height) = 0; // Get the length of this track segment - virtual float segmentLength(const track::TravelToken& aToken) const = 0; + virtual float segment_length(const track::TravelToken& a_token) const = 0; // Get a travel token for this track segment starting at a particular // position and moving in a particular direciton - virtual track::TravelToken getTravelToken(track::Position aPosition, - track::Direction aDirection) const = 0; + virtual track::TravelToken get_travel_token(track::Position a_position, + track::Direction a_direction) const = 0; // True if a train can travel in this direction along the track - virtual bool isValidDirection(const track::Direction& aDirection) const = 0; + virtual bool is_valid_direction(const track::Direction& a_direction) const = 0; // Return the position of the next segment of track and the // orientation of the train. // Note that this may not actually be a valid track segment! - // You should call IMap::isValidTrack before using it (this + // You should call IMap::is_valid_track before using it (this // will happen, e.g. if the train runs off the end of the line) // The token passed here must have been generated by this track // segment when the train entered it. - virtual track::Connection nextPosition(const track::TravelToken& aToken) + virtual track::Connection next_position(const track::TravelToken& a_token) const = 0; // Add all the endpoints of the track segment to the given list // Note that an endpoint is not the same as what is returned - // from `nextPosition' - e.g. a straight track that takes up + // from `next_position' - e.g. a straight track that takes up // one tile has a single endpoint which is its origin - virtual void getEndpoints(vector >& aList) const = 0; + virtual void get_endpoints(vector >& a_list) const = 0; // Similar to endpoints, the `covers' of a track are the tiles // which are not endpoints but are underneath the track - virtual void getCovers(vector >& output) const = 0; + virtual void get_covers(vector >& output) const = 0; // Add an exit to this section of track possibly generating // a new track segment @@ -143,27 +143,27 @@ struct ITrackSegment : IXMLSerialisable { // may be bigger than the origin segment // The track may already have an exit here in which case // a pointer to itself will be returned - virtual ITrackSegmentPtr mergeExit(Point where, + virtual ITrackSegmentPtr merge_exit(Point where, track::Direction dir) = 0; // Some track segments may have several states - e.g. points // These functions change the track state - virtual bool hasMultipleStates() const = 0; - virtual void prevState() = 0; - virtual void nextState() = 0; + virtual bool has_multiple_states() const = 0; + virtual void prev_state() = 0; + virtual void next_state() = 0; // Set a hint to display something about the track state on the next render // call - e.g display an arrow over points - virtual void setStateRenderHint() = 0; + virtual void set_state_renderHint() = 0; }; -ITrackSegmentPtr makeStraightTrack(const track::Direction& aDirection); -ITrackSegmentPtr makeCurvedTrack(track::Angle aStartAngle, - track::Angle aFinishAngle, int aRadius); -ITrackSegmentPtr makeCrossoverTrack(); -ITrackSegmentPtr makePoints(track::Direction aDirection, bool reflect); -ITrackSegmentPtr makeSlopeTrack(track::Direction axis, Vector slope, - Vector slopeBefore, Vector slopeAfter); +ITrackSegmentPtr make_straight_track(const track::Direction& a_direction); +ITrackSegmentPtr make_curved_track(track::Angle a_start_angle, + track::Angle a_finish_angle, int a_radius); +ITrackSegmentPtr make_crossover_track(); +ITrackSegmentPtr make_points(track::Direction a_direction, bool reflect); +ITrackSegmentPtr make_slope_track(track::Direction axis, Vector slope, + Vector slope_before, Vector slope_after); ITrackSegmentPtr makeSBend(track::Direction dir, int straight, int off); #endif diff --git a/include/ITrain.hpp b/include/ITrain.hpp index da63d1a..a3bc626 100644 --- a/include/ITrain.hpp +++ b/include/ITrain.hpp @@ -28,14 +28,14 @@ struct ITrain { virtual ~ITrain() {} virtual void render() const = 0; - virtual void update(int aDelta) = 0; + virtual void update(int a_delta) = 0; // Return a vector of the absolute position of the front of // the train virtual Vector front() const = 0; // Return the track segment occupied by the front of the train - virtual ITrackSegmentPtr trackSegment() const = 0; + virtual ITrackSegmentPtr track_segment() const = 0; // Return the tile occupied by the front of the train virtual track::Position tile() const = 0; @@ -52,6 +52,6 @@ struct ITrain { typedef std::tr1::shared_ptr ITrainPtr; -ITrainPtr makeTrain(IMapPtr aMap); +ITrainPtr make_train(IMapPtr a_map); #endif diff --git a/include/IWindow.hpp b/include/IWindow.hpp index c50c383..ea56e22 100644 --- a/include/IWindow.hpp +++ b/include/IWindow.hpp @@ -26,10 +26,10 @@ class IWindow { public: virtual ~IWindow() {} - virtual void run(IScreenPtr aScreen) = 0; - virtual void switchScreen(IScreenPtr aScreen) = 0; + virtual void run(IScreenPtr a_screen) = 0; + virtual void switch_screen(IScreenPtr a_screen) = 0; virtual void quit() = 0; - virtual void takeScreenShot() = 0; + virtual void take_screen_shot() = 0; virtual int width() const = 0; virtual int height() const = 0; }; diff --git a/include/IXMLParser.hpp b/include/IXMLParser.hpp index 8d6ffa7..83f02e3 100644 --- a/include/IXMLParser.hpp +++ b/include/IXMLParser.hpp @@ -33,10 +33,10 @@ namespace { template - T xmlAttrCast(const string& str); + T xml_attr_cast(const string& str); template <> - bool xmlAttrCast(const string& str) + bool xml_attr_cast(const string& str) { istringstream ss(str); bool result; @@ -52,7 +52,7 @@ namespace { } template <> - Colour xmlAttrCast(const string& str) + Colour xml_attr_cast(const string& str) { istringstream ss(str); int r, g, b; @@ -68,7 +68,7 @@ namespace { } template - T xmlAttrCast(const string& str) + T xml_attr_cast(const string& str) { return boost::lexical_cast(str); } @@ -79,43 +79,43 @@ namespace { class AttributeSet { public: AttributeSet(const xercesc::Attributes& attrs) - : myAttrs(attrs) {} + : my_attrs(attrs) {} bool has(const string& name) const { - XMLCh* xmlName = xercesc::XMLString::transcode(name.c_str()); + XMLCh* xml_name = xercesc::XMLString::transcode(name.c_str()); - int index = myAttrs.getIndex(xmlName); - xercesc::XMLString::release(&xmlName); + int index = my_attrs.getIndex(xml_name); + xercesc::XMLString::release(&xml_name); return index != -1; } template - T get(const std::string& aName) const + T get(const std::string& a_name) const { - XMLCh* xmlName = xercesc::XMLString::transcode(aName.c_str()); + XMLCh* xml_name = xercesc::XMLString::transcode(a_name.c_str()); - int index = myAttrs.getIndex(xmlName); - xercesc::XMLString::release(&xmlName); + int index = my_attrs.getIndex(xml_name); + xercesc::XMLString::release(&xml_name); if (index != -1) { char* ascii = xercesc::XMLString::transcode( - myAttrs.getValue(index)); + my_attrs.getValue(index)); - T result = xmlAttrCast(ascii); + T result = xml_attr_cast(ascii); xercesc::XMLString::release(&ascii); return result; } else - throw std::runtime_error("No attribute: " + aName); + throw std::runtime_error("No attribute: " + a_name); } template - void get(const std::string& aName, T& aT) const + void get(const std::string& a_name, T& aT) const { - aT = get(aName); + aT = get(a_name); } // Get with default @@ -126,31 +126,31 @@ public: } private: - const xercesc::Attributes& myAttrs; + const xercesc::Attributes& my_attrs; }; // SAX-like interface to XML parsing struct IXMLCallback { virtual ~IXMLCallback() {} - virtual void startElement(const string& localName, + virtual void start_element(const string& local_name, const AttributeSet& attrs) {} - virtual void endElement(const string& localName) {} - virtual void text(const string& localName, - const string& aString) {} + virtual void end_element(const string& local_name) {} + virtual void text(const string& local_name, + const string& a_string) {} }; // Interface to a validating XML parser struct IXMLParser { virtual ~IXMLParser() {} - virtual void parse(const std::string& aFileName, - IXMLCallback& aCallback) = 0; + virtual void parse(const std::string& a_file_name, + IXMLCallback& a_callback) = 0; }; typedef std::tr1::shared_ptr IXMLParserPtr; -IXMLParserPtr makeXMLParser(const std::string& aSchemaFile); +IXMLParserPtr makeXMLParser(const std::string& a_schema_file); #endif diff --git a/include/IXMLSerialisable.hpp b/include/IXMLSerialisable.hpp index 219ffd9..8634c6f 100644 --- a/include/IXMLSerialisable.hpp +++ b/include/IXMLSerialisable.hpp @@ -25,7 +25,7 @@ namespace xml { struct IXMLSerialisable { virtual ~IXMLSerialisable() {} - virtual xml::element toXml() const = 0; + virtual xml::element to_xml() const = 0; }; #endif diff --git a/include/IterateTrack.hpp b/include/IterateTrack.hpp index 1217871..07a3fd9 100644 --- a/include/IterateTrack.hpp +++ b/include/IterateTrack.hpp @@ -47,7 +47,7 @@ struct TrackIterator { }; // Kick off the iteration at an initial track segment -TrackIterator iterateTrack(IMapPtr aMap, track::Position aPosition, - track::Direction aDirection); +TrackIterator iterate_track(IMapPtr a_map, track::Position a_position, + track::Direction a_direction); #endif diff --git a/include/Maths.hpp b/include/Maths.hpp index e04d8cf..bd52d3a 100644 --- a/include/Maths.hpp +++ b/include/Maths.hpp @@ -113,7 +113,7 @@ struct Vector { return !(v == *this); } - bool approxEqual(const Vector& rhs, T delta) const + bool approx_equal(const Vector& rhs, T delta) const { return (abs(rhs.x - x) < delta) && (abs(rhs.y - y) < delta) @@ -124,21 +124,21 @@ struct Vector { }; template -std::ostream& operator<<(std::ostream& aStream, const Vector& aVector) +std::ostream& operator<<(std::ostream& a_stream, const Vector& a_vector) { - return aStream << "[" << aVector.x << " " << aVector.y - << " " << aVector.z << "]"; + return a_stream << "[" << a_vector.x << " " << a_vector.y + << " " << a_vector.z << "]"; } template -Vector makeVector(T x, T y, T z) +Vector make_vector(T x, T y, T z) { return Vector(x, y, z); } // Find a surface normal template -Vector surfaceNormal(const Vector& a, const Vector& b, +Vector surface_normal(const Vector& a, const Vector& b, const Vector& c) { Vector v1 = b - a; @@ -149,8 +149,8 @@ Vector surfaceNormal(const Vector& a, const Vector& b, } // Useful debugging function -void drawNormal(const Vector& aPosition, - const Vector& aNormal); +void draw_normal(const Vector& a_position, + const Vector& a_normal); // A 2D point in space template @@ -163,9 +163,9 @@ struct Point { Point up() const { return Point(x, y + 1); } Point down() const { return Point(x, y - 1); } - bool operator==(const Point& aPoint) const + bool operator==(const Point& a_point) const { - return aPoint.x == x && aPoint.y == y; + return a_point.x == x && a_point.y == y; } bool operator!=(const Point& rhs) const @@ -194,43 +194,43 @@ struct Point { }; template -std::ostream& operator<<(std::ostream& aStream, const Point& aPoint) +std::ostream& operator<<(std::ostream& a_stream, const Point& a_point) { - return aStream << "(" << aPoint.x << ", " << aPoint.y << ")"; + return a_stream << "(" << a_point.x << ", " << a_point.y << ")"; } template -Point makePoint(T x, T y) +Point make_point(T x, T y) { return Point(x, y); } // A frustum struct Frustum { - bool pointInFrustum(float x, float y, float z); - bool sphereInFrustum(float x, float y, float z, float radius); - bool cubeInFrustum(float x, float y, float z, float size); // size = 0.5*side_length - bool cuboidInFrustum(float x, float y, float z, + bool point_in_frustum(float x, float y, float z); + bool sphere_in_frustum(float x, float y, float z, float radius); + bool cube_in_frustum(float x, float y, float z, float size); // size = 0.5*side_length + bool cuboid_in_frustum(float x, float y, float z, float sizeX, float sizeY, float sizeZ); float planes[6][4]; }; -Frustum getViewFrustum(); +Frustum get_view_frustum(); // A rough guess at the gradient at a point on a curve -float approxGradient(function aFunc, float x); +float approx_gradient(function a_func, float x); // Useful functions for converting to/from radians template -inline float degToRad(T t) +inline float deg_to_rad(T t) { return static_cast(t) * M_PI / 180.0; } template -inline T radToDeg(float r) +inline T rad_to_deg(float r) { return static_cast(r * 180.0 / M_PI); } diff --git a/include/Matrix.hpp b/include/Matrix.hpp index 7dd9eb9..8b1a294 100644 --- a/include/Matrix.hpp +++ b/include/Matrix.hpp @@ -115,15 +115,15 @@ struct Matrix { { assert(N == 4); - T vCols[4] = { v.x, v.y, v.z, 1 }; + T v_cols[4] = { v.x, v.y, v.z, 1 }; T cols[4]; for (int i = 0; i < N; i++) { cols[i] = 0; for (int j = 0; j < N; j++) - cols[i] += entries[i][j] * vCols[j]; + cols[i] += entries[i][j] * v_cols[j]; } - return makeVector(cols[0], cols[1], cols[2]); + return make_vector(cols[0], cols[1], cols[2]); } Matrix& operator*=(const Matrix& rhs) diff --git a/include/MovingAverage.hpp b/include/MovingAverage.hpp index cb50037..20fe299 100644 --- a/include/MovingAverage.hpp +++ b/include/MovingAverage.hpp @@ -25,27 +25,27 @@ public: MovingAverage() { for (int i = 0; i < N; i++) - mySamples[i] = static_cast(0); + my_samples[i] = static_cast(0); } T value() const { T sum = static_cast(0); for (int i = 0; i < N; i++) - sum += mySamples[i]; + sum += my_samples[i]; return sum / static_cast(N); } - void operator<<(T aValue) + void operator<<(T a_value) { for (int i = N - 1; i > 0; i--) - mySamples[i] = mySamples[i-1]; - mySamples[0] = aValue; + my_samples[i] = my_samples[i-1]; + my_samples[0] = a_value; } private: - T mySamples[N]; + T my_samples[N]; }; #endif diff --git a/include/OpenGLHelper.hpp b/include/OpenGLHelper.hpp index 736aae3..73104c5 100644 --- a/include/OpenGLHelper.hpp +++ b/include/OpenGLHelper.hpp @@ -28,14 +28,14 @@ // Helper functions used by the different IWindow implementations void initGL(); -void drawGLScene(IWindowPtr aWindow, IGraphicsPtr aContext, IScreenPtr aScreen); -void resizeGLScene(IWindowPtr aWindow); +void drawGLScene(IWindowPtr a_window, IGraphicsPtr a_context, IScreenPtr a_screen); +void resizeGLScene(IWindowPtr a_window); void printGLVersion(); void checkGLError(); // Wrappers for OpenGL picking features -void beginPick(IWindowPtr aWindow, unsigned* aBuffer, int x, int y); -unsigned endPick(unsigned* aBuffer); +void begin_pick(IWindowPtr a_window, unsigned* a_buffer, int x, int y); +unsigned end_pick(unsigned* a_buffer); // Helper functions for using our Vector and Colour objects // as OpenGL types diff --git a/include/ResourceCache.hpp b/include/ResourceCache.hpp index 1c776ad..25cdd4a 100644 --- a/include/ResourceCache.hpp +++ b/include/ResourceCache.hpp @@ -29,20 +29,20 @@ class ResourceCache { public: typedef function LoaderType; - ResourceCache(LoaderType aLoader, const string& aClass) - : myLoader(aLoader), myClass(aClass) {} + ResourceCache(LoaderType a_loader, const string& a_class) + : my_loader(a_loader), my_class(a_class) {} // Load one single copy of this object // -> use this if the object has no state - shared_ptr load(const string& aResId) + shared_ptr load(const string& a_res_id) { - typename CacheType::iterator it = myCache.find(aResId); - if (it != myCache.end()) + typename CacheType::iterator it = my_cache.find(a_res_id); + if (it != my_cache.end()) return (*it).second; else { - T* loaded = myLoader(findResource(aResId, myClass)); + T* loaded = my_loader(find_resource(a_res_id, my_class)); shared_ptr ptr(loaded); - myCache[aResId] = ptr; + my_cache[a_res_id] = ptr; return ptr; } } @@ -50,18 +50,18 @@ public: // Make a copy each time a new object is loaded but only // parse the XML once // -> use this if the object has state - shared_ptr loadCopy(const string& aResId) + shared_ptr load_copy(const string& a_res_id) { - shared_ptr original = load(aResId); + shared_ptr original = load(a_res_id); return shared_ptr(new T(*original.get())); } private: - LoaderType myLoader; - const string myClass; + LoaderType my_loader; + const string my_class; typedef map > CacheType; - CacheType myCache; + CacheType my_cache; }; #endif diff --git a/include/TrackCommon.hpp b/include/TrackCommon.hpp index 9a440a6..231573a 100644 --- a/include/TrackCommon.hpp +++ b/include/TrackCommon.hpp @@ -26,58 +26,58 @@ class StraightTrackHelper { public: - void mergeStraightRail(IMeshBufferPtr buf, - Vector off, float yAngle) const; + void merge_straight_rail(IMeshBufferPtr buf, + Vector off, float y_angle) const; private: - void mergeOneRail(IMeshBufferPtr buf, - Vector off, float yAngle) const; + void merge_one_rail(IMeshBufferPtr buf, + Vector off, float y_angle) const; - static IMeshBufferPtr generateRailMeshBuffer(); + static IMeshBufferPtr generate_rail_meshBuffer(); - static IMeshBufferPtr railBuf; + static IMeshBufferPtr rail_buf; }; class SleeperHelper { public: - void mergeSleeper(IMeshBufferPtr buf, - Vector off, float yAngle) const; + void merge_sleeper(IMeshBufferPtr buf, + Vector off, float y_angle) const; private: - static IMeshBufferPtr generateSleeperMeshBuffer(); + static IMeshBufferPtr generate_sleeper_meshBuffer(); - static IMeshBufferPtr sleeperBuf; + static IMeshBufferPtr sleeper_buf; }; class BezierHelper { public: - IMeshBufferPtr makeBezierRailMesh(const BezierCurve& func) const; + IMeshBufferPtr make_bezier_railMesh(const BezierCurve& func) const; private: - static void buildOneBezierRail(const BezierCurve& func, + static void build_one_bezierRail(const BezierCurve& func, IMeshBufferPtr buf, float p); }; class CurvedTrackHelper : private SleeperHelper { public: - void mergeCurvedTrack(IMeshBufferPtr buf, Vector off, - int baseRadius, track::Angle startAngle, track::Angle endAngle) const; + void merge_curved_track(IMeshBufferPtr buf, Vector off, + int base_radius, track::Angle start_angle, track::Angle end_angle) const; private: - void transformToOrigin(Vector& off, - int baseRadius, track::Angle startAngle) const; + void transform_to_origin(Vector& off, + int base_radius, track::Angle start_angle) const; enum RailType { INNER_RAIL, OUTER_RAIL }; - static void generateCurvedRailMesh(IMeshBufferPtr buf, - int baseRadius, RailType type); - static void mergeCurvedRail(IMeshBufferPtr buf, int baseRadius, - Vector off, float yAngle); + static void generate_curved_railMesh(IMeshBufferPtr buf, + int base_radius, RailType type); + static void merge_curved_rail(IMeshBufferPtr buf, int base_radius, + Vector off, float y_angle); typedef map CurvedRailMeshMap; - static CurvedRailMeshMap curvedRailMeshes; + static CurvedRailMeshMap curved_rail_meshes; }; // Track constants diff --git a/include/XMLBuilder.hpp b/include/XMLBuilder.hpp index c56f0bf..c8a80b3 100644 --- a/include/XMLBuilder.hpp +++ b/include/XMLBuilder.hpp @@ -32,15 +32,15 @@ namespace xml { struct element { element(const string& name) - : hasChildren(false), name(name) + : has_children(false), name(name) { str = "<" + name; } template - element& addAttribute(const string& name, T t) + element& add_attribute(const string& name, T t) { - if (hasChildren) + if (has_children) throw runtime_error( "Cannot add XML attributes after children"); else { @@ -54,35 +54,35 @@ namespace xml { return *this; } - element& addChild(const element& e) + element& add_child(const element& e) { - if (!hasChildren) + if (!has_children) str += ">"; str += "\n" + e.finish(); - hasChildren = true; + has_children = true; return *this; } - element& addText(const string& text) + element& add_text(const string& text) { - if (!hasChildren) + if (!has_children) str += ">"; str += text; - hasChildren = true; + has_children = true; return *this; } string finish() const { - if (hasChildren) + if (has_children) return str + "\n"; else return str + "/>\n"; } - bool hasChildren; + bool has_children; string str, name; }; diff --git a/include/gui/ContainerWidget.hpp b/include/gui/ContainerWidget.hpp index 77279bb..b3c1fd1 100644 --- a/include/gui/ContainerWidget.hpp +++ b/include/gui/ContainerWidget.hpp @@ -31,24 +31,24 @@ namespace gui { ContainerWidget(const AttributeSet& attrs); virtual void render(RenderContext& rc) const; - virtual void adjustForTheme(const Theme& theme); + virtual void adjust_for_theme(const Theme& theme); - void addChild(Widget* w); + void add_child(Widget* w); - virtual bool handleClick(int x, int y); + virtual bool handle_click(int x, int y); protected: - virtual void childAdded(Widget* w) {}; - int countChildren(); + virtual void child_added(Widget* w) {}; + int count_children(); typedef vector ChildList; ChildList::iterator begin() { return children.begin(); } ChildList::iterator end() { return children.end(); } - ChildList::const_iterator constBegin() const + ChildList::const_iterator const_begin() const { return children.begin(); } - ChildList::const_iterator constEnd() const + ChildList::const_iterator const_end() const { return children.end(); } private: diff --git a/include/gui/IFont.hpp b/include/gui/IFont.hpp index b0fe378..cdc032d 100644 --- a/include/gui/IFont.hpp +++ b/include/gui/IFont.hpp @@ -39,8 +39,8 @@ namespace gui { FONT_NORMAL, FONT_MONO }; - IFontPtr loadFont(const string& file, int h, - FontType type=FONT_NORMAL, bool dropShadow=false); + IFontPtr load_font(const string& file, int h, + FontType type=FONT_NORMAL, bool drop_shadow=false); } diff --git a/include/gui/ILayout.hpp b/include/gui/ILayout.hpp index 40d451c..af51d77 100644 --- a/include/gui/ILayout.hpp +++ b/include/gui/ILayout.hpp @@ -46,8 +46,8 @@ namespace gui { typedef shared_ptr ILayoutPtr; - ILayoutPtr makeLayout(const string& file_name); - string parentPath(const string& path); + ILayoutPtr make_layout(const string& file_name); + string parent_path(const string& path); } diff --git a/include/gui/Label.hpp b/include/gui/Label.hpp index d1de1df..540dc67 100644 --- a/include/gui/Label.hpp +++ b/include/gui/Label.hpp @@ -38,9 +38,9 @@ namespace gui { void format(const char* fmt, ...); void render(RenderContext& rc) const; - void adjustForTheme(const Theme& theme); + void adjust_for_theme(const Theme& theme); private: - string text_, fontName; + string text_, font_name; Colour colour_; bool dirty; }; diff --git a/include/gui/RenderContext.hpp b/include/gui/RenderContext.hpp index 2d63cd7..7d3904a 100644 --- a/include/gui/RenderContext.hpp +++ b/include/gui/RenderContext.hpp @@ -37,8 +37,8 @@ namespace gui { RenderContext(const Theme& theme); ~RenderContext(); - void pushOrigin(const Widget* w); - void popOrigin(); + void push_origin(const Widget* w); + void pop_origin(); void scissor(Widget* w); diff --git a/include/gui/Theme.hpp b/include/gui/Theme.hpp index 10d5855..8ccde6b 100644 --- a/include/gui/Theme.hpp +++ b/include/gui/Theme.hpp @@ -37,10 +37,10 @@ namespace gui { Colour border() const; // Fonts - IFontPtr normalFont() const { return normal_font_; } - IFontPtr font(const string& fontName) const; + IFontPtr normal_font() const { return normal_font_; } + IFontPtr font(const string& font_name) const; - void addFont(const string& name, IFontPtr f); + void add_font(const string& name, IFontPtr f); private: IFontPtr normal_font_; diff --git a/include/gui/ThrottleMeter.hpp b/include/gui/ThrottleMeter.hpp index f110e1f..01add8d 100644 --- a/include/gui/ThrottleMeter.hpp +++ b/include/gui/ThrottleMeter.hpp @@ -35,11 +35,11 @@ namespace gui { void range(int low, int high); void render(RenderContext& rc) const; - void adjustForTheme(const Theme& theme); + void adjust_for_theme(const Theme& theme); private: - int value_, minValue, maxValue; - string fontName; + int value_, min_value, max_value; + string font_name; static const int THROTTLE_MAX = 10; static const int THROTTLE_MIN = 0; diff --git a/include/gui/ToggleBar.hpp b/include/gui/ToggleBar.hpp index f54c0e3..19e6042 100644 --- a/include/gui/ToggleBar.hpp +++ b/include/gui/ToggleBar.hpp @@ -29,12 +29,12 @@ namespace gui { ToggleBar(const AttributeSet& attrs); void render(RenderContext& rc) const; - bool handleClick(int x, int y); + bool handle_click(int x, int y); private: - void childAdded(Widget* w); + void child_added(Widget* w); int nextX; - int buttonWidth, buttonHeight; + int button_width, button_height; }; } diff --git a/include/gui/ToggleButton.hpp b/include/gui/ToggleButton.hpp index 4a3b450..dd1b3a2 100644 --- a/include/gui/ToggleButton.hpp +++ b/include/gui/ToggleButton.hpp @@ -30,7 +30,7 @@ namespace gui { ToggleButton(const AttributeSet& attrs); void render(RenderContext& rc) const; - bool handleClick(int x, int y); + bool handle_click(int x, int y); void on(); void off(); diff --git a/include/gui/Widget.hpp b/include/gui/Widget.hpp index 9b62efc..19a62de 100644 --- a/include/gui/Widget.hpp +++ b/include/gui/Widget.hpp @@ -57,17 +57,17 @@ namespace gui { void connect(Signal sig, SignalHandler handler); virtual void render(RenderContext& rc) const = 0; - virtual void adjustForTheme(const Theme& theme) {} + virtual void adjust_for_theme(const Theme& theme) {} - virtual bool handleClick(int x, int y); + virtual bool handle_click(int x, int y); - void dumpLocation() const; + void dump_location() const; protected: void raise(Signal sig); private: - static string uniqueName(); + static string unique_name(); string name_; int x_, y_, width_, height_; @@ -76,7 +76,7 @@ namespace gui { map handlers; - static int ourUniqueId; + static int our_unique_id; }; } diff --git a/include/gui/Window.hpp b/include/gui/Window.hpp index f9d112c..96bd1af 100644 --- a/include/gui/Window.hpp +++ b/include/gui/Window.hpp @@ -36,10 +36,10 @@ namespace gui { void title(const string& t) { title_ = t; } void render(RenderContext& rc) const; - void adjustForTheme(const Theme& theme); + void adjust_for_theme(const Theme& theme); private: string title_; - bool dynamicWidth, dynamicHeight; + bool dynamic_width, dynamic_height; }; } diff --git a/src/Billboard.cpp b/src/Billboard.cpp index 0f38076..60e62d5 100644 --- a/src/Billboard.cpp +++ b/src/Billboard.cpp @@ -28,37 +28,37 @@ using namespace std; namespace { - Vector cameraPosition; + Vector camera_position; } // Common functions used by billboards class BillboardCommon : public IBillboard { public: - BillboardCommon(ITexturePtr aTexture) - : texture(aTexture), - position(makeVector(0.0f, 0.0f, 0.0f)), + BillboardCommon(ITexturePtr a_texture) + : texture(a_texture), + position(make_vector(0.0f, 0.0f, 0.0f)), scale(1.0f), - colour(makeColour(1.0f, 1.0f, 1.0f)) {} + colour(make_colour(1.0f, 1.0f, 1.0f)) {} virtual ~BillboardCommon() {} // IBillboard interface - void setPosition(float x, float y, float z); - void setScale(float aScale); - void setColour(float r, float g, float b, float a); + void set_position(float x, float y, float z); + void set_scale(float a_scale); + void set_colour(float r, float g, float b, float a); void render() const; - static void renderSaved(); + static void render_saved(); private: const ITexturePtr texture; protected: - void drawTextureQuad() const; + void draw_texture_quad() const; void translate() const; - void saveMe() const; + void save_me() const; - virtual void realRender() const = 0; + virtual void real_render() const = 0; Vector position; float scale; @@ -68,55 +68,55 @@ protected: bool operator()(const BillboardCommon* lhs, const BillboardCommon* rhs) { - return distanceToCamera(lhs->position) - > distanceToCamera(rhs->position); + return distance_to_camera(lhs->position) + > distance_to_camera(rhs->position); } }; // List of billboards to draw at end of this frame - static vector toDraw; + static vector to_draw; }; -vector BillboardCommon::toDraw; +vector BillboardCommon::to_draw; -void BillboardCommon::renderSaved() +void BillboardCommon::render_saved() { using namespace placeholders; // Depth sort the saved billboards and render them - sort(toDraw.begin(), toDraw.end(), CmpDistanceToCam()); + sort(to_draw.begin(), to_draw.end(), CmpDistanceToCam()); - for_each(toDraw.begin(), toDraw.end(), - bind(&BillboardCommon::realRender, placeholders::_1)); + for_each(to_draw.begin(), to_draw.end(), + bind(&BillboardCommon::real_render, placeholders::_1)); - toDraw.clear(); + to_draw.clear(); } -void BillboardCommon::saveMe() const +void BillboardCommon::save_me() const { // Remember to draw this billboard at the end of the frame - toDraw.push_back(this); + to_draw.push_back(this); } void BillboardCommon::render() const { - saveMe(); + save_me(); } -void BillboardCommon::setPosition(float x, float y, float z) +void BillboardCommon::set_position(float x, float y, float z) { - position = makeVector(x, y, z); + position = make_vector(x, y, z); } -void BillboardCommon::setColour(float r, float g, float b, float a) +void BillboardCommon::set_colour(float r, float g, float b, float a) { - colour = makeColour(r, g, b, a); + colour = make_colour(r, g, b, a); } -void BillboardCommon::setScale(float aScale) +void BillboardCommon::set_scale(float a_scale) { - scale = aScale; + scale = a_scale; } void BillboardCommon::translate() const @@ -125,7 +125,7 @@ void BillboardCommon::translate() const } // Draw the actual quad containing the texture -void BillboardCommon::drawTextureQuad() const +void BillboardCommon::draw_texture_quad() const { glPushAttrib(GL_ENABLE_BIT); @@ -140,14 +140,16 @@ void BillboardCommon::drawTextureQuad() const const float w = scale / 2.0f; glBegin(GL_QUADS); - glTexCoord2f(1.0f, 0.0f); - glVertex2f(w, w); - glTexCoord2f(0.0f, 0.0f); - glVertex2f(-w, w); - glTexCoord2f(0.0f, 1.0f); - glVertex2f(-w, -w); - glTexCoord2f(1.0f, 1.0f); - glVertex2f(w, -w); + { + glTexCoord2f(1.0f, 0.0f); + glVertex2f(w, w); + glTexCoord2f(0.0f, 0.0f); + glVertex2f(-w, w); + glTexCoord2f(0.0f, 1.0f); + glVertex2f(-w, -w); + glTexCoord2f(1.0f, 1.0f); + glVertex2f(w, -w); + } glEnd(); glPopAttrib(); @@ -157,18 +159,18 @@ void BillboardCommon::drawTextureQuad() const // but not xz class CylindricalBillboard : public BillboardCommon { public: - CylindricalBillboard(ITexturePtr aTexture) - : BillboardCommon(aTexture) {} + CylindricalBillboard(ITexturePtr a_texture) + : BillboardCommon(a_texture) {} - void realRender() const; + void real_render() const; }; -void CylindricalBillboard::realRender() const +void CylindricalBillboard::real_render() const { // Based on code from - // http://www.lighthouse3d.com/opengl/billboarding/index.php?billCyl - Vector lookAt, objToCamProj, upAux, objToCam; - float angleCosine; + // http://www.lighthouse3d.com/opengl/billboarding/index.php?bill_cyl + Vector look_at, obj_to_camProj, up_aux, obj_to_cam; + float angle_cosine; glPushAttrib(GL_DEPTH_BUFFER_BIT); glDepthMask(GL_FALSE); @@ -177,36 +179,36 @@ void CylindricalBillboard::realRender() const translate(); - // objToCamProj is the vector in world coordinates from the + // obj_to_camProj is the vector in world coordinates from the // local origin to the camera projected in the XZ plane - objToCamProj = makeVector( - cameraPosition.x - position.x, + obj_to_camProj = make_vector( + camera_position.x - position.x, 0.0f, - cameraPosition.z - position.z); + camera_position.z - position.z); - // This is the original lookAt vector for the object + // This is the original look_at vector for the object // in world coordinates - lookAt = makeVector(0.0f, 0.0f, 1.0f); + look_at = make_vector(0.0f, 0.0f, 1.0f); // normalize both vectors to get the cosine directly afterwards - objToCamProj.normalise(); + obj_to_camProj.normalise(); // easy fix to determine wether the angle is negative or positive - // for positive angles upAux will be a vector pointing in the - // positive y direction, otherwise upAux will point downwards + // for positive angles up_aux will be a vector pointing in the + // positive y direction, otherwise up_aux will point downwards // effectively reversing the rotation. - upAux = lookAt * objToCamProj; + up_aux = look_at * obj_to_camProj; // compute the angle - angleCosine = lookAt.dot(objToCamProj); + angle_cosine = look_at.dot(obj_to_camProj); // perform the rotation. The if statement is used for stability reasons - // if the lookAt and objToCamProj vectors are too close together then - // |angleCosine| could be bigger than 1 due to lack of precision - //if ((angleCosine < 0.999999f) && (angleCosine > -0.999999f)) - glRotatef(acos(angleCosine)*180.0f/M_PI, upAux.x, upAux.y, upAux.z); + // if the look_at and obj_to_camProj vectors are too close together then + // |angle_cosine| could be bigger than 1 due to lack of precision + //if ((angle_cosine < 0.999999f) && (angle_cosine > -0.999999f)) + glRotatef(acos(angle_cosine)*180.0f/M_PI, up_aux.x, up_aux.y, up_aux.z); - drawTextureQuad(); + draw_texture_quad(); glPopMatrix(); glPopAttrib(); @@ -215,18 +217,18 @@ void CylindricalBillboard::realRender() const // A billboard which always faces the viewer class SphericalBillboard : public BillboardCommon { public: - SphericalBillboard(ITexturePtr aTexture) - : BillboardCommon(aTexture) {} + SphericalBillboard(ITexturePtr a_texture) + : BillboardCommon(a_texture) {} - void realRender() const; + void real_render() const; }; -void SphericalBillboard::realRender() const +void SphericalBillboard::real_render() const { // Based on code from - // http://www.lighthouse3d.com/opengl/billboarding/index.php?billSphe - Vector lookAt, objToCamProj, upAux, objToCam; - float angleCosine; + // http://www.lighthouse3d.com/opengl/billboarding/index.php?bill_sphe + Vector look_at, obj_to_camProj, up_aux, obj_to_cam; + float angle_cosine; glPushAttrib(GL_DEPTH_BUFFER_BIT); glDepthMask(GL_FALSE); @@ -235,88 +237,88 @@ void SphericalBillboard::realRender() const translate(); - // objToCamProj is the vector in world coordinates from the + // obj_to_camProj is the vector in world coordinates from the // local origin to the camera projected in the XZ plane - objToCamProj = makeVector(cameraPosition.x - position.x, + obj_to_camProj = make_vector(camera_position.x - position.x, 0.0f, - cameraPosition.z - position.z); + camera_position.z - position.z); - // This is the original lookAt vector for the object + // This is the original look_at vector for the object // in world coordinates - lookAt = makeVector(0.0f, 0.0f, 1.0f); + look_at = make_vector(0.0f, 0.0f, 1.0f); // normalize both vectors to get the cosine directly afterwards - objToCamProj.normalise(); + obj_to_camProj.normalise(); // easy fix to determine wether the angle is negative or positive - // for positive angles upAux will be a vector pointing in the - // positive y direction, otherwise upAux will point downwards + // for positive angles up_aux will be a vector pointing in the + // positive y direction, otherwise up_aux will point downwards // effectively reversing the rotation. - upAux = lookAt * objToCamProj; + up_aux = look_at * obj_to_camProj; // compute the angle - angleCosine = lookAt.dot(objToCamProj); + angle_cosine = look_at.dot(obj_to_camProj); // perform the rotation. The if statement is used for stability reasons - // if the lookAt and objToCamProj vectors are too close together then - // |angleCosine| could be bigger than 1 due to lack of precision - glRotatef(acos(angleCosine)*180.0f/M_PI, upAux.x, upAux.y, upAux.z); + // if the look_at and obj_to_camProj vectors are too close together then + // |angle_cosine| could be bigger than 1 due to lack of precision + glRotatef(acos(angle_cosine)*180.0f/M_PI, up_aux.x, up_aux.y, up_aux.z); // so far it is just like the cylindrical billboard. The code for the // second rotation comes now // The second part tilts the object so that it faces the camera - // objToCam is the vector in world coordinates from + // obj_to_cam is the vector in world coordinates from // the local origin to the camera - objToCam = cameraPosition - position; + obj_to_cam = camera_position - position; // Normalize to get the cosine afterwards - objToCam.normalise(); + obj_to_cam.normalise(); - // Compute the angle between objToCamProj and objToCam, + // Compute the angle between obj_to_camProj and obj_to_cam, //i.e. compute the required angle for the lookup vector - angleCosine = objToCamProj.dot(objToCam); + angle_cosine = obj_to_camProj.dot(obj_to_cam); // Tilt the object. The test is done to prevent instability - // when objToCam and objToCamProj have a very small + // when obj_to_cam and obj_to_camProj have a very small // angle between them - if ((angleCosine < 0.99990) && (angleCosine > -0.9999)) { - if (objToCam.y < 0) - glRotatef(acos(angleCosine)*180/M_PI,1,0,0); + if ((angle_cosine < 0.99990) && (angle_cosine > -0.9999)) { + if (obj_to_cam.y < 0) + glRotatef(acos(angle_cosine)*180/M_PI,1,0,0); else - glRotatef(acos(angleCosine)*180/M_PI,-1,0,0); + glRotatef(acos(angle_cosine)*180/M_PI,-1,0,0); } - drawTextureQuad(); + draw_texture_quad(); glPopMatrix(); glPopAttrib(); } -IBillboardPtr makeCylindricalBillboard(ITexturePtr aTexture) +IBillboardPtr make_cylindrical_billboard(ITexturePtr a_texture) { - return IBillboardPtr(new CylindricalBillboard(aTexture)); + return IBillboardPtr(new CylindricalBillboard(a_texture)); } -IBillboardPtr makeSphericalBillboard(ITexturePtr aTexture) +IBillboardPtr make_spherical_billboard(ITexturePtr a_texture) { - return IBillboardPtr(new SphericalBillboard(aTexture)); + return IBillboardPtr(new SphericalBillboard(a_texture)); } -void setBillboardCameraOrigin(Vector aPosition) +void set_billboard_cameraOrigin(Vector a_position) { - cameraPosition = aPosition; + camera_position = a_position; } -float distanceToCamera(Vector aPosition) +float distance_to_camera(Vector a_position) { - return (cameraPosition - aPosition).length(); + return (camera_position - a_position).length(); } -void renderBillboards() +void render_billboards() { - BillboardCommon::renderSaved(); + BillboardCommon::render_saved(); } diff --git a/src/Building.cpp b/src/Building.cpp index cf233fe..042b0b2 100644 --- a/src/Building.cpp +++ b/src/Building.cpp @@ -27,20 +27,20 @@ // Concrete implementation of buildings class Building : public IScenery, public IXMLCallback { public: - Building(IResourcePtr aRes); + Building(IResourcePtr a_res); // ISceneryInterface const string& name() const { return name_; } void render() const; - void setAngle(float a) { angle = a; } - void setPosition(float x, float y, float z); + void set_angle(float a) { angle = a; } + void set_position(float x, float y, float z); void merge(IMeshBufferPtr buf); // IXMLSerialisable interface - xml::element toXml() const; + xml::element to_xml() const; // IXMLCallback interface - void text(const string& localName, const string& aString); + void text(const string& local_name, const string& a_string); private: IModelPtr model_; @@ -50,29 +50,29 @@ private: Vector position; struct ParserState { - string modelFile; + string model_file; float scale; - } *parserState; + } *parser_state; }; -Building::Building(IResourcePtr aRes) - : name_("???"), resource(aRes), angle(0.0f) +Building::Building(IResourcePtr a_res) + : name_("???"), resource(a_res), angle(0.0f) { static IXMLParserPtr parser = makeXMLParser("schemas/building.xsd"); - parserState = new ParserState; - parserState->scale = 1.0f; + parser_state = new ParserState; + parser_state->scale = 1.0f; - parser->parse(aRes->xmlFileName(), *this); + parser->parse(a_res->xml_file_name(), *this); - model_ = loadModel(aRes, parserState->modelFile, parserState->scale); + model_ = load_model(a_res, parser_state->model_file, parser_state->scale); - delete parserState; + delete parser_state; } -void Building::setPosition(float x, float y, float z) +void Building::set_position(float x, float y, float z) { - position = makeVector(x, y, z); + position = make_vector(x, y, z); } void Building::render() const @@ -91,48 +91,48 @@ void Building::merge(IMeshBufferPtr buf) model_->merge(buf, position, angle); } -void Building::text(const string& localName, const string& aString) +void Building::text(const string& local_name, const string& a_string) { - if (localName == "name") - name_ = aString; - else if (localName == "scale") - parserState->scale = boost::lexical_cast(aString); - else if (localName == "model") - parserState->modelFile = aString; + if (local_name == "name") + name_ = a_string; + else if (local_name == "scale") + parser_state->scale = boost::lexical_cast(a_string); + else if (local_name == "model") + parser_state->model_file = a_string; } -xml::element Building::toXml() const +xml::element Building::to_xml() const { return xml::element("building") - .addAttribute("angle", static_cast(angle)) - .addAttribute("name", resource->name()); + .add_attribute("angle", static_cast(angle)) + .add_attribute("name", resource->name()); } namespace { - Building* loadBuildingXml(IResourcePtr aRes) + Building* load_building_xml(IResourcePtr a_res) { - log() << "Loading building from " << aRes->xmlFileName(); + log() << "Loading building from " << a_res->xml_file_name(); - return new Building(aRes); + return new Building(a_res); } } -ISceneryPtr loadBuilding(const string& aResId, float angle) +ISceneryPtr load_building(const string& a_res_id, float angle) { - static ResourceCache cache(loadBuildingXml, "buildings"); + static ResourceCache cache(load_building_xml, "buildings"); - shared_ptr bld = cache.loadCopy(aResId); - bld->setAngle(angle); + shared_ptr bld = cache.load_copy(a_res_id); + bld->set_angle(angle); return ISceneryPtr(bld); } -ISceneryPtr loadBuilding(const AttributeSet& attrs) +ISceneryPtr load_building(const AttributeSet& attrs) { float angle; string name; attrs.get("name", name); attrs.get("angle", angle); - return loadBuilding(name, angle); + return load_building(name, angle); } diff --git a/src/Config.cpp b/src/Config.cpp index c122f79..c99d2f8 100644 --- a/src/Config.cpp +++ b/src/Config.cpp @@ -48,56 +48,56 @@ public: ~Config(); // IConfig interface - const IConfig::Option& get(const string& aKey) const; - void set(const string& aKey, const IConfig::Option& aValue); + const IConfig::Option& get(const string& a_key) const; + void set(const string& a_key, const IConfig::Option& a_value); void flush(); // IXMLCallback interface - void startElement(const string& localName, const AttributeSet& attrs); - void text(const string& localName, const string& aString); + void start_element(const string& local_name, const AttributeSet& attrs); + void text(const string& local_name, const string& a_string); private: - static string configFileName(); + static string config_file_name(); template - void setFromString(const string& aKey, const string& aString); + void set_from_string(const string& a_key, const string& a_string); template - void bindNextOption(const AttributeSet& attrs); + void bind_next_option(const AttributeSet& attrs); typedef map ConfigMap; - ConfigMap configMap; + ConfigMap config_map; - string configFile; - bool amDirty; + string config_file; + bool am_dirty; // Used by the XML parser - string myActiveOption; + string my_active_option; }; // Read the config file from disk Config::Config() - : amDirty(false) + : am_dirty(false) { for (size_t i = 0; i < sizeof(::defaults)/sizeof(Default); i++) - configMap[::get<0>(::defaults[i])] = ::get<1>(::defaults[i]); + config_map[::get<0>(::defaults[i])] = ::get<1>(::defaults[i]); - configFile = configFileName(); + config_file = config_file_name(); - if (boost::filesystem::exists(configFile)) { - log() << "Reading config from " << configFile; + if (boost::filesystem::exists(config_file)) { + log() << "Reading config from " << config_file; IXMLParserPtr parser = makeXMLParser("schemas/config.xsd"); - parser->parse(configFile, *this); + parser->parse(config_file, *this); // Ignore all the set() calls made by the XML parser - amDirty = false; + am_dirty = false; } else { - warn() << "Config file not present: " << configFile; + warn() << "Config file not present: " << config_file; // Write a default config file when we exit - amDirty = true; + am_dirty = true; } } @@ -107,7 +107,7 @@ Config::~Config() } // Find the config file location on this platform -string Config::configFileName() +string Config::config_file_name() { #ifdef WIN32 throw runtime_error("TODO: find config dir on Win32"); @@ -139,28 +139,28 @@ string Config::configFileName() #endif // #ifdef WIN32 } -void Config::startElement(const string& localName, const AttributeSet& attrs) +void Config::start_element(const string& local_name, const AttributeSet& attrs) { - if (localName == "option") - attrs.get("name", myActiveOption); + if (local_name == "option") + attrs.get("name", my_active_option); } -void Config::text(const string& localName, const string& aString) +void Config::text(const string& local_name, const string& a_string) { - if (localName == "string") - setFromString(myActiveOption, aString); - else if (localName == "int") - setFromString(myActiveOption, aString); - else if (localName == "bool") - setFromString(myActiveOption, aString); - else if (localName == "float") - setFromString(myActiveOption, aString); + if (local_name == "string") + set_from_string(my_active_option, a_string); + else if (local_name == "int") + set_from_string(my_active_option, a_string); + else if (local_name == "bool") + set_from_string(my_active_option, a_string); + else if (local_name == "float") + set_from_string(my_active_option, a_string); } template -void Config::setFromString(const string& aKey, const string& aString) +void Config::set_from_string(const string& a_key, const string& a_string) { - configMap[aKey] = boost::lexical_cast(aString); + config_map[a_key] = boost::lexical_cast(a_string); } // Write the config file back to disk @@ -169,39 +169,39 @@ void Config::flush() using namespace boost::filesystem; using namespace boost; - if (!amDirty) + if (!am_dirty) return; - log() << "Saving config to " << configFile; + log() << "Saving config to " << config_file; - create_directories(path(configFile).remove_filename()); + create_directories(path(config_file).remove_filename()); - ofstream ofs(configFile.c_str()); + ofstream ofs(config_file.c_str()); if (!ofs.good()) throw runtime_error("Failed to write to config file"); xml::element root("config"); - for (ConfigMap::const_iterator it = configMap.begin(); - it != configMap.end(); ++it) { + for (ConfigMap::const_iterator it = config_map.begin(); + it != config_map.end(); ++it) { // We can only serialize some types const any& a = (*it).second; const type_info& t = a.type(); - string text, typeName; + string text, type_name; if (t == typeid(string)) { - typeName = "string"; + type_name = "string"; text = any_cast(a); } else if (t == typeid(int)) { - typeName = "int"; + type_name = "int"; text = lexical_cast(any_cast(a)); } else if (t == typeid(float)) { - typeName = "float"; + type_name = "float"; text = lexical_cast(any_cast(a)); } else if (t == typeid(bool)) { - typeName = "bool"; + type_name = "bool"; text = lexical_cast(any_cast(a)); } else @@ -210,38 +210,38 @@ void Config::flush() + boost::lexical_cast(t.name())); xml::element option("option"); - option.addAttribute("name", (*it).first); + option.add_attribute("name", (*it).first); - xml::element type(typeName); - type.addText(text); - option.addChild(type); + xml::element type(type_name); + type.add_text(text); + option.add_child(type); - root.addChild(option); + root.add_child(option); } ofs << xml::document(root); - amDirty = false; + am_dirty = false; } // Read a single option -const IConfig::Option& Config::get(const string& aKey) const +const IConfig::Option& Config::get(const string& a_key) const { - ConfigMap::const_iterator it = configMap.find(aKey); - if (it != configMap.end()) + ConfigMap::const_iterator it = config_map.find(a_key); + if (it != config_map.end()) return (*it).second; else - throw runtime_error("Bad config key " + aKey); + throw runtime_error("Bad config key " + a_key); } -void Config::set(const string& aKey, const IConfig::Option& aValue) +void Config::set(const string& a_key, const IConfig::Option& a_value) { - configMap[aKey] = aValue; - amDirty = true; + config_map[a_key] = a_value; + am_dirty = true; } // Return the single config file instance -IConfigPtr getConfig() +IConfigPtr get_config() { static IConfigPtr cfg(new Config); diff --git a/src/CrossoverTrack.cpp b/src/CrossoverTrack.cpp index ff0464b..6cd71f9 100644 --- a/src/CrossoverTrack.cpp +++ b/src/CrossoverTrack.cpp @@ -38,29 +38,29 @@ public: CrossoverTrack() : myX(0), myY(0), height(0.0f) {} ~CrossoverTrack() {} - void setOrigin(int x, int y, float h); + void set_origin(int x, int y, float h); void render() const {} void merge(IMeshBufferPtr buf) const; - float segmentLength(const track::TravelToken& aToken) const; - bool isValidDirection(const track::Direction& aDirection) const; - track::Connection nextPosition(const track::TravelToken& aToken) const; - void getEndpoints(vector >& aList) const; - void getCovers(vector >& output) const { } - ITrackSegmentPtr mergeExit(Point where, track::Direction dir); - track::TravelToken getTravelToken(track::Position aPosition, - track::Direction aDirection) const; - void nextState() {} - void prevState() {} - bool hasMultipleStates() const { return false; } - void setStateRenderHint() {} + float segment_length(const track::TravelToken& a_token) const; + bool is_valid_direction(const track::Direction& a_direction) const; + track::Connection next_position(const track::TravelToken& a_token) const; + void get_endpoints(vector >& a_list) const; + void get_covers(vector >& output) const { } + ITrackSegmentPtr merge_exit(Point where, track::Direction dir); + track::TravelToken get_travel_token(track::Position a_position, + track::Direction a_direction) const; + void next_state() {} + void prev_state() {} + bool has_multiple_states() const { return false; } + void set_state_renderHint() {} // IXMLSerialisable interface - xml::element toXml() const; + xml::element to_xml() const; private: - void transform(const track::TravelToken& aToken, float delta) const; + void transform(const track::TravelToken& a_token, float delta) const; int myX, myY; float height; @@ -70,88 +70,88 @@ void CrossoverTrack::merge(IMeshBufferPtr buf) const { // Render the y-going rails and sleepers { - Vector off = makeVector( + Vector off = make_vector( static_cast(myX), height, static_cast(myY)); - mergeStraightRail(buf, off, 0.0f); + merge_straight_rail(buf, off, 0.0f); - off += makeVector(0.0f, 0.0f, -0.4f); + off += make_vector(0.0f, 0.0f, -0.4f); for (int i = 0; i < 4; i++) { - mergeSleeper(buf, off, 90.0f); - off += makeVector(0.0f, 0.0f, 0.25f); + merge_sleeper(buf, off, 90.0f); + off += make_vector(0.0f, 0.0f, 0.25f); } } // Render the x-going rails and sleepers { - Vector off = makeVector( + Vector off = make_vector( static_cast(myX), height, static_cast(myY)); - mergeStraightRail(buf, off, 90.0f); + merge_straight_rail(buf, off, 90.0f); - off += makeVector(-0.4f, 0.0f, 0.0f); + off += make_vector(-0.4f, 0.0f, 0.0f); for (int i = 0; i < 4; i++) { - mergeSleeper(buf, off, 0.0f); - off += makeVector(0.25f, 0.0f, 0.0f); + merge_sleeper(buf, off, 0.0f); + off += make_vector(0.25f, 0.0f, 0.0f); } } } -void CrossoverTrack::setOrigin(int x, int y, float h ) +void CrossoverTrack::set_origin(int x, int y, float h ) { myX = x; myY = y; height = h; } -float CrossoverTrack::segmentLength(const track::TravelToken& aToken) const +float CrossoverTrack::segment_length(const track::TravelToken& a_token) const { return 1.0f; } track::TravelToken -CrossoverTrack::getTravelToken(track::Position aPosition, - track::Direction aDirection) const +CrossoverTrack::get_travel_token(track::Position a_position, + track::Direction a_direction) const { - if (!isValidDirection(aDirection)) + if (!is_valid_direction(a_direction)) throw runtime_error - ("Invalid direction on crossover: " + lexical_cast(aDirection)); + ("Invalid direction on crossover: " + lexical_cast(a_direction)); track::TravelToken tok = { - aDirection, - aPosition, + a_direction, + a_position, bind(&CrossoverTrack::transform, this, _1, _2), - track::flatGradientFunc, + track::flat_gradient_func, 1 }; return tok; } -void CrossoverTrack::transform(const track::TravelToken& aToken, +void CrossoverTrack::transform(const track::TravelToken& a_token, float delta) const { assert(delta < 1.0); - bool backwards = aToken.direction== -axis::X || aToken.direction == -axis::Y; + bool backwards = a_token.direction== -axis::X || a_token.direction == -axis::Y; if (backwards) { delta = 1.0f - delta; } - track::Direction dir = backwards ? -aToken.direction : aToken.direction; + track::Direction dir = backwards ? -a_token.direction : a_token.direction; - const double xTrans = dir == axis::X ? delta : 0; - const double yTrans = dir == axis::Y ? delta : 0; + const double x_trans = dir == axis::X ? delta : 0; + const double y_trans = dir == axis::Y ? delta : 0; - glTranslated(static_cast(myX) + xTrans, + glTranslated(static_cast(myX) + x_trans, height, - static_cast(myY) + yTrans); + static_cast(myY) + y_trans); if (dir == axis::Y) glRotated(-90.0, 0.0, 1.0, 0.0); @@ -162,50 +162,50 @@ void CrossoverTrack::transform(const track::TravelToken& aToken, glRotated(-180.0, 0.0, 1.0, 0.0); } -bool CrossoverTrack::isValidDirection(const track::Direction& aDirection) const +bool CrossoverTrack::is_valid_direction(const track::Direction& a_direction) const { - return aDirection == axis::X || aDirection == axis::Y - || aDirection == -axis::Y || aDirection == -axis::X; + return a_direction == axis::X || a_direction == axis::Y + || a_direction == -axis::Y || a_direction == -axis::X; } track::Connection -CrossoverTrack::nextPosition(const track::TravelToken& aToken) const +CrossoverTrack::next_position(const track::TravelToken& a_token) const { - if (aToken.direction == axis::X) - return make_pair(makePoint(myX + 1, myY), axis::X); - else if (aToken.direction == -axis::X) - return make_pair(makePoint(myX - 1, myY), -axis::X); - else if (aToken.direction == axis::Y) - return make_pair(makePoint(myX, myY + 1), axis::Y); - else if (aToken.direction == -axis::Y) - return make_pair(makePoint(myX, myY - 1), -axis::Y); + if (a_token.direction == axis::X) + return make_pair(make_point(myX + 1, myY), axis::X); + else if (a_token.direction == -axis::X) + return make_pair(make_point(myX - 1, myY), -axis::X); + else if (a_token.direction == axis::Y) + return make_pair(make_point(myX, myY + 1), axis::Y); + else if (a_token.direction == -axis::Y) + return make_pair(make_point(myX, myY - 1), -axis::Y); else throw runtime_error - ("Invalid direction on crossover: " + lexical_cast(aToken.direction)); + ("Invalid direction on crossover: " + lexical_cast(a_token.direction)); } -void CrossoverTrack::getEndpoints(vector >& aList) const +void CrossoverTrack::get_endpoints(vector >& a_list) const { - aList.push_back(makePoint(myX, myY)); + a_list.push_back(make_point(myX, myY)); } -ITrackSegmentPtr CrossoverTrack::mergeExit(Point where, +ITrackSegmentPtr CrossoverTrack::merge_exit(Point where, track::Direction dir) { - if (where == makePoint(myX, myY) - && isValidDirection(dir)) + if (where == make_point(myX, myY) + && is_valid_direction(dir)) return shared_from_this(); // No way to extend a crossover return ITrackSegmentPtr(); } -xml::element CrossoverTrack::toXml() const +xml::element CrossoverTrack::to_xml() const { - return xml::element("crossoverTrack"); + return xml::element("crossover_track"); } -ITrackSegmentPtr makeCrossoverTrack() +ITrackSegmentPtr make_crossover_track() { return ITrackSegmentPtr(new CrossoverTrack); } diff --git a/src/CurvedTrack.cpp b/src/CurvedTrack.cpp index a24e9e3..f0196e7 100644 --- a/src/CurvedTrack.cpp +++ b/src/CurvedTrack.cpp @@ -37,50 +37,50 @@ class CurvedTrack : public ITrackSegment, public enable_shared_from_this, private CurvedTrackHelper { public: - CurvedTrack(track::Angle aStartAngle, track::Angle aFinishAngle, - int aRadius); + CurvedTrack(track::Angle a_start_angle, track::Angle a_finish_angle, + int a_radius); ~CurvedTrack(); void render() const {} void merge(IMeshBufferPtr buf) const; - void setOrigin(int x, int y, float h); - float segmentLength(const track::TravelToken& aToken) const; + void set_origin(int x, int y, float h); + float segment_length(const track::TravelToken& a_token) const; - Connection nextPosition(const track::TravelToken& aToken) const; - bool isValidDirection(const Direction& aDirection) const; - void getEndpoints(vector >& aList) const; - void getCovers(vector >& output) const; + Connection next_position(const track::TravelToken& a_token) const; + bool is_valid_direction(const Direction& a_direction) const; + void get_endpoints(vector >& a_list) const; + void get_covers(vector >& output) const; - ITrackSegmentPtr mergeExit(Point where, track::Direction dir); + ITrackSegmentPtr merge_exit(Point where, track::Direction dir); - xml::element toXml() const; - track::TravelToken getTravelToken(track::Position aPosition, - track::Direction aDirection) const; + xml::element to_xml() const; + track::TravelToken get_travel_token(track::Position a_position, + track::Direction a_direction) const; - bool hasMultipleStates() const { return false; } - void nextState() {} - void prevState() {} - void setStateRenderHint() {} + bool has_multiple_states() const { return false; } + void next_state() {} + void prev_state() {} + void set_state_renderHint() {} private: - void transform(const track::TravelToken& aToken, float delta) const; - void glTransformToOrigin() const; - Vector cwEntryVector() const; - Vector ccwEntryVector() const; - void ensureValidDirection(const Direction& aDirection) const; + void transform(const track::TravelToken& a_token, float delta) const; + void glTransform_toOrigin() const; + Vector cw_entry_vector() const; + Vector ccw_entry_vector() const; + void ensure_valid_direction(const Direction& a_direction) const; Point origin; - int baseRadius; - track::Angle startAngle, finishAngle; + int base_radius; + track::Angle start_angle, finish_angle; float height; }; -CurvedTrack::CurvedTrack(track::Angle aStartAngle, - track::Angle aFinishAngle, - int aRadius) - : origin(makePoint(0, 0)), baseRadius(aRadius), - startAngle(aStartAngle), finishAngle(aFinishAngle), +CurvedTrack::CurvedTrack(track::Angle a_start_angle, + track::Angle a_finish_angle, + int a_radius) + : origin(make_point(0, 0)), base_radius(a_radius), + start_angle(a_start_angle), finish_angle(a_finish_angle), height(0.0f) { @@ -91,72 +91,72 @@ CurvedTrack::~CurvedTrack() } -void CurvedTrack::setOrigin(int x, int y, float h) +void CurvedTrack::set_origin(int x, int y, float h) { - origin = makePoint(x, y); + origin = make_point(x, y); height = h; } track::TravelToken -CurvedTrack::getTravelToken(track::Position aPosition, - track::Direction aDirection) const +CurvedTrack::get_travel_token(track::Position a_position, + track::Direction a_direction) const { - ensureValidDirection(aDirection); + ensure_valid_direction(a_direction); track::TravelToken tok = { - aDirection, - aPosition, + a_direction, + a_position, bind(&CurvedTrack::transform, this, _1, _2), - track::flatGradientFunc, + track::flat_gradient_func, 1 }; return tok; } -void CurvedTrack::glTransformToOrigin() const +void CurvedTrack::glTransform_toOrigin() const { - glTranslatef((baseRadius-1)*-sin(degToRad(startAngle)) - 0.5f, 0.0f, - (baseRadius-1)*-cos(degToRad(startAngle)) - 0.5f); + glTranslatef((base_radius-1)*-sin(deg_to_rad(start_angle)) - 0.5f, 0.0f, + (base_radius-1)*-cos(deg_to_rad(start_angle)) - 0.5f); // There *must* be a way to incorporate this in the above translation // as a neat formula, but I really can't think of it // This is a complete a hack, but whatever... - if (startAngle >= 90 && startAngle <= 180) + if (start_angle >= 90 && start_angle <= 180) glTranslatef(0.0f, 0.0f, 1.0f); - if (startAngle >= 180 && startAngle <= 270) + if (start_angle >= 180 && start_angle <= 270) glTranslatef(1.0f, 0.0f, 0.0f); } -void CurvedTrack::transform(const track::TravelToken& aToken, float delta) const +void CurvedTrack::transform(const track::TravelToken& a_token, float delta) const { - assert(delta < segmentLength(aToken)); + assert(delta < segment_length(a_token)); glTranslated(static_cast(origin.x), height, static_cast(origin.y)); - glTransformToOrigin(); + glTransform_toOrigin(); - bool backwards = aToken.direction == cwEntryVector(); + bool backwards = a_token.direction == cw_entry_vector(); - double ratio = delta / segmentLength(aToken); + double ratio = delta / segment_length(a_token); if (backwards) ratio = 1.0 - ratio; - double angle = startAngle + (90.0 * ratio); + double angle = start_angle + (90.0 * ratio); glRotated(angle, 0.0, 1.0, 0.0); - glTranslated(0.0, 0.0, static_cast(baseRadius - 0.5)); + glTranslated(0.0, 0.0, static_cast(base_radius - 0.5)); if (backwards) glRotatef(180.0, 0, 1, 0); } -float CurvedTrack::segmentLength(const track::TravelToken& aToken) const +float CurvedTrack::segment_length(const track::TravelToken& a_token) const { // Assume curve is only through 90 degrees - return M_PI * (static_cast(baseRadius) - 0.5f) / 2.0f; + return M_PI * (static_cast(base_radius) - 0.5f) / 2.0f; } // @@ -179,118 +179,118 @@ float CurvedTrack::segmentLength(const track::TravelToken& aToken) const // // The vector the train is moving on if it enters clockwise -Vector CurvedTrack::cwEntryVector() const +Vector CurvedTrack::cw_entry_vector() const { - return makeVector(-cos(degToRad(finishAngle)), 0, - sin(degToRad(finishAngle))); + return make_vector(-cos(deg_to_rad(finish_angle)), 0, + sin(deg_to_rad(finish_angle))); } // The vector the train is moving on if it enters counter-clockwise -Vector CurvedTrack::ccwEntryVector() const +Vector CurvedTrack::ccw_entry_vector() const { - return makeVector(cos(degToRad(startAngle)), 0.0, - -sin(degToRad(startAngle))); + return make_vector(cos(deg_to_rad(start_angle)), 0.0, + -sin(deg_to_rad(start_angle))); } -void CurvedTrack::ensureValidDirection(const Direction& aDirection) const +void CurvedTrack::ensure_valid_direction(const Direction& a_direction) const { - if (!isValidDirection(aDirection)) + if (!is_valid_direction(a_direction)) throw runtime_error ("Invalid direction on curved track from " - + lexical_cast(startAngle) + " to " - + lexical_cast(finishAngle) + " degrees: " - + lexical_cast(aDirection) + + lexical_cast(start_angle) + " to " + + lexical_cast(finish_angle) + " degrees: " + + lexical_cast(a_direction) + " (should be " - + lexical_cast(cwEntryVector()) + " or " - + lexical_cast(ccwEntryVector()) + ")"); + + lexical_cast(cw_entry_vector()) + " or " + + lexical_cast(ccw_entry_vector()) + ")"); } -bool CurvedTrack::isValidDirection(const Direction& aDirection) const +bool CurvedTrack::is_valid_direction(const Direction& a_direction) const { - return aDirection == cwEntryVector() || aDirection == ccwEntryVector(); + return a_direction == cw_entry_vector() || a_direction == ccw_entry_vector(); } -Connection CurvedTrack::nextPosition(const track::TravelToken& aToken) const +Connection CurvedTrack::next_position(const track::TravelToken& a_token) const { bool backwards; - Vector nextDir; - if (aToken.direction == cwEntryVector()) { - nextDir = -ccwEntryVector(); + Vector next_dir; + if (a_token.direction == cw_entry_vector()) { + next_dir = -ccw_entry_vector(); backwards = true; } - else if (aToken.direction == ccwEntryVector()) { - nextDir = -cwEntryVector(); + else if (a_token.direction == ccw_entry_vector()) { + next_dir = -cw_entry_vector(); backwards = false; } else assert(false); // Assuming 90 degree curves again - const int cosEnd = static_cast(cos(degToRad(finishAngle))); - const int cosStart = static_cast(cos(degToRad(startAngle))); - const int sinEnd = static_cast(sin(degToRad(finishAngle))); - const int sinStart = static_cast(sin(degToRad(startAngle))); + const int cos_end = static_cast(cos(deg_to_rad(finish_angle))); + const int cos_start = static_cast(cos(deg_to_rad(start_angle))); + const int sin_end = static_cast(sin(deg_to_rad(finish_angle))); + const int sin_start = static_cast(sin(deg_to_rad(start_angle))); - int xDelta, yDelta; + int x_delta, y_delta; if (backwards) - xDelta = yDelta = 0; + x_delta = y_delta = 0; else { - xDelta = (baseRadius - 1) * (sinEnd - sinStart); - yDelta = (baseRadius - 1) * (cosEnd - cosStart); + x_delta = (base_radius - 1) * (sin_end - sin_start); + y_delta = (base_radius - 1) * (cos_end - cos_start); } - return make_pair(makePoint(origin.x + xDelta + nextDir.x, - origin.y + yDelta + nextDir.z), - nextDir); + return make_pair(make_point(origin.x + x_delta + next_dir.x, + origin.y + y_delta + next_dir.z), + next_dir); } -void CurvedTrack::getEndpoints(vector >& aList) const +void CurvedTrack::get_endpoints(vector >& a_list) const { - aList.push_back(origin); + a_list.push_back(origin); // Assuming 90 degree curves again - const int cosEnd = static_cast(cos(degToRad(finishAngle))); - const int cosStart = static_cast(cos(degToRad(startAngle))); - const int sinEnd = static_cast(sin(degToRad(finishAngle))); - const int sinStart = static_cast(sin(degToRad(startAngle))); + const int cos_end = static_cast(cos(deg_to_rad(finish_angle))); + const int cos_start = static_cast(cos(deg_to_rad(start_angle))); + const int sin_end = static_cast(sin(deg_to_rad(finish_angle))); + const int sin_start = static_cast(sin(deg_to_rad(start_angle))); - const int xDelta = (baseRadius - 1) * (sinEnd - sinStart); - const int yDelta = (baseRadius - 1) * (cosEnd - cosStart); + const int x_delta = (base_radius - 1) * (sin_end - sin_start); + const int y_delta = (base_radius - 1) * (cos_end - cos_start); - aList.push_back(makePoint(origin.x + xDelta, origin.y + yDelta)); + a_list.push_back(make_point(origin.x + x_delta, origin.y + y_delta)); } -void CurvedTrack::getCovers(vector >& output) const +void CurvedTrack::get_covers(vector >& output) const { vector > exits; - getEndpoints(exits); + get_endpoints(exits); const Point& start = exits.at(0); const Point& finish = exits.at(1); - Point trueOrigin = - (startAngle == 90 || startAngle == 270) - ? makePoint(finish.x, start.y) - : makePoint(start.x, finish.y); + Point true_origin = + (start_angle == 90 || start_angle == 270) + ? make_point(finish.x, start.y) + : make_point(start.x, finish.y); set > tmp; // A fiddle factor to put the cover tiles in the best location - const float fiddleRadius = static_cast(baseRadius) - 0.5f; + const float fiddle_radius = static_cast(base_radius) - 0.5f; - const float sign = (startAngle == 0 || startAngle == 180) ? 1.0f : -1.0f; + const float sign = (start_angle == 0 || start_angle == 180) ? 1.0f : -1.0f; - for (track::Angle angle = startAngle; angle < finishAngle; angle += 5) { - float x = fiddleRadius * sign * cos(degToRad(angle)); - float y = fiddleRadius * sign * sin(degToRad(angle)); - Point p = makePoint(static_cast(x), + for (track::Angle angle = start_angle; angle < finish_angle; angle += 5) { + float x = fiddle_radius * sign * cos(deg_to_rad(angle)); + float y = fiddle_radius * sign * sin(deg_to_rad(angle)); + Point p = make_point(static_cast(x), static_cast(y)); - if (abs(p.x) >= baseRadius || abs(p.y) >= baseRadius) + if (abs(p.x) >= base_radius || abs(p.y) >= base_radius) continue; - Point actual = p + trueOrigin; + Point actual = p + true_origin; if (actual != start && actual != finish) tmp.insert(actual); @@ -299,12 +299,12 @@ void CurvedTrack::getCovers(vector >& output) const copy(tmp.begin(), tmp.end(), back_inserter(output)); } -ITrackSegmentPtr CurvedTrack::mergeExit(Point where, track::Direction dir) +ITrackSegmentPtr CurvedTrack::merge_exit(Point where, track::Direction dir) { // See if this is already an exit - if (isValidDirection(dir)) { + if (is_valid_direction(dir)) { vector > exits; - getEndpoints(exits); + get_endpoints(exits); for (vector >::iterator it = exits.begin(); it != exits.end(); ++it) @@ -318,27 +318,27 @@ ITrackSegmentPtr CurvedTrack::mergeExit(Point where, track::Direction dir) void CurvedTrack::merge(IMeshBufferPtr buf) const { - const Vector off = makeVector( + const Vector off = make_vector( static_cast(origin.x), height, static_cast(origin.y)); - mergeCurvedTrack(buf, off, baseRadius, startAngle, finishAngle); + merge_curved_track(buf, off, base_radius, start_angle, finish_angle); } -xml::element CurvedTrack::toXml() const +xml::element CurvedTrack::to_xml() const { - return xml::element("curvedTrack") - .addAttribute("startAngle", startAngle) - .addAttribute("finishAngle", finishAngle) - .addAttribute("radius", baseRadius); + return xml::element("curved_track") + .add_attribute("start_angle", start_angle) + .add_attribute("finish_angle", finish_angle) + .add_attribute("radius", base_radius); } -ITrackSegmentPtr makeCurvedTrack(track::Angle aStartAngle, - track::Angle aFinishAngle, int aRadius) +ITrackSegmentPtr make_curved_track(track::Angle a_start_angle, + track::Angle a_finish_angle, int a_radius) { - assert(aStartAngle < aFinishAngle); + assert(a_start_angle < a_finish_angle); return ITrackSegmentPtr - (new CurvedTrack(aStartAngle, aFinishAngle, aRadius)); + (new CurvedTrack(a_start_angle, a_finish_angle, a_radius)); } diff --git a/src/Editor.cpp b/src/Editor.cpp index a415d0a..7d568b4 100644 --- a/src/Editor.cpp +++ b/src/Editor.cpp @@ -33,21 +33,21 @@ // Concrete editor class class Editor : public IScreen { public: - Editor(IMapPtr aMap); - Editor(const string& aMapName); + Editor(IMapPtr a_map); + Editor(const string& a_map_name); ~Editor(); - void display(IGraphicsPtr aContext) const; + void display(IGraphicsPtr a_context) const; void overlay() const; - void update(IPickBufferPtr pickBuffer, int aDelta); - void onKeyDown(SDLKey aKey); - void onKeyUp(SDLKey aKey); - void onMouseMove(IPickBufferPtr pickBuffer, + void update(IPickBufferPtr pick_buffer, int a_delta); + void on_key_down(SDLKey a_key); + void on_key_up(SDLKey a_key); + void on_mouse_move(IPickBufferPtr pick_buffer, int x, int y, int xrel, int yrel); - void onMouseClick(IPickBufferPtr pickBuffer, int x, int y, - MouseButton aButton); - void onMouseRelease(IPickBufferPtr pickBuffer, int x, int y, - MouseButton aButton); + void on_mouse_click(IPickBufferPtr pick_buffer, int x, int y, + MouseButton a_button); + void on_mouse_release(IPickBufferPtr pick_buffer, int x, int y, + MouseButton a_button); // Different tools the user can be using enum Tool { @@ -55,53 +55,53 @@ public: LEVEL_TOOL, START_TOOL, STATION_TOOL, BUILDING_TOOL, TREE_TOOL, SMOOTH_TOOL }; - void setTool(Tool aTool) { myTool = aTool; } + void set_tool(Tool a_tool) { my_tool = a_tool; } - IMapPtr getMap() { return map; } - void setMap(IMapPtr aMap); + IMapPtr get_map() { return map; } + void set_map(IMapPtr a_map); private: void buildGUI(); - void drawDraggedTrack(); - bool drawTrackTile(Point where, track::Direction axis); - void drawDraggedStraight(const track::Direction& anAxis, int aLength); - void drawDraggedCurve(int xLength, int yLength); - bool canConnect(const Point& aFirstPoint, - const Point& aSecondPoint) const; - bool canPlaceTrack(ITrackSegmentPtr track); - void dragBoxBounds(int& xMin, int& xMax, int &yMin, int& yMax) const; - void deleteObjects(); - void plantTrees(); + void draw_dragged_track(); + bool draw_track_tile(Point where, track::Direction axis); + void draw_dragged_straight(const track::Direction& an_axis, int a_length); + void draw_dragged_curve(int x_length, int y_length); + bool can_connect(const Point& a_first_point, + const Point& a_second_point) const; + bool can_place_track(ITrackSegmentPtr track); + void drag_box_bounds(int& x_min, int& x_max, int &y_min, int& y_max) const; + void delete_objects(); + void plant_trees(); void save(); IMapPtr map; - ILightPtr mySun; - Vector myPosition; + ILightPtr my_sun; + Vector my_position; - Tool myTool; - bool amScrolling; + Tool my_tool; + bool am_scrolling; // Variables for dragging track segments - Point dragBegin, dragEnd; - bool amDragging; + Point drag_begin, drag_end; + bool am_dragging; // GUI elements gui::ILayoutPtr layout; - ISceneryPickerPtr buildingPicker, treePicker; + ISceneryPickerPtr building_picker, tree_picker; }; -Editor::Editor(IMapPtr aMap) - : map(aMap), myPosition(4.5f, -17.5f, -21.5f), - myTool(TRACK_TOOL), amScrolling(false), amDragging(false) +Editor::Editor(IMapPtr a_map) + : map(a_map), my_position(4.5f, -17.5f, -21.5f), + my_tool(TRACK_TOOL), am_scrolling(false), am_dragging(false) { - mySun = makeSunLight(); + my_sun = make_sun_light(); buildGUI(); - map->setGrid(true); + map->set_grid(true); - log() << "Editing " << aMap->name(); + log() << "Editing " << a_map->name(); } Editor::~Editor() @@ -113,40 +113,40 @@ void Editor::buildGUI() { using namespace placeholders; - layout = gui::makeLayout("layouts/editor.xml"); + layout = gui::make_layout("layouts/editor.xml"); layout->get("/tool_wnd/tools/track").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, TRACK_TOOL)); + bind(&Editor::set_tool, this, TRACK_TOOL)); layout->get("/tool_wnd/tools/raise").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, RAISE_TOOL)); + bind(&Editor::set_tool, this, RAISE_TOOL)); layout->get("/tool_wnd/tools/lower").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, LOWER_TOOL)); + bind(&Editor::set_tool, this, LOWER_TOOL)); layout->get("/tool_wnd/tools/level").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, LEVEL_TOOL)); + bind(&Editor::set_tool, this, LEVEL_TOOL)); layout->get("/tool_wnd/tools/delete").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, DELETE_TOOL)); + bind(&Editor::set_tool, this, DELETE_TOOL)); layout->get("/tool_wnd/tools/start").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, START_TOOL)); + bind(&Editor::set_tool, this, START_TOOL)); layout->get("/tool_wnd/tools/station").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, STATION_TOOL)); + bind(&Editor::set_tool, this, STATION_TOOL)); layout->get("/tool_wnd/tools/building").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, BUILDING_TOOL)); + bind(&Editor::set_tool, this, BUILDING_TOOL)); layout->get("/tool_wnd/tools/tree").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, TREE_TOOL)); + bind(&Editor::set_tool, this, TREE_TOOL)); layout->get("/tool_wnd/tools/smooth").connect(gui::Widget::SIG_CLICK, - bind(&Editor::setTool, this, SMOOTH_TOOL)); + bind(&Editor::set_tool, this, SMOOTH_TOOL)); layout->get("/lower/action_wnd/save").connect(gui::Widget::SIG_CLICK, bind(&Editor::save, this)); - buildingPicker = makeBuildingPicker(layout); - treePicker = makeTreePicker(layout); + building_picker = make_building_picker(layout); + tree_picker = make_tree_picker(layout); } -void Editor::setMap(IMapPtr aMap) +void Editor::set_map(IMapPtr a_map) { - map = aMap; - map->setGrid(true); + map = a_map; + map->set_grid(true); } void Editor::save() @@ -156,37 +156,37 @@ void Editor::save() // Calculate the bounds of the drag box accounting for the different // possible directions of dragging -void Editor::dragBoxBounds(int& xMin, int& xMax, int &yMin, int& yMax) const +void Editor::drag_box_bounds(int& x_min, int& x_max, int &y_min, int& y_max) const { - xMin = min(dragBegin.x, dragEnd.x); - xMax = max(dragBegin.x, dragEnd.x); + x_min = min(drag_begin.x, drag_end.x); + x_max = max(drag_begin.x, drag_end.x); - yMin = min(dragBegin.y, dragEnd.y); - yMax = max(dragBegin.y, dragEnd.y); + y_min = min(drag_begin.y, drag_end.y); + y_max = max(drag_begin.y, drag_end.y); } // Render the next frame -void Editor::display(IGraphicsPtr aContext) const +void Editor::display(IGraphicsPtr a_context) const { if (!map) return; - aContext->setCamera(myPosition, makeVector(45.0f, 45.0f, 0.0f)); + a_context->set_camera(my_position, make_vector(45.0f, 45.0f, 0.0f)); - mySun->apply(); + my_sun->apply(); // Draw the highlight if we are dragging track - if (amDragging) { + if (am_dragging) { int xmin, xmax, ymin, ymax; - dragBoxBounds(xmin, xmax, ymin, ymax); + drag_box_bounds(xmin, xmax, ymin, ymax); for (int x = xmin; x <= xmax; x++) { for (int y = ymin; y <= ymax; y++) - map->highlightTile(makePoint(x, y), colour::WHITE); + map->highlight_tile(make_point(x, y), colour::WHITE); } } - map->render(aContext); + map->render(a_context); } // Render the overlay @@ -196,33 +196,33 @@ void Editor::overlay() const } // Prepare the next frame -void Editor::update(IPickBufferPtr pickBuffer, int aDelta) +void Editor::update(IPickBufferPtr pick_buffer, int a_delta) { } -// True if the `aFirstPoint' is a valid track segment and it can -// connect to `aSecondPoint' -bool Editor::canConnect(const Point& aFirstPoint, - const Point& aSecondPoint) const +// True if the `a_first_point' is a valid track segment and it can +// connect to `a_second_point' +bool Editor::can_connect(const Point& a_first_point, + const Point& a_second_point) const { - if (!map->isValidTrack(aFirstPoint)) + if (!map->is_valid_track(a_first_point)) return false; - ITrackSegmentPtr track = map->trackAt(aFirstPoint); + ITrackSegmentPtr track = map->track_at(a_first_point); - Vector dir = makeVector( - aFirstPoint.x - aSecondPoint.x, + Vector dir = make_vector( + a_first_point.x - a_second_point.x, 0, - aFirstPoint.y - aSecondPoint.y).normalise(); + a_first_point.y - a_second_point.y).normalise(); - return track->isValidDirection(dir) - || track->isValidDirection(-dir); + return track->is_valid_direction(dir) + || track->is_valid_direction(-dir); } // Draw a single tile of straight track and check for collisions // Returns `false' if track cannot be placed here -bool Editor::drawTrackTile(Point where, track::Direction axis) +bool Editor::draw_track_tile(Point where, track::Direction axis) { // Ensure axis is only in the positive direction if (axis == -axis::X) @@ -230,10 +230,10 @@ bool Editor::drawTrackTile(Point where, track::Direction axis) else if (axis == -axis::Y) axis = axis::Y; - if (map->isValidTrack(where)) { - ITrackSegmentPtr merged = map->trackAt(where)->mergeExit(where, axis); + if (map->is_valid_track(where)) { + ITrackSegmentPtr merged = map->track_at(where)->merge_exit(where, axis); if (merged) { - map->setTrackAt(where, merged); + map->set_track_at(where, merged); return true; } else { @@ -243,34 +243,34 @@ bool Editor::drawTrackTile(Point where, track::Direction axis) } else { bool level; - Vector slope = map->slopeAt(where, axis, level); + Vector slope = map->slope_at(where, axis, level); - bool bValid, aValid; - Vector slopeBefore = map->slopeBefore(where, axis, bValid); - Vector slopeAfter = map->slopeAfter(where, axis, aValid); + bool b_valid, a_valid; + Vector slope_before = map->slope_before(where, axis, b_valid); + Vector slope_after = map->slope_after(where, axis, a_valid); if (level) { const bool flat = abs(slope.y) < 0.001f - && (!bValid || abs(slopeBefore.y) < 0.001f) - && (!aValid || abs(slopeAfter.y) < 0.001); + && (!b_valid || abs(slope_before.y) < 0.001f) + && (!a_valid || abs(slope_after.y) < 0.001); if (flat) { - map->setTrackAt(where, makeStraightTrack(axis)); + map->set_track_at(where, make_straight_track(axis)); return true; } else { - if (!bValid || !aValid) { + if (!b_valid || !a_valid) { warn() << "Cannot place track here"; return false; } else { debug() << "slope=" << slope - << " before=" << slopeBefore - << " after=" << slopeAfter; + << " before=" << slope_before + << " after=" << slope_after; - map->setTrackAt(where, - makeSlopeTrack(axis, slope, slopeBefore, slopeAfter)); + map->set_track_at(where, + make_slope_track(axis, slope, slope_before, slope_after)); return true; } @@ -285,28 +285,28 @@ bool Editor::drawTrackTile(Point where, track::Direction axis) // Special case where the user drags a rectangle of width 1 // This just draws straight track along the rectangle -void Editor::drawDraggedStraight(const track::Direction& anAxis, int aLength) +void Editor::draw_dragged_straight(const track::Direction& an_axis, int a_length) { - Point where = dragBegin; + Point where = drag_begin; - for (int i = 0; i < aLength; i++) { - drawTrackTile(where, anAxis); + for (int i = 0; i < a_length; i++) { + draw_track_tile(where, an_axis); - where.x += anAxis.x; - where.y += anAxis.z; + where.x += an_axis.x; + where.y += an_axis.z; } } // True if a track segment could be placed in its present location -bool Editor::canPlaceTrack(ITrackSegmentPtr track) +bool Editor::can_place_track(ITrackSegmentPtr track) { vector > covered; - track->getEndpoints(covered); - track->getCovers(covered); + track->get_endpoints(covered); + track->get_covers(covered); for (vector >::iterator it = covered.begin(); it != covered.end(); ++it) { - if (map->isValidTrack(*it)) { + if (map->is_valid_track(*it)) { warn() << "Cannot place track here"; return false; } @@ -317,117 +317,117 @@ bool Editor::canPlaceTrack(ITrackSegmentPtr track) // Called when the user has finished dragging a rectangle for track // Connect the beginning and end up in the simplest way possible -void Editor::drawDraggedTrack() +void Editor::draw_dragged_track() { track::Direction straight; // Orientation for straight track section int xmin, xmax, ymin, ymax; - dragBoxBounds(xmin, xmax, ymin, ymax); + drag_box_bounds(xmin, xmax, ymin, ymax); int xlen = abs(xmax - xmin) + 1; int ylen = abs(ymax - ymin) + 1; // Try to merge the start and end directly - const track::Direction mergeAxis = - xlen > ylen ? (dragBegin.x < dragEnd.x ? -axis::X : axis::X) - : (dragBegin.y < dragEnd.y ? -axis::Y : axis::Y); - if (map->isValidTrack(dragEnd)) { + const track::Direction merge_axis = + xlen > ylen ? (drag_begin.x < drag_end.x ? -axis::X : axis::X) + : (drag_begin.y < drag_end.y ? -axis::Y : axis::Y); + if (map->is_valid_track(drag_end)) { ITrackSegmentPtr merged = - map->trackAt(dragEnd)->mergeExit(dragBegin, mergeAxis); + map->track_at(drag_end)->merge_exit(drag_begin, merge_axis); if (merged) { // Erase all the tiles covered for (int x = xmin; x <= xmax; x++) { for (int y = ymin; y <= ymax; y++) - map->eraseTile(x, y); + map->erase_tile(x, y); } - map->setTrackAt(dragEnd, merged); + map->set_track_at(drag_end, merged); return; } } // Normalise the coordinates so the start is always the one with // the smallest x-coordinate - if (dragBegin.x > dragEnd.x) - swap(dragBegin, dragEnd); + if (drag_begin.x > drag_end.x) + swap(drag_begin, drag_end); - track::Direction startDir, endDir; - bool startWasGuess = false; - bool endWasGuess = false; + track::Direction start_dir, end_dir; + bool start_was_guess = false; + bool end_was_guess = false; // Try to work out the direction of the track start - if (canConnect(dragBegin.left(), dragBegin) - || canConnect(dragBegin.right(), dragBegin)) { - startDir = axis::X; + if (can_connect(drag_begin.left(), drag_begin) + || can_connect(drag_begin.right(), drag_begin)) { + start_dir = axis::X; } - else if (canConnect(dragBegin.up(), dragBegin) - || canConnect(dragBegin.down(), dragBegin)) { - startDir = axis::Y; + else if (can_connect(drag_begin.up(), drag_begin) + || can_connect(drag_begin.down(), drag_begin)) { + start_dir = axis::Y; } else - startWasGuess = true; + start_was_guess = true; // Try to work out the direction of the track end - if (canConnect(dragEnd.left(), dragEnd) - || canConnect(dragEnd.right(), dragEnd)) { - endDir = axis::X; + if (can_connect(drag_end.left(), drag_end) + || can_connect(drag_end.right(), drag_end)) { + end_dir = axis::X; } - else if (canConnect(dragEnd.up(), dragEnd) - || canConnect(dragEnd.down(), dragEnd)) { - endDir = axis::Y; + else if (can_connect(drag_end.up(), drag_end) + || can_connect(drag_end.down(), drag_end)) { + end_dir = axis::Y; } else - endWasGuess = true; + end_was_guess = true; // If we have to guess both orientations use a heuristic to decide // between S-bends and curves - if (endWasGuess && startWasGuess) { + if (end_was_guess && start_was_guess) { if (min(xlen, ylen) <= 2) { if (xlen > ylen) - startDir = endDir = axis::X; + start_dir = end_dir = axis::X; else - startDir = endDir = axis::Y; + start_dir = end_dir = axis::Y; } else { - startDir = axis::X; - endDir = axis::Y; + start_dir = axis::X; + end_dir = axis::Y; } } // Otherwise always prefer curves to S-bends - else if (startWasGuess) - startDir = endDir == axis::X ? axis::Y : axis::X; - else if (endWasGuess) - endDir = startDir == axis::X ? axis::Y : axis::X; + else if (start_was_guess) + start_dir = end_dir == axis::X ? axis::Y : axis::X; + else if (end_was_guess) + end_dir = start_dir == axis::X ? axis::Y : axis::X; if (xlen == 1 && ylen == 1) { // A single tile - drawTrackTile(dragBegin, startDir); + draw_track_tile(drag_begin, start_dir); } else if (xlen == 1) - drawDraggedStraight(dragBegin.y < dragEnd.y ? axis::Y : -axis::Y, ylen); + draw_dragged_straight(drag_begin.y < drag_end.y ? axis::Y : -axis::Y, ylen); else if (ylen == 1) - drawDraggedStraight(axis::X, xlen); - else if (startDir == endDir) { + draw_dragged_straight(axis::X, xlen); + else if (start_dir == end_dir) { // An S-bend - if (startDir == axis::Y && dragBegin.y > dragEnd.y) - swap(dragBegin, dragEnd); + if (start_dir == axis::Y && drag_begin.y > drag_end.y) + swap(drag_begin, drag_end); const int straight = - (startDir == axis::X - ? dragEnd.x - dragBegin.x - : dragEnd.y - dragBegin.y) + 1; + (start_dir == axis::X + ? drag_end.x - drag_begin.x + : drag_end.y - drag_begin.y) + 1; const int offset = - startDir == axis::X - ? dragEnd.y - dragBegin.y - : dragEnd.x - dragBegin.x; - ITrackSegmentPtr track = makeSBend(startDir, straight, offset); - const Point where = dragBegin; - track->setOrigin(where.x, where.y, map->heightAt(where)); - - if (canPlaceTrack(track)) - map->setTrackAt(where, track); + start_dir == axis::X + ? drag_end.y - drag_begin.y + : drag_end.x - drag_begin.x; + ITrackSegmentPtr track = makeSBend(start_dir, straight, offset); + const Point where = drag_begin; + track->set_origin(where.x, where.y, map->height_at(where)); + + if (can_place_track(track)) + map->set_track_at(where, track); } else { // Curves at the moment cannot be ellipses so lay track down @@ -436,228 +436,228 @@ void Editor::drawDraggedTrack() if (xlen > ylen) { // One of the ends must lie along the x-axis since all // curves are through 90 degrees so extend that one - if (startDir == axis::X) { - drawTrackTile(dragBegin, axis::X); - dragBegin.x++; + if (start_dir == axis::X) { + draw_track_tile(drag_begin, axis::X); + drag_begin.x++; } else { - drawTrackTile(dragEnd, axis::X); - dragEnd.x--; + draw_track_tile(drag_end, axis::X); + drag_end.x--; } xlen--; } else { // Need to draw track along y-axis - if (startDir == axis::Y) { - drawTrackTile(dragBegin, axis::Y); + if (start_dir == axis::Y) { + draw_track_tile(drag_begin, axis::Y); // The y-coordinate for the drag points is not guaranteed // to be sorted - if (dragBegin.y > dragEnd.y) - dragBegin.y--; + if (drag_begin.y > drag_end.y) + drag_begin.y--; else - dragBegin.y++; + drag_begin.y++; } else { - drawTrackTile(dragEnd, axis::Y); + draw_track_tile(drag_end, axis::Y); - if (dragBegin.y > dragEnd.y) - dragEnd.y++; + if (drag_begin.y > drag_end.y) + drag_end.y++; else - dragEnd.y--; + drag_end.y--; } ylen--; } } - track::Angle startAngle, endAngle; + track::Angle start_angle, end_angle; Point where; - if (startDir == axis::X && endDir == axis::Y) { - if (dragBegin.y < dragEnd.y) { - startAngle = 90; - endAngle = 180; - where = dragEnd; + if (start_dir == axis::X && end_dir == axis::Y) { + if (drag_begin.y < drag_end.y) { + start_angle = 90; + end_angle = 180; + where = drag_end; } else { - startAngle = 0; - endAngle = 90; - where = dragBegin; + start_angle = 0; + end_angle = 90; + where = drag_begin; } } else { - if (dragBegin.y < dragEnd.y) { - startAngle = 270; - endAngle = 360; - where = dragBegin; + if (drag_begin.y < drag_end.y) { + start_angle = 270; + end_angle = 360; + where = drag_begin; } else { - startAngle = 180; - endAngle = 270; - where = dragEnd; + start_angle = 180; + end_angle = 270; + where = drag_end; } } - ITrackSegmentPtr track = makeCurvedTrack(startAngle, endAngle, xlen); - track->setOrigin(where.x, where.y, map->heightAt(where)); + ITrackSegmentPtr track = make_curved_track(start_angle, end_angle, xlen); + track->set_origin(where.x, where.y, map->height_at(where)); - if (canPlaceTrack(track)) - map->setTrackAt(where, track); + if (can_place_track(track)) + map->set_track_at(where, track); } } // Delete all objects in the area selected by the user -void Editor::deleteObjects() +void Editor::delete_objects() { int xmin, xmax, ymin, ymax; - dragBoxBounds(xmin, xmax, ymin, ymax); + drag_box_bounds(xmin, xmax, ymin, ymax); for (int x = xmin; x <= xmax; x++) { for (int y = ymin; y <= ymax; y++) - map->eraseTile(x, y); + map->erase_tile(x, y); } } // Plant trees at random locations in the dragged region -void Editor::plantTrees() +void Editor::plant_trees() { int xmin, xmax, ymin, ymax; - dragBoxBounds(xmin, xmax, ymin, ymax); + drag_box_bounds(xmin, xmax, ymin, ymax); - const bool isSingleTile = (xmin == xmax) && (ymin == ymax); + const bool is_single_tile = (xmin == xmax) && (ymin == ymax); const float threshold = 0.9f; - static Uniform treeRand(0.0f, 1.0f); + static Uniform tree_rand(0.0f, 1.0f); for (int x = xmin; x <= xmax; x++) { for (int y = ymin; y <= ymax; y++) { - const Point p = makePoint(x, y); + const Point p = make_point(x, y); - if ((isSingleTile || treeRand() > threshold) && map->emptyTile(p)) - map->addScenery(p, treePicker->get()); + if ((is_single_tile || tree_rand() > threshold) && map->empty_tile(p)) + map->add_scenery(p, tree_picker->get()); } } } -void Editor::onMouseMove(IPickBufferPtr pickBuffer, int x, int y, +void Editor::on_mouse_move(IPickBufferPtr pick_buffer, int x, int y, int xrel, int yrel) { - if (amDragging) { + if (am_dragging) { // Extend the selection rectangle - map->setPickMode(true); - IGraphicsPtr pickContext = pickBuffer->beginPick(x, y); - display(pickContext); - int id = pickBuffer->endPick(); - map->setPickMode(false); + map->set_pick_mode(true); + IGraphicsPtr pick_context = pick_buffer->begin_pick(x, y); + display(pick_context); + int id = pick_buffer->end_pick(); + map->set_pick_mode(false); if (id > 0) - dragEnd = map->pickPosition(id); + drag_end = map->pick_position(id); } - else if (amScrolling) { + else if (am_scrolling) { const float speed = 0.05f; - myPosition.x -= static_cast(xrel) * speed; - myPosition.z -= static_cast(xrel) * speed; + my_position.x -= static_cast(xrel) * speed; + my_position.z -= static_cast(xrel) * speed; - myPosition.x += static_cast(yrel) * speed; - myPosition.z -= static_cast(yrel) * speed; + my_position.x += static_cast(yrel) * speed; + my_position.z -= static_cast(yrel) * speed; } } -void Editor::onMouseClick(IPickBufferPtr pickBuffer, int x, int y, - MouseButton aButton) +void Editor::on_mouse_click(IPickBufferPtr pick_buffer, int x, int y, + MouseButton a_button) { - if (aButton == MOUSE_RIGHT) { + if (a_button == MOUSE_RIGHT) { // Start scrolling - amScrolling = true; + am_scrolling = true; } - else if (aButton == MOUSE_LEFT) { - bool clickedOnGUI = layout->click(x, y); + else if (a_button == MOUSE_LEFT) { + bool clicked_onGUI = layout->click(x, y); - if (!clickedOnGUI) { + if (!clicked_onGUI) { // See if the user clicked on something in the map - map->setPickMode(true); - IGraphicsPtr pickContext = pickBuffer->beginPick(x, y); - display(pickContext); - int id = pickBuffer->endPick(); - map->setPickMode(false); + map->set_pick_mode(true); + IGraphicsPtr pick_context = pick_buffer->begin_pick(x, y); + display(pick_context); + int id = pick_buffer->end_pick(); + map->set_pick_mode(false); if (id > 0) { // Begin dragging a selection rectangle - Point where = map->pickPosition(id); + Point where = map->pick_position(id); - dragBegin = dragEnd = where; - amDragging = true; + drag_begin = drag_end = where; + am_dragging = true; } } } - else if (aButton == MOUSE_WHEEL_UP) { - myPosition.y -= 0.5f; + else if (a_button == MOUSE_WHEEL_UP) { + my_position.y -= 0.5f; } - else if (aButton == MOUSE_WHEEL_DOWN) { - myPosition.y += 0.5f; + else if (a_button == MOUSE_WHEEL_DOWN) { + my_position.y += 0.5f; } } -void Editor::onMouseRelease(IPickBufferPtr pickBuffer, int x, int y, - MouseButton aButton) +void Editor::on_mouse_release(IPickBufferPtr pick_buffer, int x, int y, + MouseButton a_button) { - if (amDragging) { + if (am_dragging) { // Stop dragging and perform the action - switch (myTool) { + switch (my_tool) { case TRACK_TOOL: - drawDraggedTrack(); + draw_dragged_track(); break; case RAISE_TOOL: - map->raiseArea(dragBegin, dragEnd); + map->raise_area(drag_begin, drag_end); break; case LOWER_TOOL: - map->lowerArea(dragBegin, dragEnd); + map->lower_area(drag_begin, drag_end); break; case LEVEL_TOOL: - map->levelArea(dragBegin, dragEnd); + map->level_area(drag_begin, drag_end); break; case DELETE_TOOL: - deleteObjects(); + delete_objects(); break; case START_TOOL: - map->setStart(dragBegin.x, dragBegin.y); + map->set_start(drag_begin.x, drag_begin.y); break; case STATION_TOOL: - map->extendStation(dragBegin, dragEnd); + map->extend_station(drag_begin, drag_end); break; case BUILDING_TOOL: - map->addScenery(dragBegin, buildingPicker->get()); + map->add_scenery(drag_begin, building_picker->get()); break; case TREE_TOOL: - plantTrees(); + plant_trees(); break; case SMOOTH_TOOL: - map->smoothArea(dragBegin, dragEnd); + map->smooth_area(drag_begin, drag_end); break; } - amDragging = false; + am_dragging = false; } - else if (amScrolling) { - amScrolling = false; + else if (am_scrolling) { + am_scrolling = false; } } -void Editor::onKeyUp(SDLKey aKey) +void Editor::on_key_up(SDLKey a_key) { } -void Editor::onKeyDown(SDLKey aKey) +void Editor::on_key_down(SDLKey a_key) { - switch (aKey) { + switch (a_key) { case SDLK_g: // Toggle grid - map->setGrid(true); + map->set_grid(true); break; case SDLK_PRINT: - getGameWindow()->takeScreenShot(); + get_game_window()->take_screen_shot(); break; default: break; @@ -665,7 +665,7 @@ void Editor::onKeyDown(SDLKey aKey) } // Create an instance of the editor screen -IScreenPtr makeEditorScreen(IMapPtr aMap) +IScreenPtr make_editor_screen(IMapPtr a_map) { - return IScreenPtr(new Editor(aMap)); + return IScreenPtr(new Editor(a_map)); } diff --git a/src/Engine.cpp b/src/Engine.cpp index a1e53f1..8f6ae3a 100644 --- a/src/Engine.cpp +++ b/src/Engine.cpp @@ -60,44 +60,44 @@ class Engine : public IRollingStock, public IXMLCallback, public enable_shared_from_this { public: - Engine(IResourcePtr aRes); + Engine(IResourcePtr a_res); // IRollingStock interface void render() const; void update(int delta, double gravity); - double speed() const { return mySpeed; } - double mass() const { return myMass; } + double speed() const { return my_speed; } + double mass() const { return my_mass; } IControllerPtr controller() { return shared_from_this(); } float length() const { return model->dimensions().x; } // IController interface - void actOn(Action anAction); - int throttle() const { return myThrottle; } - bool brakeOn() const { return isBrakeOn; } - bool reverseOn() const { return reverse; } - double pressure() const { return myBoilerPressure; } - double temp() const { return myFireTemp; } - bool stopped() const { return haveStopped; } + void act_on(Action an_action); + int throttle() const { return my_throttle; } + bool brake_on() const { return is_brake_on; } + bool reverse_on() const { return reverse; } + double pressure() const { return my_boiler_pressure; } + double temp() const { return my_fire_temp; } + bool stopped() const { return have_stopped; } // IXMLCallback interface - void text(const string& localName, const string& aString); + void text(const string& local_name, const string& a_string); private: - double tractiveEffort() const; + double tractive_effort() const; double resistance() const; - double brakeForce() const; + double brake_force() const; IModelPtr model; - double mySpeed, myMass, myBoilerPressure, myFireTemp; - double statTractiveEffort; - bool isBrakeOn; - int myThrottle; // Ratio measured in tenths + double my_speed, my_mass, my_boiler_pressure, my_fire_temp; + double stat_tractive_effort; + bool is_brake_on; + int my_throttle; // Ratio measured in tenths bool reverse; - bool haveStopped; + bool have_stopped; // Boiler pressure lags behind temperature - MovingAverage myBoilerDelay; + MovingAverage my_boiler_delay; IResourcePtr resource; @@ -115,26 +115,26 @@ const double Engine::INIT_PRESSURE(0.2); const double Engine::INIT_TEMP(50.0); const double Engine::STOP_SPEED(0.01); -Engine::Engine(IResourcePtr aRes) - : mySpeed(0.0), myMass(29.0), - myBoilerPressure(INIT_PRESSURE), - myFireTemp(INIT_TEMP), - statTractiveEffort(34.7), - isBrakeOn(true), myThrottle(0), +Engine::Engine(IResourcePtr a_res) + : my_speed(0.0), my_mass(29.0), + my_boiler_pressure(INIT_PRESSURE), + my_fire_temp(INIT_TEMP), + stat_tractive_effort(34.7), + is_brake_on(true), my_throttle(0), reverse(false), - haveStopped(true), - resource(aRes) + have_stopped(true), + resource(a_res) { static IXMLParserPtr parser = makeXMLParser("schemas/engine.xsd"); - parser->parse(resource->xmlFileName(), *this); + parser->parse(resource->xml_file_name(), *this); } // Callback for loading elements from the XML file -void Engine::text(const string& localName, const string& aString) +void Engine::text(const string& local_name, const string& a_string) { - if (localName == "model") { - model = loadModel(resource, aString, MODEL_SCALE); + if (local_name == "model") { + model = load_model(resource, a_string, MODEL_SCALE); model->cache(); } } @@ -146,49 +146,49 @@ void Engine::render() const } // Calculate the current tractive effort -double Engine::tractiveEffort() const +double Engine::tractive_effort() const { const double dir = reverse ? -1.0 : 1.0; - if (abs(mySpeed) < TRACTIVE_EFFORT_KNEE) - return statTractiveEffort * dir; + if (abs(my_speed) < TRACTIVE_EFFORT_KNEE) + return stat_tractive_effort * dir; else - return (statTractiveEffort * TRACTIVE_EFFORT_KNEE) - / abs(mySpeed) + return (stat_tractive_effort * TRACTIVE_EFFORT_KNEE) + / abs(my_speed) * dir; } // Calculate the magnitude of the resistance on the train double Engine::resistance() const { - const double sign = mySpeed < 0.0 ? -1.0 : 1.0; + const double sign = my_speed < 0.0 ? -1.0 : 1.0; const double a = 4.0; const double b = 0.05; const double c = 0.006; - const double absSpeed = abs(mySpeed); + const double abs_speed = abs(my_speed); - return sign * (a + b*absSpeed + c*absSpeed*absSpeed); + return sign * (a + b*abs_speed + c*abs_speed*abs_speed); } // Calculate the magnitude of the braking force -double Engine::brakeForce() const +double Engine::brake_force() const { const double beta = 0.09; const double g = 9.78; // Brake always acts against direction of motion double dir; - if (mySpeed < 0.0) + if (my_speed < 0.0) dir = -1.0; else dir = 1.0; - if (abs(mySpeed) < STOP_SPEED) + if (abs(my_speed) < STOP_SPEED) return 0.0; else - return myMass * g * beta * dir; + return my_mass * g * beta * dir; } // Compute the next state of the engine @@ -196,54 +196,54 @@ void Engine::update(int delta, double gravity) { // Update the pressure of the boiler // The fire temperature is delayed and then used to increase it - myBoilerDelay << myFireTemp; - myBoilerPressure = myBoilerDelay.value(); + my_boiler_delay << my_fire_temp; + my_boiler_pressure = my_boiler_delay.value(); - const double P = tractiveEffort(); + const double P = tractive_effort(); const double Q = resistance(); - const double B = isBrakeOn ? brakeForce() : 0.0; + const double B = is_brake_on ? brake_force() : 0.0; const double G = gravity; // The applied tractive effort is controlled by the throttle - const double netP = P * static_cast(myThrottle) / 10.0; + const double netP = P * static_cast(my_throttle) / 10.0; - const double deltaSeconds = delta / 1000.0f; - const double a = ((netP - Q - B + G) / myMass) * deltaSeconds; + const double delta_seconds = delta / 1000.0f; + const double a = ((netP - Q - B + G) / my_mass) * delta_seconds; - if (abs(mySpeed) < STOP_SPEED && myThrottle == 0) { - if (isBrakeOn) - mySpeed = 0.0; - haveStopped = true; + if (abs(my_speed) < STOP_SPEED && my_throttle == 0) { + if (is_brake_on) + my_speed = 0.0; + have_stopped = true; } else - haveStopped = false; + have_stopped = false; - mySpeed += a; + my_speed += a; #if 0 debug() << "P=" << netP << ", Q=" << Q << ", B=" << B << ", G=" << G - << ", a=" << a << ", v=" << mySpeed + << ", a=" << a << ", v=" << my_speed << " (delta=" << delta << " grad=" << gradient << ")"; #endif } // User interface to the engine -void Engine::actOn(Action anAction) +void Engine::act_on(Action an_action) { - switch (anAction) { + switch (an_action) { case BRAKE_TOGGLE: - isBrakeOn = !isBrakeOn; + is_brake_on = !is_brake_on; break; case SHOVEL_COAL: - myFireTemp += 10.0; + my_fire_temp += 10.0; break; case THROTTLE_UP: - myThrottle = min(myThrottle + 1, 10); + my_throttle = min(my_throttle + 1, 10); break; case THROTTLE_DOWN: - myThrottle = max(myThrottle - 1, 0); + my_throttle = max(my_throttle - 1, 0); break; case TOGGLE_REVERSE: reverse = !reverse; @@ -254,17 +254,17 @@ void Engine::actOn(Action anAction) } namespace { - Engine* loadEngineXml(IResourcePtr aRes) + Engine* load_engine_xml(IResourcePtr a_res) { - log() << "Loading engine from " << aRes->xmlFileName(); + log() << "Loading engine from " << a_res->xml_file_name(); - return new Engine(aRes); + return new Engine(a_res); } } // Load an engine from a resource file -IRollingStockPtr loadEngine(const string& aResId) +IRollingStockPtr load_engine(const string& a_res_id) { - static ResourceCache cache(loadEngineXml, "engines"); - return cache.loadCopy(aResId); + static ResourceCache cache(load_engine_xml, "engines"); + return cache.load_copy(a_res_id); } diff --git a/src/Fog.cpp b/src/Fog.cpp index bfed6b8..c1c9bba 100644 --- a/src/Fog.cpp +++ b/src/Fog.cpp @@ -39,9 +39,9 @@ private: void Fog::apply() const { - GLfloat fogColor[4] = { r, g, b, 1.0f }; + GLfloat fog_color[4] = { r, g, b, 1.0f }; glFogi(GL_FOG_MODE, GL_LINEAR); - glFogfv(GL_FOG_COLOR, fogColor); + glFogfv(GL_FOG_COLOR, fog_color); glFogf(GL_FOG_DENSITY, density); glHint(GL_FOG_HINT, GL_DONT_CARE); glFogf(GL_FOG_START, start); @@ -49,18 +49,18 @@ void Fog::apply() const glEnable(GL_FOG); } -IFogPtr makeFog(float r, float g, float b, +IFogPtr make_fog(float r, float g, float b, float density, float start, float end) { return IFogPtr(new Fog(r, g, b, density, start, end)); } -IFogPtr makeFog(float density, float start, float end) +IFogPtr make_fog(float density, float start, float end) { float params[4]; glGetFloatv(GL_COLOR_CLEAR_VALUE, params); - return makeFog(params[0], params[1], params[2], + return make_fog(params[0], params[1], params[2], density, start, end); } diff --git a/src/Frustum.cpp b/src/Frustum.cpp index b9eef05..fdeb913 100644 --- a/src/Frustum.cpp +++ b/src/Frustum.cpp @@ -34,7 +34,7 @@ enum PlaneData { }; // Normalise a plane's normal vector -static void normalisePlane(float frustum[6][4], int side) +static void normalise_plane(float frustum[6][4], int side) { float magnitude = (float)sqrtf(frustum[side][A]*frustum[side][A] + frustum[side][B]*frustum[side][B] + @@ -47,7 +47,7 @@ static void normalisePlane(float frustum[6][4], int side) } // Tests whether a point is in the frustum or not -bool Frustum::pointInFrustum(float x, float y, float z) +bool Frustum::point_in_frustum(float x, float y, float z) { // Look through each plane... for (int i = 0; i < 6; i++) { @@ -59,7 +59,7 @@ bool Frustum::pointInFrustum(float x, float y, float z) } // Tests whether a sphere is inside the frustum or not -bool Frustum::sphereInFrustum(float x, float y, float z, float radius) +bool Frustum::sphere_in_frustum(float x, float y, float z, float radius) { // Look through each plane for (int i = 0; i < 6; i++) { @@ -71,7 +71,7 @@ bool Frustum::sphereInFrustum(float x, float y, float z, float radius) } // Tests whether a cube is in the view frustum -bool Frustum::cubeInFrustum(float x, float y, float z, float size) +bool Frustum::cube_in_frustum(float x, float y, float z, float size) { // Look through each plane for (int i = 0; i < 6; i++ ) { @@ -100,7 +100,7 @@ bool Frustum::cubeInFrustum(float x, float y, float z, float size) } // Works out whether a cuboid is contained in a frustum -bool Frustum::cuboidInFrustum(float x, float y, float z, +bool Frustum::cuboid_in_frustum(float x, float y, float z, float sizeX, float sizeY, float sizeZ) { int i; @@ -133,7 +133,7 @@ bool Frustum::cuboidInFrustum(float x, float y, float z, } // Extract the view frustum from OpenGL -Frustum getViewFrustum() +Frustum get_view_frustum() { float proj[16]; float modl[16]; @@ -175,7 +175,7 @@ Frustum getViewFrustum() f.planes[RIGHT][D] = clip[15] - clip[12]; // Normalize the RIGHT plane - normalisePlane(f.planes, RIGHT); + normalise_plane(f.planes, RIGHT); // Extract the LEFT plane f.planes[LEFT][A] = clip[ 3] + clip[ 0]; @@ -184,7 +184,7 @@ Frustum getViewFrustum() f.planes[LEFT][D] = clip[15] + clip[12]; // Normalize the LEFT plane - normalisePlane(f.planes, LEFT); + normalise_plane(f.planes, LEFT); // Extract the BOTTOM plane f.planes[BOTTOM][A] = clip[ 3] + clip[ 1]; @@ -193,7 +193,7 @@ Frustum getViewFrustum() f.planes[BOTTOM][D] = clip[15] + clip[13]; // Normalize the BOTTOM plane - normalisePlane(f.planes, BOTTOM); + normalise_plane(f.planes, BOTTOM); // Extract TOP plane f.planes[TOP][A] = clip[ 3] - clip[ 1]; @@ -202,7 +202,7 @@ Frustum getViewFrustum() f.planes[TOP][D] = clip[15] - clip[13]; // Normalize the TOP plane - normalisePlane(f.planes, TOP); + normalise_plane(f.planes, TOP); // Extract the BACK plane f.planes[BACK][A] = clip[ 3] - clip[ 2]; @@ -211,7 +211,7 @@ Frustum getViewFrustum() f.planes[BACK][D] = clip[15] - clip[14]; // Normalize the BACK plane - normalisePlane(f.planes, BACK); + normalise_plane(f.planes, BACK); // Extract the FRONT plane f.planes[FRONT][A] = clip[ 3] + clip[ 2]; @@ -220,7 +220,7 @@ Frustum getViewFrustum() f.planes[FRONT][D] = clip[15] + clip[14]; // Normalize the FRONT plane - normalisePlane(f.planes, FRONT); + normalise_plane(f.planes, FRONT); return f; } diff --git a/src/Game.cpp b/src/Game.cpp index 0c943dc..4db27f0 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -36,68 +36,68 @@ // Implementation of the main play screen class Game : public IScreen { public: - Game(IMapPtr aMap); + Game(IMapPtr a_map); ~Game(); - void display(IGraphicsPtr aContext) const; + void display(IGraphicsPtr a_context) const; void overlay() const; - void update(IPickBufferPtr aPickBuffer, int aDelta); - void onKeyDown(SDLKey aKey); - void onKeyUp(SDLKey aKey); - void onMouseMove(IPickBufferPtr aPickBuffer, int x, int y, int xrel, + void update(IPickBufferPtr a_pick_buffer, int a_delta); + void on_key_down(SDLKey a_key); + void on_key_up(SDLKey a_key); + void on_mouse_move(IPickBufferPtr a_pick_buffer, int x, int y, int xrel, int yrel); - void onMouseClick(IPickBufferPtr aPickBuffer, int x, int y, - MouseButton aButton); - void onMouseRelease(IPickBufferPtr aPickBuffer, int x, int y, - MouseButton aButton) {} + void on_mouse_click(IPickBufferPtr a_pick_buffer, int x, int y, + MouseButton a_button); + void on_mouse_release(IPickBufferPtr a_pick_buffer, int x, int y, + MouseButton a_button) {} private: - void lookAhead(); - void nearStation(IStationPtr s); - void leftStation(); - Vector cameraPosition(float aRadius) const; - void switchToBirdCamera(); - void stoppedAtStation(); + void look_ahead(); + void near_station(IStationPtr s); + void left_station(); + Vector camera_position(float a_radius) const; + void switch_to_birdCamera(); + void stopped_at_station(); enum TrackStateReq { NEXT, PREV }; - void alterTrackState(TrackStateReq req); + void alter_track_state(TrackStateReq req); IMapPtr map; ITrainPtr train; ILightPtr sun; // Station the train is either approaching or stopped at - IStationPtr activeStation; + IStationPtr active_station; // Camera position - float horizAngle, vertAngle, viewRadius; + float horiz_angle, vert_angle, view_radius; // Camera adjustment float cameraHTarget, cameraVTarget; - float cameraSpeed; + float camera_speed; enum CameraMode { CAMERA_FLOATING, CAMERA_FIXED, CAMERA_BIRD }; - CameraMode cameraMode; + CameraMode camera_mode; gui::ILayoutPtr layout; - IMessageAreaPtr messageArea; + IMessageAreaPtr message_area; }; -Game::Game(IMapPtr aMap) - : map(aMap), - horizAngle(M_PI/4.0f), - vertAngle(M_PI/4.0f), - viewRadius(20.0f) +Game::Game(IMapPtr a_map) + : map(a_map), + horiz_angle(M_PI/4.0f), + vert_angle(M_PI/4.0f), + view_radius(20.0f) { - train = makeTrain(map); - sun = makeSunLight(); + train = make_train(map); + sun = make_sun_light(); - map->setGrid(false); + map->set_grid(false); // Build the GUI - layout = gui::makeLayout("layouts/game.xml"); - messageArea = makeMessageArea(); + layout = gui::make_layout("layouts/game.xml"); + message_area = make_message_area(); - switchToBirdCamera(); + switch_to_birdCamera(); } Game::~Game() @@ -105,119 +105,119 @@ Game::~Game() } -Vector Game::cameraPosition(float aRadius) const +Vector Game::camera_position(float a_radius) const { // Two angles give unique position on surface of a sphere // Look up ``spherical coordinates'' - const float yCentre = 0.9f; + const float y_centre = 0.9f; Vector position = train->front(); - position.x += aRadius * cosf(horizAngle) * sinf(vertAngle); - position.z += aRadius * sinf(horizAngle) * sinf(vertAngle); - position.y = aRadius * cosf(vertAngle) + yCentre; + position.x += a_radius * cosf(horiz_angle) * sinf(vert_angle); + position.z += a_radius * sinf(horiz_angle) * sinf(vert_angle); + position.y = a_radius * cosf(vert_angle) + y_centre; return position; } -void Game::switchToBirdCamera() +void Game::switch_to_birdCamera() { - cameraMode = CAMERA_BIRD; + camera_mode = CAMERA_BIRD; cameraHTarget = M_PI/4.0f; cameraVTarget = M_PI/4.0f; - cameraSpeed = 100.0f; + camera_speed = 100.0f; } -void Game::display(IGraphicsPtr aContext) const +void Game::display(IGraphicsPtr a_context) const { - Vector trainPos = train->front(); + Vector train_pos = train->front(); - Vector position = cameraPosition(viewRadius); + Vector position = camera_position(view_radius); - aContext->lookAt(position, trainPos); - setBillboardCameraOrigin(position); + a_context->look_at(position, train_pos); + set_billboard_cameraOrigin(position); sun->apply(); - map->render(aContext); + map->render(a_context); train->render(); - renderBillboards(); + render_billboards(); } void Game::overlay() const { layout->render(); - messageArea->render(); + message_area->render(); } -void Game::stoppedAtStation() +void Game::stopped_at_station() { //layout->get("/station").visible(true); } -void Game::update(IPickBufferPtr aPickBuffer, int aDelta) +void Game::update(IPickBufferPtr a_pick_buffer, int a_delta) { - messageArea->update(aDelta); + message_area->update(a_delta); - train->update(aDelta); + train->update(a_delta); // Update the GUI elements layout->cast("/throttle_meter").value( train->controller()->throttle()); - const double msToMPH = 2.237; + const double ms_toMPH = 2.237; layout->cast("/speed_label").format( - "Speed: %.1lfmph", abs(train->speed()) * msToMPH); + "Speed: %.1lfmph", abs(train->speed()) * ms_toMPH); IControllerPtr ctrl = train->controller(); - layout->get("/brake_label").visible(ctrl->brakeOn()); - layout->get("/reverse_label").visible(ctrl->reverseOn()); + layout->get("/brake_label").visible(ctrl->brake_on()); + layout->get("/reverse_label").visible(ctrl->reverse_on()); - lookAhead(); + look_ahead(); // Move the camera vertically if it's currently underground #if 0 // Calculate the location of the near clip plane - const float nearClip = getConfig()->get("NearClip"); - Vector clipPosition = cameraPosition(viewRadius - nearClip); + const float near_clip = get_config()->get("NearClip"); + Vector clip_position = camera_position(view_radius - near_clip); // A hack because we don't calculate the height properly const float MIN_HEIGHT = 0.25f; - float h = map->heightAt(clipPosition.x, clipPosition.z); + float h = map->height_at(clip_position.x, clip_position.z); - if (h + MIN_HEIGHT > clipPosition.y) { - cameraVTarget -= 0.001f * static_cast(aDelta); - cameraSpeed = 200.0f; + if (h + MIN_HEIGHT > clip_position.y) { + cameraVTarget -= 0.001f * static_cast(a_delta); + camera_speed = 200.0f; } #endif // Bounce the camera if we need to - vertAngle -= (vertAngle - cameraVTarget) / cameraSpeed; - horizAngle -= (horizAngle - cameraHTarget) / cameraSpeed; + vert_angle -= (vert_angle - cameraVTarget) / camera_speed; + horiz_angle -= (horiz_angle - cameraHTarget) / camera_speed; } // Signal that we are approaching a station -void Game::nearStation(IStationPtr s) +void Game::near_station(IStationPtr s) { - leftStation(); // Clear any previous station + left_station(); // Clear any previous station - if (s != activeStation) { - activeStation = s; - s->setHighlightVisible(true); + if (s != active_station) { + active_station = s; + s->set_highlight_visible(true); - //gui::Widget& stationWnd = layout->get("/station"); + //gui::Widget& station_wnd = layout->get("/station"); layout->cast("/station/name").text(s->name()); } } // Signal that we are no longer at or approaching a station -void Game::leftStation() +void Game::left_station() { - if (activeStation) { - activeStation->setHighlightVisible(false); - activeStation.reset(); + if (active_station) { + active_station->set_highlight_visible(false); + active_station.reset(); //layout->get("/station").visible(false); } @@ -225,66 +225,66 @@ void Game::leftStation() // Look along the track and notify the player of any stations, points, etc. // that they are approaching -void Game::lookAhead() +void Game::look_ahead() { - TrackIterator it = iterateTrack(map, train->tile(), + TrackIterator it = iterate_track(map, train->tile(), train->direction()); // Are we sitting on a station? if (it.status == TRACK_STATION) { - nearStation(it.station); + near_station(it.station); if (train->controller()->stopped()) - stoppedAtStation(); + stopped_at_station(); else - messageArea->post("Stop here for station " + it.station->name()); + message_area->post("Stop here for station " + it.station->name()); return; } - const int maxLook = 10; - for (int i = 0; i < maxLook; i++) { + const int max_look = 10; + for (int i = 0; i < max_look; i++) { it = it.next(); if (it.status != TRACK_OK) { - bool clearStation = true; + bool clear_station = true; switch (it.status) { case TRACK_STATION: - messageArea->post("Approaching station " + it.station->name()); - nearStation(it.station); - clearStation = false; + message_area->post("Approaching station " + it.station->name()); + near_station(it.station); + clear_station = false; return; case TRACK_NO_MORE: - messageArea->post("Oh no! You're going to crash!"); + message_area->post("Oh no! You're going to crash!"); break; case TRACK_CHOICE: - messageArea->post("Oh no! You have to make a decision!"); - it.track->setStateRenderHint(); + message_area->post("Oh no! You have to make a decision!"); + it.track->set_state_renderHint(); break; default: break; } - if (!clearStation) - leftStation(); + if (!clear_station) + left_station(); return; } } // We're not approaching any station - leftStation(); + left_station(); } -void Game::alterTrackState(TrackStateReq req) +void Game::alter_track_state(TrackStateReq req) { // Change the state of the nearest points, etc. - TrackIterator it = iterateTrack(map, train->tile(), + TrackIterator it = iterate_track(map, train->tile(), train->direction()); - const int maxAlterLook = 10; + const int max_alter_look = 10; - for (int i = 0; i < maxAlterLook; i++) { + for (int i = 0; i < max_alter_look; i++) { // Skip over the first section of track which may be some // points - we don't want to alter the track we're on! @@ -293,10 +293,10 @@ void Game::alterTrackState(TrackStateReq req) if (it.status == TRACK_CHOICE) { switch (req) { case NEXT: - it.track->nextState(); + it.track->next_state(); break; case PREV: - it.track->prevState(); + it.track->prev_state(); break; } @@ -307,79 +307,79 @@ void Game::alterTrackState(TrackStateReq req) warn() << "No nearby track state to change"; } -void Game::onKeyDown(SDLKey aKey) +void Game::on_key_down(SDLKey a_key) { - switch (aKey) { + switch (a_key) { case SDLK_PAGEUP: - viewRadius = max(viewRadius - 0.2f, 0.1f); + view_radius = max(view_radius - 0.2f, 0.1f); break; case SDLK_PAGEDOWN: - viewRadius += 0.2f; + view_radius += 0.2f; break; case SDLK_b: - train->controller()->actOn(BRAKE_TOGGLE); + train->controller()->act_on(BRAKE_TOGGLE); break; case SDLK_r: if (train->controller()->throttle() == 0) - train->controller()->actOn(TOGGLE_REVERSE); + train->controller()->act_on(TOGGLE_REVERSE); else - messageArea->post("Reduce power first!", 51, 1000); + message_area->post("Reduce power first!", 51, 1000); break; case SDLK_LCTRL: - train->controller()->actOn(SHOVEL_COAL); + train->controller()->act_on(SHOVEL_COAL); break; case SDLK_PRINT: - getGameWindow()->takeScreenShot(); + get_game_window()->take_screen_shot(); break; case SDLK_LEFT: - alterTrackState(PREV); + alter_track_state(PREV); break; case SDLK_RIGHT: - alterTrackState(NEXT); + alter_track_state(NEXT); break; case SDLK_UP: - train->controller()->actOn(THROTTLE_UP); + train->controller()->act_on(THROTTLE_UP); break; case SDLK_DOWN: - train->controller()->actOn(THROTTLE_DOWN); + train->controller()->act_on(THROTTLE_DOWN); break; case SDLK_TAB: - if (cameraMode == CAMERA_FLOATING) - cameraMode = CAMERA_FIXED; - else if (cameraMode == CAMERA_FIXED) - switchToBirdCamera(); + if (camera_mode == CAMERA_FLOATING) + camera_mode = CAMERA_FIXED; + else if (camera_mode == CAMERA_FIXED) + switch_to_birdCamera(); else - cameraMode = CAMERA_FLOATING; + camera_mode = CAMERA_FLOATING; break; default: break; } } -void Game::onKeyUp(SDLKey aKey) +void Game::on_key_up(SDLKey a_key) { } -void Game::onMouseClick(IPickBufferPtr aPickBuffer, int x, int y, - MouseButton aButton) +void Game::on_mouse_click(IPickBufferPtr a_pick_buffer, int x, int y, + MouseButton a_button) { - switch (aButton) { + switch (a_button) { case MOUSE_WHEEL_UP: - viewRadius = max(viewRadius - 1.0f, 0.1f); + view_radius = max(view_radius - 1.0f, 0.1f); break; case MOUSE_WHEEL_DOWN: - viewRadius += 1.0f; + view_radius += 1.0f; break; default: break; } } -void Game::onMouseMove(IPickBufferPtr aPickBuffer, int x, int y, +void Game::on_mouse_move(IPickBufferPtr a_pick_buffer, int x, int y, int xrel, int yrel) { - if (cameraMode == CAMERA_FLOATING) { + if (camera_mode == CAMERA_FLOATING) { cameraHTarget -= xrel / 100.0f; cameraVTarget += yrel / 100.0f; @@ -393,12 +393,12 @@ void Game::onMouseMove(IPickBufferPtr aPickBuffer, int x, int y, if (cameraVTarget < top) cameraVTarget = top; - cameraSpeed = 2.0f; + camera_speed = 2.0f; } } // Create an instance of the play screen with the given map -IScreenPtr makeGameScreen(IMapPtr aMap) +IScreenPtr make_game_screen(IMapPtr a_map) { - return IScreenPtr(new Game(aMap)); + return IScreenPtr(new Game(a_map)); } diff --git a/src/IterateTrack.cpp b/src/IterateTrack.cpp index f6766dc..bd2598a 100644 --- a/src/IterateTrack.cpp +++ b/src/IterateTrack.cpp @@ -27,22 +27,22 @@ TrackIterator TrackIterator::next() const track::Direction dir; track::Position pos; - tie(pos, dir) = track->nextPosition(token); + tie(pos, dir) = track->next_position(token); - return iterateTrack(map, pos, dir); + return iterate_track(map, pos, dir); } // Build an iterator object for a given track segment -TrackIterator iterateTrack(IMapPtr aMap, track::Position aPosition, - track::Direction aDirection) +TrackIterator iterate_track(IMapPtr a_map, track::Position a_position, + track::Direction a_direction) { TrackIterator it; - it.map = aMap; + it.map = a_map; it.status = TRACK_OK ; - if (aMap->isValidTrack(aPosition)) { - it.track = aMap->trackAt(aPosition); - it.token = it.track->getTravelToken(aPosition, aDirection); + if (a_map->is_valid_track(a_position)) { + it.track = a_map->track_at(a_position); + it.token = it.track->get_travel_token(a_position, a_direction); } else { // Fell off the end @@ -54,22 +54,22 @@ TrackIterator iterateTrack(IMapPtr aMap, track::Position aPosition, // Are we sitting on a station? typedef vector > PointList; PointList endpoints; - it.track->getEndpoints(endpoints); + it.track->get_endpoints(endpoints); IStationPtr station; for (PointList::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p) - if ((it.station = aMap->stationAt(makePoint((*p).x, (*p).y)))) { + if ((it.station = a_map->station_at(make_point((*p).x, (*p).y)))) { it.status = TRACK_STATION; break; } - if (it.token.numExits > 1) { - assert(it.track->hasMultipleStates()); + if (it.token.num_exits > 1) { + assert(it.track->has_multiple_states()); it.status = TRACK_CHOICE; } else - assert(it.token.numExits == 1); + assert(it.token.num_exits == 1); return it; } diff --git a/src/Light.cpp b/src/Light.cpp index cb75b88..ce26e3a 100644 --- a/src/Light.cpp +++ b/src/Light.cpp @@ -24,9 +24,9 @@ struct SunLight : ILight { void apply() const { - //const GLfloat globalAmbient[] = { 0.3f, 0.3f, 0.3f, 1.0f }; - const GLfloat globalAmbient[] = { 0.0f, 0.0f, 0.0f, 1.0f }; - glLightModelfv(GL_LIGHT_MODEL_AMBIENT, globalAmbient); + //const GLfloat global_ambient[] = { 0.3f, 0.3f, 0.3f, 1.0f }; + const GLfloat global_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f }; + glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); const GLfloat ambient[] = { 0.45f, 0.45f, 0.45f, 1.0f }; //const GLfloat diffuse[] = { 0.4f, 0.4f, 0.4f, 1.0f }; @@ -48,7 +48,7 @@ struct SunLight : ILight { }; -ILightPtr makeSunLight() +ILightPtr make_sun_light() { return ILightPtr(new SunLight); } diff --git a/src/Logger.cpp b/src/Logger.cpp index 7deceee..21c1b0a 100644 --- a/src/Logger.cpp +++ b/src/Logger.cpp @@ -32,27 +32,27 @@ class LoggerImpl : public ILogger { public: LoggerImpl(); - PrintLinePtr writeMsg(LogMsgType type); + PrintLinePtr write_msg(LogMsgType type); }; namespace { - bool isStdoutTTY; + bool is_stdoutTTY; } LoggerImpl::LoggerImpl() { #ifdef WIN32 - isStdoutTTY = (_isatty(_fileno(stdout)) != 0); + is_stdoutTTY = (_isatty(_fileno(stdout)) != 0); #else - isStdoutTTY = (isatty(fileno(stdout)) != 0); + is_stdoutTTY = (isatty(fileno(stdout)) != 0); #endif cout.precision(3); } -PrintLinePtr LoggerImpl::writeMsg(LogMsgType type) +PrintLinePtr LoggerImpl::write_msg(LogMsgType type) { - if (isStdoutTTY) + if (is_stdoutTTY) cout << "\x1B[1m"; switch (type) { @@ -60,17 +60,17 @@ PrintLinePtr LoggerImpl::writeMsg(LogMsgType type) cout << "[INFO ] "; break; case LOG_DEBUG: - if (isStdoutTTY) + if (is_stdoutTTY) cout << "\x1B[36m"; cout << "[DEBUG] "; break; case LOG_WARN: - if (isStdoutTTY) + if (is_stdoutTTY) cout << "\x1B[33m"; cout << "[WARN ] "; break; case LOG_ERROR: - if (isStdoutTTY) + if (is_stdoutTTY) cout << "\x1B[31m"; cout << "[ERROR] "; break; @@ -78,22 +78,22 @@ PrintLinePtr LoggerImpl::writeMsg(LogMsgType type) return PrintLinePtr(new PrintLine(cout)); } -PrintLine::PrintLine(ostream& aStream) - : stream(aStream) +PrintLine::PrintLine(ostream& a_stream) + : stream(a_stream) { } PrintLine::~PrintLine() { - if (isStdoutTTY) + if (is_stdoutTTY) cout << "\x1B[0m"; stream << endl; } // Return the single instance of Logger -ILoggerPtr getLogger() +ILoggerPtr get_logger() { static ILoggerPtr logger(new LoggerImpl); return logger; diff --git a/src/Main.cpp b/src/Main.cpp index 3092b46..a7a2674 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -34,22 +34,22 @@ namespace { IWindowPtr window; // Options set from command line - int newMapWidth = 32; - int newMapHeight = 32; - string mapFile; + int new_map_width = 32; + int new_map_height = 32; + string map_file; string action; - void parseOptions(int argc, char** argv) + void parse_options(int argc, char** argv) { using namespace boost::program_options; options_description desc("Allowed options"); desc.add_options() ("help", "Display this help message") - ("width", value(&newMapWidth), "Set new map width") - ("height", value(&newMapHeight), "Set new map height") + ("width", value(&new_map_width), "Set new map width") + ("height", value(&new_map_height), "Set new map height") ("action", value(&action), "Either `play' or `edit'") - ("map", value(&mapFile), "Name of map to load or create") + ("map", value(&map_file), "Name of map to load or create") ; positional_options_description p; @@ -75,14 +75,14 @@ namespace { } } -IWindowPtr getGameWindow() +IWindowPtr get_game_window() { return ::window; } int main(int argc, char** argv) { - parseOptions(argc, argv); + parse_options(argc, argv); cout << PACKAGE << " " << VERSION << "." << PATCH << endl << endl << "Copyright (C) 2009-2010 Nick Gasson" << endl @@ -95,26 +95,26 @@ int main(int argc, char** argv) log() << "Program started"; try { - if (::action == "" || ::mapFile == "") + if (::action == "" || ::map_file == "") throw runtime_error("Usage: TrainGame (edit|play) [map]"); - initResources(); + init_resources(); - IConfigPtr cfg = getConfig(); + IConfigPtr cfg = get_config(); ::window = makeSDLWindow(); IScreenPtr screen; if (::action == "edit") { - if (resourceExists(mapFile, "maps")) - screen = makeEditorScreen(loadMap(::mapFile)); + if (resource_exists(map_file, "maps")) + screen = make_editor_screen(load_map(::map_file)); else { - screen = makeEditorScreen( - makeEmptyMap(::mapFile, ::newMapWidth, ::newMapHeight)); + screen = make_editor_screen( + make_empty_map(::map_file, ::new_map_width, ::new_map_height)); } } else if (::action == "play") { - screen = makeGameScreen(loadMap(::mapFile)); + screen = make_game_screen(load_map(::map_file)); } else if (::action == "uidemo") { screen = makeUIDemo(); diff --git a/src/Map.cpp b/src/Map.cpp index f3013be..ccffb0a 100644 --- a/src/Map.cpp +++ b/src/Map.cpp @@ -51,12 +51,12 @@ // information about the track. class TrackNode { public: - TrackNode(ITrackSegmentPtr aTrack, int x, int y) - : track(aTrack), lastFrame(-1), - origin(makePoint(x, y)) {} + TrackNode(ITrackSegmentPtr a_track, int x, int y) + : track(a_track), last_frame(-1), + origin(make_point(x, y)) {} - inline void renderedOn(int f) { lastFrame = f; } - inline bool needsRendering(int f) const { return f != lastFrame; } + inline void rendered_on(int f) { last_frame = f; } + inline bool needs_rendering(int f) const { return f != last_frame; } inline ITrackSegmentPtr get() { return track; } @@ -64,7 +64,7 @@ public: inline int originY() const { return origin.y; } private: ITrackSegmentPtr track; - int lastFrame; + int last_frame; Point origin; }; @@ -74,58 +74,58 @@ class Map : public IMap, public ISectorRenderable, public enable_shared_from_this { friend class MapLoader; public: - Map(IResourcePtr aRes); + Map(IResourcePtr a_res); ~Map(); // IMap interface - int width() const { return myWidth; } - int depth() const { return myDepth; } - double heightAt() const { return 0.0; } + int width() const { return my_width; } + int depth() const { return my_depth; } + double height_at() const { return 0.0; } string name() const { return resource->name(); } - void setStart(int x, int y); - void setStart(int x, int y, int dirX, int dirY); - void setGrid(bool onOff); - void setPickMode(bool onOff) { inPickMode = onOff; } + void set_start(int x, int y); + void set_start(int x, int y, int dirX, int dirY); + void set_grid(bool on_off); + void set_pick_mode(bool on_off) { in_pick_mode = on_off; } track::Connection start() const; - ITrackSegmentPtr trackAt(const Point& aPoint) const; - IStationPtr stationAt(Point aPoint) const; - void setTrackAt(const Point& aPoint, ITrackSegmentPtr aTrack); - bool isValidTrack(const Point& aPoint) const; - void render(IGraphicsPtr aContext) const; - void highlightTile(Point point, Colour colour) const; - void resetMap(int aWidth, int aDepth); - void eraseTile(int x, int y); - bool emptyTile(Point tile) const; - - void raiseArea(const Point& aStartPos, - const Point& aFinishPos); - void lowerArea(const Point& aStartPos, - const Point& aFinishPos); - void levelArea(Point aStartPos, Point aFinishPos); - void smoothArea(Point start, Point finish); + ITrackSegmentPtr track_at(const Point& a_point) const; + IStationPtr station_at(Point a_point) const; + void set_track_at(const Point& a_point, ITrackSegmentPtr a_track); + bool is_valid_track(const Point& a_point) const; + void render(IGraphicsPtr a_context) const; + void highlight_tile(Point point, Colour colour) const; + void reset_map(int a_width, int a_depth); + void erase_tile(int x, int y); + bool empty_tile(Point tile) const; + + void raise_area(const Point& a_start_pos, + const Point& a_finish_pos); + void lower_area(const Point& a_start_pos, + const Point& a_finish_pos); + void level_area(Point a_start_pos, Point a_finish_pos); + void smooth_area(Point start, Point finish); void save(); - IStationPtr extendStation(Point aStartPos, - Point aFinishPos); - float heightAt(float x, float y) const; - float heightAt(Point where) const; - Vector slopeAt(Point where, track::Direction axis, + IStationPtr extend_station(Point a_start_pos, + Point a_finish_pos); + float height_at(float x, float y) const; + float height_at(Point where) const; + Vector slope_at(Point where, track::Direction axis, bool& level) const; - Vector slopeBefore(Point where, + Vector slope_before(Point where, track::Direction axis, bool &valid) const; - Vector slopeAfter(Point where, + Vector slope_after(Point where, track::Direction axis, bool &valid) const; - void addScenery(Point where, ISceneryPtr s); + void add_scenery(Point where, ISceneryPtr s); // ISectorRenderable interface - void renderSector(IGraphicsPtr aContext, int id, - Point botLeft, Point topRight); - void postRenderSector(IGraphicsPtr aContext, int id, - Point botLeft, Point topRight); + void render_sector(IGraphicsPtr a_context, int id, + Point bot_left, Point top_right); + void post_render_sector(IGraphicsPtr a_context, int id, + Point bot_left, Point top_right); private: // Tiles on the map @@ -139,106 +139,106 @@ private: // Vertices on the terrain struct Vertex { Vector pos, normal; - } *heightMap; + } *height_map; static const unsigned TILE_NAME_BASE = 1000; // Base of tile naming static const unsigned NULL_OBJECT = 0; // Non-existant object static const float TILE_HEIGHT; // Standard height increment // Meshes for each terrain sector - vector terrainMeshes; + vector terrain_meshes; inline int index(int x, int y) const { - assert(x < myWidth && y < myDepth && x >= 0 && y >= 0); - return x + y*myWidth; + assert(x < my_width && y < my_depth && x >= 0 && y >= 0); + return x + y*my_width; } - inline int tileName(int x, int z) const + inline int tile_name(int x, int z) const { return TILE_NAME_BASE + index(x, z); } - inline Tile& tileAt(int x, int z) const + inline Tile& tile_at(int x, int z) const { return tiles[index(x, z)]; } - inline Tile& tileAt(const Point& p) const + inline Tile& tile_at(const Point& p) const { - return tileAt(p.x, p.y); + return tile_at(p.x, p.y); } - inline Vertex& heightAt(int i) const + inline Vertex& height_at(int i) const { - assert(i >= 0 && i < (myWidth + 1) * (myDepth + 1)); - return heightMap[i]; + assert(i >= 0 && i < (my_width + 1) * (my_depth + 1)); + return height_map[i]; } - bool isValidTileName(unsigned aName) const + bool is_valid_tileName(unsigned a_name) const { - return aName >= TILE_NAME_BASE - && aName < TILE_NAME_BASE + myWidth * myDepth; + return a_name >= TILE_NAME_BASE + && a_name < TILE_NAME_BASE + my_width * my_depth; } - Point pickPosition(unsigned aName) const + Point pick_position(unsigned a_name) const { - assert(isValidTileName(aName)); + assert(is_valid_tileName(a_name)); - int a = aName - TILE_NAME_BASE; - return makePoint(a % myWidth, a / myWidth); + int a = a_name - TILE_NAME_BASE; + return make_point(a % my_width, a / my_width); } - void writeHeightMap() const; - void saveTo(ostream& of); - void readHeightMap(IResource::Handle aHandle); - void tileVertices(int x, int y, int* indexes) const; - void renderPickSector(Point botLeft, Point topRight); - void drawStartLocation() const; - void setStationAt(Point point, IStationPtr aStation); - void renderHighlightedTiles() const; + void write_height_map() const; + void save_to(ostream& of); + void read_height_map(IResource::Handle a_handle); + void tile_vertices(int x, int y, int* indexes) const; + void render_pick_sector(Point bot_left, Point top_right); + void draw_start_location() const; + void set_station_at(Point point, IStationPtr a_station); + void render_highlighted_tiles() const; // Mesh modification - void buildMesh(int id, Point botLeft, Point topRight); - bool haveMesh(int id, Point botLeft, Point topRight); - void dirtyTile(int x, int y); + void build_mesh(int id, Point bot_left, Point top_right); + bool have_mesh(int id, Point bot_left, Point top_right); + void dirty_tile(int x, int y); // Terrain modification - void changeAreaHeight(const Point& aStartPos, - const Point& aFinishPos, float aHeightDelta); - void raiseTile(int x, int y, float deltaHeight); - void setTileHeight(int x, int y, float h); - void fixNormals(int x, int y); - bool raiseWillCoverTrack(int x, int y) const; + void change_area_height(const Point& a_start_pos, + const Point& a_finish_pos, float a_height_delta); + void raise_tile(int x, int y, float delta_height); + void set_tile_height(int x, int y, float h); + void fix_normals(int x, int y); + bool raise_will_coverTrack(int x, int y) const; - int myWidth, myDepth; - Point startLocation; - track::Direction startDirection; - IQuadTreePtr quadTree; + int my_width, my_depth; + Point start_location; + track::Direction start_direction; + IQuadTreePtr quad_tree; IFogPtr fog; - bool shouldDrawGridLines, inPickMode; - list > dirtyTiles; + bool should_draw_gridLines, in_pick_mode; + list > dirty_tiles; IResourcePtr resource; - vector seaSectors; + vector sea_sectors; // Variables used during rendering - mutable int frameNum; - mutable vector, Colour> > highlightedTiles; + mutable int frame_num; + mutable vector, Colour> > highlighted_tiles; }; const float Map::TILE_HEIGHT(0.2f); -Map::Map(IResourcePtr aRes) - : tiles(NULL), heightMap(NULL), myWidth(0), myDepth(0), - startLocation(makePoint(1, 1)), - startDirection(axis::X), - shouldDrawGridLines(false), inPickMode(false), - resource(aRes), frameNum(0) +Map::Map(IResourcePtr a_res) + : tiles(NULL), height_map(NULL), my_width(0), my_depth(0), + start_location(make_point(1, 1)), + start_direction(axis::X), + should_draw_gridLines(false), in_pick_mode(false), + resource(a_res), frame_num(0) { - const float farClip = getConfig()->get("FarClip"); - fog = makeFog(0.005f, // Density - 3.0f * farClip / 4.0f, // Start - farClip); // End distance + const float far_clip = get_config()->get("FarClip"); + fog = make_fog(0.005f, // Density + 3.0f * far_clip / 4.0f, // Start + far_clip); // End distance } Map::~Map() @@ -246,43 +246,43 @@ Map::~Map() delete tiles; } -ITrackSegmentPtr Map::trackAt(const Point& aPoint) const +ITrackSegmentPtr Map::track_at(const Point& a_point) const { - TrackNodePtr ptr = tileAt(aPoint.x, aPoint.y).track; + TrackNodePtr ptr = tile_at(a_point.x, a_point.y).track; if (ptr) return ptr->get(); else { ostringstream ss; - ss << "No track segment at " << aPoint; + ss << "No track segment at " << a_point; throw runtime_error(ss.str()); } } -IStationPtr Map::stationAt(Point aPoint) const +IStationPtr Map::station_at(Point a_point) const { - return tileAt(aPoint.x, aPoint.y).station; + return tile_at(a_point.x, a_point.y).station; } -void Map::setStationAt(Point point, IStationPtr aStation) +void Map::set_station_at(Point point, IStationPtr a_station) { - tileAt(point).station = aStation; + tile_at(point).station = a_station; } -void Map::eraseTile(int x, int y) +void Map::erase_tile(int x, int y) { - Tile& tile = tileAt(x, y); + Tile& tile = tile_at(x, y); if (tile.track) { // We have to be a bit careful since a piece of track has multiple // endpoints vector > covers; - tile.track->get()->getEndpoints(covers); - tile.track->get()->getCovers(covers); + tile.track->get()->get_endpoints(covers); + tile.track->get()->get_covers(covers); for (vector >::iterator it = covers.begin(); it != covers.end(); ++it) - tileAt((*it).x, (*it).y).track.reset(); + tile_at((*it).x, (*it).y).track.reset(); } if (tile.scenery) @@ -291,79 +291,79 @@ void Map::eraseTile(int x, int y) if (tile.station) tile.station.reset(); - dirtyTile(x, y); + dirty_tile(x, y); } -bool Map::emptyTile(Point point) const +bool Map::empty_tile(Point point) const { - Tile& tile = tileAt(point); + Tile& tile = tile_at(point); return !(tile.track || tile.scenery); } -void Map::setTrackAt(const Point& where, ITrackSegmentPtr track) +void Map::set_track_at(const Point& where, ITrackSegmentPtr track) { int indexes[4]; - tileVertices(where.x, where.y, indexes); + tile_vertices(where.x, where.y, indexes); - float lowestHeight = 1.0e20f; + float lowest_height = 1.0e20f; for (int i = 0; i < 4; i++) - lowestHeight = min(heightMap[indexes[i]].pos.y, lowestHeight); + lowest_height = min(height_map[indexes[i]].pos.y, lowest_height); - track->setOrigin(where.x, where.y, lowestHeight); + track->set_origin(where.x, where.y, lowest_height); TrackNodePtr node(new TrackNode(track, where.x, where.y)); // Attach the track node to every tile it covers vector > covers; - track->getEndpoints(covers); - track->getCovers(covers); + track->get_endpoints(covers); + track->get_covers(covers); for (vector >::iterator it = covers.begin(); it != covers.end(); ++it) { - tileAt((*it).x, (*it).y).track = node; + tile_at((*it).x, (*it).y).track = node; - dirtyTile((*it).x, (*it).y); + dirty_tile((*it).x, (*it).y); } } -bool Map::isValidTrack(const Point& where) const +bool Map::is_valid_track(const Point& where) const { if (where.x < 0 || where.y < 0 - || where.x >= myWidth || where.y >= myDepth) + || where.x >= my_width || where.y >= my_depth) return false; - return tileAt(where.x, where.y).track; + return tile_at(where.x, where.y).track; } // Return a location where the train may start track::Connection Map::start() const { - return make_pair(startLocation, startDirection); + return make_pair(start_location, start_direction); } // Try to place the train on this tile -void Map::setStart(int x, int y) +void Map::set_start(int x, int y) { - const track::Direction possDirs[] = { + const track::Direction poss_dirs[] = { axis::X, axis::Y, -axis::X, -axis::Y }; - static int nextDir = 0; + static int next_dir = 0; - TrackNodePtr trackNode = tileAt(x, y).track; - if (!trackNode) { + TrackNodePtr track_node = tile_at(x, y).track; + if (!track_node) { warn() << "Must place start on track"; return; } - ITrackSegmentPtr track = trackNode->get(); + ITrackSegmentPtr track = track_node->get(); int tried = 0; do { - if (track->isValidDirection(possDirs[nextDir])) + if (track->is_valid_direction(poss_dirs[next_dir])) break; else - nextDir = (nextDir + 1) % 4; + next_dir = (next_dir + 1) % 4; } while (++tried < 4); if (tried == 4) { @@ -371,61 +371,63 @@ void Map::setStart(int x, int y) return; } - startLocation = makePoint(x, y); - startDirection = possDirs[nextDir]; + start_location = make_point(x, y); + start_direction = poss_dirs[next_dir]; - nextDir = (nextDir + 1) % 4; + next_dir = (next_dir + 1) % 4; } // Force the train to start on this tile -void Map::setStart(int x, int y, int dirX, int dirY) +void Map::set_start(int x, int y, int dirX, int dirY) { - startLocation = makePoint(x, y); - startDirection = makeVector(dirX, 0, dirY); + start_location = make_point(x, y); + start_direction = make_vector(dirX, 0, dirY); + + debug() << "start " << start_location; } -void Map::setGrid(bool onOff) +void Map::set_grid(bool on_off) { - shouldDrawGridLines = onOff; + should_draw_gridLines = on_off; } -void Map::resetMap(int aWidth, int aDepth) +void Map::reset_map(int a_width, int a_depth) { - myWidth = aWidth; - myDepth = aDepth; + my_width = a_width; + my_depth = a_depth; // Allocate memory if (tiles) delete[] tiles; - tiles = new Tile[aWidth * aDepth]; + tiles = new Tile[a_width * a_depth]; - if (heightMap) - delete[] heightMap; - heightMap = new Vertex[(aWidth + 1) * (aDepth + 1)]; + if (height_map) + delete[] height_map; + height_map = new Vertex[(a_width + 1) * (a_depth + 1)]; // Make a flat map - for (int x = 0; x <= aWidth; x++) { - for (int y = 0; y <= aDepth; y++) { - Vertex& v = heightMap[x + y*(aWidth+1)]; + for (int x = 0; x <= a_width; x++) { + for (int y = 0; y <= a_depth; y++) { + Vertex& v = height_map[x + y*(a_width+1)]; const float xf = static_cast(x) - 0.5f; const float yf = static_cast(y) - 0.5f; - v.pos = makeVector(xf, 0.0f, yf); - v.normal = makeVector(0.0f, 1.0f, 0.0f); + v.pos = make_vector(xf, 0.0f, yf); + v.normal = make_vector(0.0f, 1.0f, 0.0f); } } // Create quad tree - quadTree = makeQuadTree(shared_from_this(), myWidth, myDepth); + quad_tree = make_quad_tree(shared_from_this(), my_width, my_depth); } -void Map::highlightTile(Point point, Colour colour) const +void Map::highlight_tile(Point point, Colour colour) const { - highlightedTiles.push_back(make_tuple(point, colour)); + highlighted_tiles.push_back(make_tuple(point, colour)); } -void Map::renderHighlightedTiles() const +void Map::render_highlighted_tiles() const { // At the end of the render loop, draw the highlighted tiles over // the top of all others - this is to get the transparency working @@ -439,23 +441,23 @@ void Map::renderHighlightedTiles() const glDepthMask(GL_FALSE); vector, Colour> >::const_iterator it; - for (it = highlightedTiles.begin(); it != highlightedTiles.end(); ++it) { + for (it = highlighted_tiles.begin(); it != highlighted_tiles.end(); ++it) { const Point& point = get<0>(*it); Colour colour = get<1>(*it); // User should be able to click on the highlight as well - glPushName(tileName(point.x, point.y)); + glPushName(tile_name(point.x, point.y)); colour.a = 0.5f; gl::colour(colour); glBegin(GL_POLYGON); int indexes[4]; - tileVertices(point.x, point.y, indexes); + tile_vertices(point.x, point.y, indexes); for (int i = 0; i < 4; i++) { - Vertex& v = heightMap[indexes[i]]; + Vertex& v = height_map[indexes[i]]; glNormal3f(v.normal.x, v.normal.y, v.normal.z); glVertex3f(v.pos.x, v.pos.y + 0.1f, v.pos.z); } @@ -467,14 +469,14 @@ void Map::renderHighlightedTiles() const glPopAttrib(); - highlightedTiles.clear(); + highlighted_tiles.clear(); } -void Map::render(IGraphicsPtr aContext) const +void Map::render(IGraphicsPtr a_context) const { - // The `frameNum' counter is used to ensure we draw each + // The `frame_num' counter is used to ensure we draw each // track segment at most once per frame - frameNum++; + frame_num++; fog->apply(); @@ -491,17 +493,17 @@ void Map::render(IGraphicsPtr aContext) const glEnable(GL_CULL_FACE); glPushMatrix(); - quadTree->render(aContext); + quad_tree->render(a_context); glPopMatrix(); - renderHighlightedTiles(); + render_highlighted_tiles(); glPopAttrib(); } // Draw an arrow on the start location -void Map::drawStartLocation() const +void Map::draw_start_location() const { glPushAttrib(GL_ENABLE_BIT); glPushMatrix(); @@ -510,22 +512,22 @@ void Map::drawStartLocation() const glDisable(GL_TEXTURE_2D); int indexes[4]; - tileVertices(startLocation.x, startLocation.y, indexes); + tile_vertices(start_location.x, start_location.y, indexes); - float avgHeight = 0.0f; + float avg_height = 0.0f; for (int i = 0; i < 4; i++) - avgHeight += heightMap[indexes[i]].pos.y; - avgHeight /= 4.0f; + avg_height += height_map[indexes[i]].pos.y; + avg_height /= 4.0f; - glTranslatef(static_cast(startLocation.x), - avgHeight + 0.1f, - static_cast(startLocation.y)); + glTranslatef(static_cast(start_location.x), + avg_height + 0.1f, + static_cast(start_location.y)); - if (startDirection == axis::X) + if (start_direction == axis::X) glRotatef(90.0f, 0.0f, 1.0f, 0.0f); - else if (startDirection == -axis::Y) + else if (start_direction == -axis::Y) glRotatef(180.0f, 0.0f, 1.0f, 0.0f); - else if (startDirection == -axis::X) + else if (start_direction == -axis::X) glRotatef(270.0f, 0.0f, 1.0f, 0.0f); glColor4f(0.0f, 0.9f, 0.0f, 0.8f); @@ -543,24 +545,24 @@ void Map::drawStartLocation() const // Check to see if the given id contains a valid mesh and ensure the // array is large enough to hold it -bool Map::haveMesh(int id, Point botLeft, Point topRight) +bool Map::have_mesh(int id, Point bot_left, Point top_right) { - if (id >= static_cast(terrainMeshes.size())) - terrainMeshes.resize(id + 1); + if (id >= static_cast(terrain_meshes.size())) + terrain_meshes.resize(id + 1); - bool ok = terrainMeshes[id]; - list >::iterator it = dirtyTiles.begin(); + bool ok = terrain_meshes[id]; + list >::iterator it = dirty_tiles.begin(); - while (it != dirtyTiles.end()) { + while (it != dirty_tiles.end()) { bool covered = - (*it).x >= botLeft.x - && (*it).x <= topRight.x - && (*it).y >= botLeft.y - && (*it).y <= topRight.y; + (*it).x >= bot_left.x + && (*it).x <= top_right.x + && (*it).y >= bot_left.y + && (*it).y <= top_right.y; if (covered) { ok = false; - it = dirtyTiles.erase(it); + it = dirty_tiles.erase(it); } else ++it; @@ -570,22 +572,22 @@ bool Map::haveMesh(int id, Point botLeft, Point topRight) } // Record that the mesh containing a tile needs rebuilding -void Map::dirtyTile(int x, int y) +void Map::dirty_tile(int x, int y) { - dirtyTiles.push_back(makePoint(x, y)); + dirty_tiles.push_back(make_point(x, y)); // Push its neighbours as well since the vertices of a tile sit // on mesh boundaries - dirtyTiles.push_back(makePoint(x, y + 1)); - dirtyTiles.push_back(makePoint(x, y - 1)); - dirtyTiles.push_back(makePoint(x + 1, y)); - dirtyTiles.push_back(makePoint(x - 1, y)); + dirty_tiles.push_back(make_point(x, y + 1)); + dirty_tiles.push_back(make_point(x, y - 1)); + dirty_tiles.push_back(make_point(x + 1, y)); + dirty_tiles.push_back(make_point(x - 1, y)); } // Generate a terrain mesh for a particular sector -void Map::buildMesh(int id, Point botLeft, Point topRight) +void Map::build_mesh(int id, Point bot_left, Point top_right) { - static const tuple colourMap[] = { + static const tuple colour_map[] = { // Start height colour make_tuple( 7.0f, makeRGB(238, 233, 233) ), make_tuple( 5.0f, makeRGB(124, 113, 36) ), @@ -595,17 +597,17 @@ void Map::buildMesh(int id, Point botLeft, Point topRight) make_tuple( -1e10f, makeRGB(177, 176, 96) ) }; - IMeshBufferPtr buf = makeMeshBuffer(); + IMeshBufferPtr buf = make_mesh_buffer(); // Incrementing the frame counter here ensures that any track which spans // multiple sectors will be merged with each applicable mesh even when // the meshes are built on the same frame - ++frameNum; + ++frame_num; - for (int x = topRight.x-1; x >= botLeft.x; x--) { - for (int y = botLeft.y; y < topRight.y; y++) { + for (int x = top_right.x-1; x >= bot_left.x; x--) { + for (int y = bot_left.y; y < top_right.y; y++) { int indexes[4]; - tileVertices(x, y, indexes); + tile_vertices(x, y, indexes); const int order[6] = { indexes[1], indexes[2], indexes[3], @@ -613,167 +615,167 @@ void Map::buildMesh(int id, Point botLeft, Point topRight) }; for (int i = 0; i < 6; i++) { - const Vertex& v = heightMap[order[i]]; + const Vertex& v = height_map[order[i]]; const float h = v.pos.y; tuple hcol; int j = 0; do { - hcol = colourMap[j++]; + hcol = colour_map[j++]; } while (get<0>(hcol) > h); - buf->add(makeVector(v.pos.x, v.pos.y, v.pos.z), - makeVector(v.normal.x, v.normal.y, v.normal.z), + buf->add(make_vector(v.pos.x, v.pos.y, v.pos.z), + make_vector(v.normal.x, v.normal.y, v.normal.z), get<1>(hcol)); } } } // Merge any static scenery - for (int x = topRight.x-1; x >= botLeft.x; x--) { - for (int y = botLeft.y; y < topRight.y; y++) { - Tile& tile = tileAt(x, y); + for (int x = top_right.x-1; x >= bot_left.x; x--) { + for (int y = bot_left.y; y < top_right.y; y++) { + Tile& tile = tile_at(x, y); if (tile.scenery) tile.scenery->merge(buf); // Draw the track, if any - if (tile.track && tile.track->needsRendering(frameNum)) { + if (tile.track && tile.track->needs_rendering(frame_num)) { // TODO: how will this work with track that spans // multiple sectors? tile.track->get()->merge(buf); - tile.track->renderedOn(frameNum); + tile.track->rendered_on(frame_num); } } } // Draw the sides of the map if this is an edge sector - const float x1 = static_cast(botLeft.x) - 0.5f; - const float x2 = static_cast(topRight.x) - 0.5f; - const float y1 = static_cast(botLeft.y) - 0.5f; - const float y2 = static_cast(topRight.y) - 0.5f; + const float x1 = static_cast(bot_left.x) - 0.5f; + const float x2 = static_cast(top_right.x) - 0.5f; + const float y1 = static_cast(bot_left.y) - 0.5f; + const float y2 = static_cast(top_right.y) - 0.5f; const Colour brown = makeRGB(104, 57, 12); const float depth = -3.0f; int index[4]; - if (botLeft.x == 0) { - for (int y = botLeft.y; y < topRight.y; y++) { + if (bot_left.x == 0) { + for (int y = bot_left.y; y < top_right.y; y++) { const float yf = static_cast(y) - 0.5f; - tileVertices(0, y, index); + tile_vertices(0, y, index); - const float h1 = heightAt(index[3]).pos.y; - const float h2 = heightAt(index[0]).pos.y; + const float h1 = height_at(index[3]).pos.y; + const float h2 = height_at(index[0]).pos.y; - buf->addQuad(makeVector(x1, h1, yf), - makeVector(x1, depth, yf), - makeVector(x1, depth, yf + 1.0f), - makeVector(x1, h2, yf + 1.0f), + buf->add_quad(make_vector(x1, h1, yf), + make_vector(x1, depth, yf), + make_vector(x1, depth, yf + 1.0f), + make_vector(x1, h2, yf + 1.0f), brown); } } - if (topRight.x == myWidth) { - for (int y = botLeft.y; y < topRight.y; y++) { + if (top_right.x == my_width) { + for (int y = bot_left.y; y < top_right.y; y++) { const float yf = static_cast(y) - 0.5f; - tileVertices(myWidth - 1, y, index); + tile_vertices(my_width - 1, y, index); - const float h1 = heightAt(index[2]).pos.y; - const float h2 = heightAt(index[1]).pos.y; + const float h1 = height_at(index[2]).pos.y; + const float h2 = height_at(index[1]).pos.y; - buf->addQuad(makeVector(x2, depth, yf), - makeVector(x2, h1, yf), - makeVector(x2, h2, yf + 1.0f), - makeVector(x2, depth, yf + 1.0f), + buf->add_quad(make_vector(x2, depth, yf), + make_vector(x2, h1, yf), + make_vector(x2, h2, yf + 1.0f), + make_vector(x2, depth, yf + 1.0f), brown); } } - if (botLeft.y == 0) { - for (int x = botLeft.x; x < topRight.x; x++) { + if (bot_left.y == 0) { + for (int x = bot_left.x; x < top_right.x; x++) { const float xf = static_cast(x) - 0.5f; - tileVertices(x, 0, index); + tile_vertices(x, 0, index); - const float h1 = heightAt(index[3]).pos.y; - const float h2 = heightAt(index[2]).pos.y; + const float h1 = height_at(index[3]).pos.y; + const float h2 = height_at(index[2]).pos.y; - buf->addQuad(makeVector(xf, depth, y1), - makeVector(xf, h1, y1), - makeVector(xf + 1.0f, h2, y1), - makeVector(xf + 1.0f, depth, y1), + buf->add_quad(make_vector(xf, depth, y1), + make_vector(xf, h1, y1), + make_vector(xf + 1.0f, h2, y1), + make_vector(xf + 1.0f, depth, y1), brown); } } - if (topRight.y == myDepth) { - for (int x = botLeft.x; x < topRight.x; x++) { + if (top_right.y == my_depth) { + for (int x = bot_left.x; x < top_right.x; x++) { const float xf = static_cast(x) - 0.5f; - tileVertices(x, myDepth - 1, index); + tile_vertices(x, my_depth - 1, index); - const float h1 = heightAt(index[0]).pos.y; - const float h2 = heightAt(index[1]).pos.y; + const float h1 = height_at(index[0]).pos.y; + const float h2 = height_at(index[1]).pos.y; - buf->addQuad(makeVector(xf, h1, y2), - makeVector(xf, depth, y2), - makeVector(xf + 1.0f, depth, y2), - makeVector(xf + 1.0f, h2, y2), + buf->add_quad(make_vector(xf, h1, y2), + make_vector(xf, depth, y2), + make_vector(xf + 1.0f, depth, y2), + make_vector(xf + 1.0f, h2, y2), brown); } } - terrainMeshes[id] = makeMesh(buf); + terrain_meshes[id] = make_mesh(buf); // Check if this sector needs a sea quad drawn - bool belowSeaLevel = false; - for (int x = topRight.x-1; x >= botLeft.x; x--) { - for (int y = botLeft.y; y < topRight.y; y++) { + bool below_sea_level = false; + for (int x = top_right.x-1; x >= bot_left.x; x--) { + for (int y = bot_left.y; y < top_right.y; y++) { int index[4]; - tileVertices(x, y, index); + tile_vertices(x, y, index); - belowSeaLevel |= - heightAt(index[0]).pos.y < 0.0f - || heightAt(index[1]).pos.y < 0.0f - || heightAt(index[2]).pos.y < 0.0f - || heightAt(index[3]).pos.y < 0.0f; - - if (belowSeaLevel) - goto belowSeaLevelOut; + below_sea_level |= + height_at(index[0]).pos.y < 0.0f + || height_at(index[1]).pos.y < 0.0f + || height_at(index[2]).pos.y < 0.0f + || height_at(index[3]).pos.y < 0.0f; + + if (below_sea_level) + goto below_sea_levelOut; } } - belowSeaLevelOut: + below_sea_levelOut: - size_t minSize = id + 1; - if (seaSectors.size() < minSize) - seaSectors.resize(minSize); - seaSectors.at(id) = belowSeaLevel; + size_t min_size = id + 1; + if (sea_sectors.size() < min_size) + sea_sectors.resize(min_size); + sea_sectors.at(id) = below_sea_level; // Make sure we don't rebuild this mesh if any of the tiles are dirty - haveMesh(id, botLeft, topRight); + have_mesh(id, bot_left, top_right); } // A special rendering mode when selecting tiles -void Map::renderPickSector(Point botLeft, Point topRight) +void Map::render_pick_sector(Point bot_left, Point top_right) { glColor3f(1.0f, 1.0f, 1.0f); - for (int x = topRight.x-1; x >= botLeft.x; x--) { - for (int y = botLeft.y; y < topRight.y; y++) { + for (int x = top_right.x-1; x >= bot_left.x; x--) { + for (int y = bot_left.y; y < top_right.y; y++) { // Name this tile - glPushName(tileName(x, y)); + glPushName(tile_name(x, y)); int indexes[4]; - tileVertices(x, y, indexes); + tile_vertices(x, y, indexes); glBegin(GL_QUADS); for (int i = 0; i < 4; i++) { - const Vertex& v = heightMap[indexes[i]]; + const Vertex& v = height_map[indexes[i]]; glNormal3f(v.normal.x, v.normal.y, v.normal.z); glVertex3f(v.pos.x, v.pos.y, v.pos.z); } @@ -785,114 +787,114 @@ void Map::renderPickSector(Point botLeft, Point topRight) } // Render a small part of the map as directed by the quad tree -void Map::renderSector(IGraphicsPtr aContext, int id, - Point botLeft, Point topRight) +void Map::render_sector(IGraphicsPtr a_context, int id, + Point bot_left, Point top_right) { - if (inPickMode) { - renderPickSector(botLeft, topRight); + if (in_pick_mode) { + render_pick_sector(bot_left, top_right); return; } - if (!haveMesh(id, botLeft, topRight)) - buildMesh(id, botLeft, topRight); + if (!have_mesh(id, bot_left, top_right)) + build_mesh(id, bot_left, top_right); { // Parts of track may extend outside the sector so these // are clipped off - const float x = botLeft.x - 0.5f; - const float w = quadTree->leafSize(); - const float z = botLeft.y - 0.5f; - const float d = quadTree->leafSize(); + const float x = bot_left.x - 0.5f; + const float w = quad_tree->leaf_size(); + const float z = bot_left.y - 0.5f; + const float d = quad_tree->leaf_size(); ClipVolume clip(x, w, z, d); - terrainMeshes[id]->render(); + terrain_meshes[id]->render(); } // Draw the overlays - for (int x = topRight.x-1; x >= botLeft.x; x--) { - for (int y = botLeft.y; y < topRight.y; y++) { + for (int x = top_right.x-1; x >= bot_left.x; x--) { + for (int y = bot_left.y; y < top_right.y; y++) { //for (int i = 0; i < 4; i++) { - // const Vertex& v = heightMap[indexes[i]]; - // drawNormal(v.pos, v.normal); + // const Vertex& v = height_map[indexes[i]]; + // draw_normal(v.pos, v.normal); //} - if (shouldDrawGridLines) { + if (should_draw_gridLines) { // Render grid lines glColor3f(0.0f, 0.0f, 0.0f); glBegin(GL_LINE_LOOP); int indexes[4]; - tileVertices(x, y, indexes); + tile_vertices(x, y, indexes); for (int i = 0; i < 4; i++) { - const Vertex& v = heightMap[indexes[i]]; + const Vertex& v = height_map[indexes[i]]; glVertex3f(v.pos.x, v.pos.y, v.pos.z); } glEnd(); } - Tile& tile = tileAt(x, y); + Tile& tile = tile_at(x, y); - if (tile.track && tile.track->needsRendering(frameNum)) { + if (tile.track && tile.track->needs_rendering(frame_num)) { #if 0 // Draw the endpoints for debugging vector > tiles; - tile.track->get()->getEndpoints(tiles); + tile.track->get()->get_endpoints(tiles); for_each(tiles.begin(), tiles.end(), - bind(&Map::highlightTile, this, placeholders::_1, - makeColour(0.9f, 0.1f, 0.1f))); + bind(&Map::highlight_tile, this, placeholders::_1, + make_colour(0.9f, 0.1f, 0.1f))); tiles.clear(); - tile.track->get()->getCovers(tiles); + tile.track->get()->get_covers(tiles); for_each(tiles.begin(), tiles.end(), - bind(&Map::highlightTile, this, placeholders::_1, - makeColour(0.4f, 0.7f, 0.1f))); + bind(&Map::highlight_tile, this, placeholders::_1, + make_colour(0.4f, 0.7f, 0.1f))); #endif // Draw track highlights tile.track->get()->render(); - tile.track->renderedOn(frameNum); + tile.track->rendered_on(frame_num); } // Draw the station, if any if (tile.station - && (shouldDrawGridLines || tile.station->highlightVisible())) - highlightTile(makePoint(x, y), tile.station->highlightColour()); + && (should_draw_gridLines || tile.station->highlight_visible())) + highlight_tile(make_point(x, y), tile.station->highlight_colour()); // Draw the start location if it's on this tile - if (startLocation.x == x && startLocation.y == y - && shouldDrawGridLines) - drawStartLocation(); + if (start_location.x == x && start_location.y == y + && should_draw_gridLines) + draw_start_location(); } } } // Render the semi-transparent overlays such as water -void Map::postRenderSector(IGraphicsPtr aContext, int id, - Point botLeft, Point topRight) +void Map::post_render_sector(IGraphicsPtr a_context, int id, + Point bot_left, Point top_right) { // Draw the water - if (!inPickMode && seaSectors.at(id)) { + if (!in_pick_mode && sea_sectors.at(id)) { glPushAttrib(GL_ENABLE_BIT); glEnable(GL_BLEND); glDisable(GL_TEXTURE_2D); - const float blX = static_cast(botLeft.x); - const float blY = static_cast(botLeft.y); - const float trX = static_cast(topRight.x); - const float trY = static_cast(topRight.y); + const float blX = static_cast(bot_left.x); + const float blY = static_cast(bot_left.y); + const float trX = static_cast(top_right.x); + const float trY = static_cast(top_right.y); - static const float seaLevel = -0.6f; + static const float sea_level = -0.6f; gl::colour(makeRGB(0, 80, 160, 150)); glNormal3f(0.0f, 1.0f, 0.0f); glBegin(GL_QUADS); - glVertex3f(blX - 0.5f, seaLevel, blY - 0.5f); - glVertex3f(blX - 0.5f, seaLevel, trY - 0.5f); - glVertex3f(trX - 0.5f, seaLevel, trY - 0.5f); - glVertex3f(trX - 0.5f, seaLevel, blY - 0.5f); + glVertex3f(blX - 0.5f, sea_level, blY - 0.5f); + glVertex3f(blX - 0.5f, sea_level, trY - 0.5f); + glVertex3f(trX - 0.5f, sea_level, trY - 0.5f); + glVertex3f(trX - 0.5f, sea_level, blY - 0.5f); glEnd(); glPopAttrib(); @@ -902,63 +904,63 @@ void Map::postRenderSector(IGraphicsPtr aContext, int id, // Called when we've changed the height of part of a tile // This readjusts all the normals and those of its neighbours // to point in the right direction -void Map::fixNormals(int x, int y) +void Map::fix_normals(int x, int y) { - if ((x < 0) || (y < 0) || (x >= myWidth) || (y >= myDepth)) + if ((x < 0) || (y < 0) || (x >= my_width) || (y >= my_depth)) return; int indexes[4]; - tileVertices(x, y, indexes); + tile_vertices(x, y, indexes); for (int n = 0; n < 4; n++) { const int i = indexes[n]; - Vertex& v = heightMap[i]; + Vertex& v = height_map[i]; Vector west, north, east, south; - bool haveWest = true, haveNorth = true, - haveEast = true, haveSouth = true; + bool have_west = true, have_north = true, + have_east = true, have_south = true; - if (i > 0 && i % (myWidth + 1) > 0) - west = heightAt(i-1).pos; + if (i > 0 && i % (my_width + 1) > 0) + west = height_at(i-1).pos; else - haveWest = false; + have_west = false; - if (i < (myWidth + 1) * myDepth - 1) - north = heightAt(i + (myWidth + 1)).pos; + if (i < (my_width + 1) * my_depth - 1) + north = height_at(i + (my_width + 1)).pos; else - haveNorth = false; + have_north = false; - if (i < (myWidth + 1) * (myDepth + 1) - 1 - && i % (myWidth + 1) < myWidth) - east = heightAt(i + 1).pos; + if (i < (my_width + 1) * (my_depth + 1) - 1 + && i % (my_width + 1) < my_width) + east = height_at(i + 1).pos; else - haveEast = false; + have_east = false; - if (i > (myWidth + 1)) - south = heightAt(i - (myWidth + 1)).pos; + if (i > (my_width + 1)) + south = height_at(i - (my_width + 1)).pos; else - haveSouth = false; + have_south = false; float count = 4.0f; - Vector avg = makeVector(0.0f, 0.0f, 0.0f); + Vector avg = make_vector(0.0f, 0.0f, 0.0f); - if (haveWest && haveNorth) - avg += surfaceNormal(north, v.pos, west); + if (have_west && have_north) + avg += surface_normal(north, v.pos, west); else count -= 1.0f; - if (haveEast && haveNorth) - avg += surfaceNormal(east, v.pos, north); + if (have_east && have_north) + avg += surface_normal(east, v.pos, north); else count -= 1.0f; - if (haveSouth && haveEast) - avg += surfaceNormal(south, v.pos, east); + if (have_south && have_east) + avg += surface_normal(south, v.pos, east); else count -= 1.0f; - if (haveWest && haveSouth) - avg += surfaceNormal(west, v.pos, south); + if (have_west && have_south) + avg += surface_normal(west, v.pos, south); else count -= 1.0f; @@ -967,100 +969,100 @@ void Map::fixNormals(int x, int y) } // Find the terrain vertices that border a tile -void Map::tileVertices(int x, int y, int* indexes) const +void Map::tile_vertices(int x, int y, int* indexes) const { - assert(x >= 0 && x < myWidth && y >= 0 && y < myDepth); + assert(x >= 0 && x < my_width && y >= 0 && y < my_depth); - indexes[3] = x + (y * (myWidth+1)); // (X, Y) - indexes[2] = (x+1) + (y * (myWidth+1)); // (X+1, Y) - indexes[1] = (x+1) + ((y+1) * (myWidth+1)); // (X+1, Y+1) - indexes[0] = x + ((y+1) * (myWidth+1)); // (X, Y+1) + indexes[3] = x + (y * (my_width+1)); // (X, Y) + indexes[2] = (x+1) + (y * (my_width+1)); // (X+1, Y) + indexes[1] = (x+1) + ((y+1) * (my_width+1)); // (X+1, Y+1) + indexes[0] = x + ((y+1) * (my_width+1)); // (X, Y+1) } // True if changing the height of this tile will affect // a piece of track -bool Map::raiseWillCoverTrack(int x, int y) const +bool Map::raise_will_coverTrack(int x, int y) const { - return tileAt(x, y).track - || (x < myWidth - 1 && tileAt(x + 1, y).track) - || (x > 0 && tileAt(x - 1, y).track) - || (y < myDepth - 1 && tileAt(x, y + 1).track) - || (y > 0 && tileAt(x, y - 1).track) - || (x < myWidth - 1 && y < myDepth - 1 && tileAt(x + 1, y + 1).track) - || (x > 0 && y < myDepth - 1 && tileAt(x - 1, y + 1).track) - || (x > 0 && y > 0 && tileAt(x - 1, y - 1).track) - || (x < myWidth - 1 && y > 0 && tileAt(x + 1, y - 1).track); + return tile_at(x, y).track + || (x < my_width - 1 && tile_at(x + 1, y).track) + || (x > 0 && tile_at(x - 1, y).track) + || (y < my_depth - 1 && tile_at(x, y + 1).track) + || (y > 0 && tile_at(x, y - 1).track) + || (x < my_width - 1 && y < my_depth - 1 && tile_at(x + 1, y + 1).track) + || (x > 0 && y < my_depth - 1 && tile_at(x - 1, y + 1).track) + || (x > 0 && y > 0 && tile_at(x - 1, y - 1).track) + || (x < my_width - 1 && y > 0 && tile_at(x + 1, y - 1).track); } // Changes the height of a complete tile -void Map::raiseTile(int x, int y, float deltaHeight) +void Map::raise_tile(int x, int y, float delta_height) { - if (raiseWillCoverTrack(x, y)) { + if (raise_will_coverTrack(x, y)) { warn() << "Cannot raise terrain over track"; return; } int indexes[4]; - tileVertices(x, y, indexes); + tile_vertices(x, y, indexes); for (int i = 0; i < 4; i++) - heightMap[indexes[i]].pos.y += deltaHeight; + height_map[indexes[i]].pos.y += delta_height; - fixNormals(x, y); - dirtyTile(x, y); + fix_normals(x, y); + dirty_tile(x, y); } // Sets the absolute height of a tile -void Map::setTileHeight(int x, int y, float h) +void Map::set_tile_height(int x, int y, float h) { - bool trackAffected = raiseWillCoverTrack(x, y); + bool track_affected = raise_will_coverTrack(x, y); int indexes[4]; - tileVertices(x, y, indexes); + tile_vertices(x, y, indexes); for (int i = 0; i < 4; i++) { - if (trackAffected - && abs(heightMap[indexes[i]].pos.y - h) > 0.01f) { + if (track_affected + && abs(height_map[indexes[i]].pos.y - h) > 0.01f) { warn() << "Cannot level terrain under track"; return; } else - heightMap[indexes[i]].pos.y = h; + height_map[indexes[i]].pos.y = h; } - fixNormals(x, y); - dirtyTile(x, y); + fix_normals(x, y); + dirty_tile(x, y); } -float Map::heightAt(float x, float y) const +float Map::height_at(float x, float y) const { - const int xFloor = static_cast(floorf(x)); - const int yFloor = static_cast(floorf(y)); + const int x_floor = static_cast(floorf(x)); + const int y_floor = static_cast(floorf(y)); - return heightAt(makePoint(xFloor, yFloor)); + return height_at(make_point(x_floor, y_floor)); } -float Map::heightAt(Point where) const +float Map::height_at(Point where) const { if (where.x < 0 || where.y < 0 - || where.x >= myWidth || where.y >= myDepth) + || where.x >= my_width || where.y >= my_depth) return 0.0f; int indexes[4]; - tileVertices(where.x, where.y, indexes); + tile_vertices(where.x, where.y, indexes); float avg = 0.0f; for (int i = 0; i < 4; i++) - avg += heightMap[indexes[i]].pos.y; + avg += height_map[indexes[i]].pos.y; return avg / 4.0f; } -Vector Map::slopeAt(Point where, +Vector Map::slope_at(Point where, track::Direction axis, bool &level) const { int indexes[4]; - tileVertices(where.x, where.y, indexes); + tile_vertices(where.x, where.y, indexes); // This is slightly consfusing since the track Y axis // is the Z axis in the height map @@ -1068,18 +1070,18 @@ Vector Map::slopeAt(Point where, Vector v1, v2; if (axis == axis::X) { - v1 = heightMap[indexes[2]].pos - heightMap[indexes[3]].pos; - v2 = heightMap[indexes[1]].pos - heightMap[indexes[0]].pos; + v1 = height_map[indexes[2]].pos - height_map[indexes[3]].pos; + v2 = height_map[indexes[1]].pos - height_map[indexes[0]].pos; } else { - v1 = heightMap[indexes[0]].pos - heightMap[indexes[3]].pos; - v2 = heightMap[indexes[1]].pos - heightMap[indexes[2]].pos; + v1 = height_map[indexes[0]].pos - height_map[indexes[3]].pos; + v2 = height_map[indexes[1]].pos - height_map[indexes[2]].pos; } - level = v1.approxEqual(v2, 0.001f); + level = v1.approx_equal(v2, 0.001f); #if 0 - debug() << "slopeAt where=" << where + debug() << "slope_at where=" << where << " axis=" << axis << " v1=" << v1 << " v2=" << v2 << " level=" << level; @@ -1088,93 +1090,93 @@ Vector Map::slopeAt(Point where, return v1; } -Vector Map::slopeBefore(Point where, +Vector Map::slope_before(Point where, track::Direction axis, bool &valid) const { Point before; if (axis == axis::X) - before = where + makePoint(-1, 0); + before = where + make_point(-1, 0); else - before = where + makePoint(0, -1); + before = where + make_point(0, -1); - const bool offEdge = + const bool off_edge = (axis == axis::X && before.x < 0) || (axis == axis::Y && before.y < 0); - valid = !offEdge; + valid = !off_edge; - if (offEdge) - return makeVector(0.0f, 0.0f, 0.0f); + if (off_edge) + return make_vector(0.0f, 0.0f, 0.0f); else { bool ignored; - return slopeAt(before, axis, ignored); + return slope_at(before, axis, ignored); } } -Vector Map::slopeAfter(Point where, +Vector Map::slope_after(Point where, track::Direction axis, bool &valid) const { Point after; if (axis == axis::X) - after = where + makePoint(1, 0); + after = where + make_point(1, 0); else - after = where + makePoint(0, 1); + after = where + make_point(0, 1); - const bool offEdge = + const bool off_edge = (axis == axis::X && after.x >= width()) || (axis == axis::Y && after.y >= depth()); - valid = !offEdge; + valid = !off_edge; - if (offEdge) - return makeVector(0.0f, 0.0f, 0.0f); + if (off_edge) + return make_vector(0.0f, 0.0f, 0.0f); else { bool ignored; - return slopeAt(after, axis, ignored); + return slope_at(after, axis, ignored); } } -void Map::changeAreaHeight(const Point& aStartPos, - const Point& aFinishPos, - float aHeightDelta) +void Map::change_area_height(const Point& a_start_pos, + const Point& a_finish_pos, + float a_height_delta) { - const int xmin = min(aStartPos.x, aFinishPos.x); - const int xmax = max(aStartPos.x, aFinishPos.x); + const int xmin = min(a_start_pos.x, a_finish_pos.x); + const int xmax = max(a_start_pos.x, a_finish_pos.x); - const int ymin = min(aStartPos.y, aFinishPos.y); - const int ymax = max(aStartPos.y, aFinishPos.y); + const int ymin = min(a_start_pos.y, a_finish_pos.y); + const int ymax = max(a_start_pos.y, a_finish_pos.y); for (int x = xmin; x <= xmax; x++) { for (int y = ymin; y <= ymax; y++) - raiseTile(x, y, aHeightDelta); + raise_tile(x, y, a_height_delta); } } -void Map::levelArea(Point aStartPos, Point aFinishPos) +void Map::level_area(Point a_start_pos, Point a_finish_pos) { - const int xmin = min(aStartPos.x, aFinishPos.x); - const int xmax = max(aStartPos.x, aFinishPos.x); + const int xmin = min(a_start_pos.x, a_finish_pos.x); + const int xmax = max(a_start_pos.x, a_finish_pos.x); - const int ymin = min(aStartPos.y, aFinishPos.y); - const int ymax = max(aStartPos.y, aFinishPos.y); + const int ymin = min(a_start_pos.y, a_finish_pos.y); + const int ymax = max(a_start_pos.y, a_finish_pos.y); int indexes[4]; - tileVertices(aStartPos.x, aStartPos.y, indexes); + tile_vertices(a_start_pos.x, a_start_pos.y, indexes); - float avgHeight = 0.0f; + float avg_height = 0.0f; for (int i = 0; i < 4; i++) - avgHeight += heightMap[indexes[i]].pos.y; - avgHeight /= 4.0f; + avg_height += height_map[indexes[i]].pos.y; + avg_height /= 4.0f; for (int x = xmin; x <= xmax; x++) { for (int y = ymin; y <= ymax; y++) - setTileHeight(x, y, avgHeight); + set_tile_height(x, y, avg_height); } } -void Map::smoothArea(Point start, Point finish) +void Map::smooth_area(Point start, Point finish) { const int xmin = min(start.x, finish.x); const int xmax = max(start.x, finish.x); @@ -1184,33 +1186,33 @@ void Map::smoothArea(Point start, Point finish) Point step; if (xmin == xmax) - step = makePoint(0, 1); + step = make_point(0, 1); else if (ymin == ymax) - step = makePoint(1, 0); + step = make_point(1, 0); else { warn() << "Can only smooth strips"; return; } - const Point absStart = makePoint(xmin, ymin); - const Point absFinish = makePoint(xmax, ymax); + const Point abs_start = make_point(xmin, ymin); + const Point abs_finish = make_point(xmax, ymax); - const float heightStart = heightAt(absStart); - const float heightFinish = heightAt(absFinish); + const float height_start = height_at(abs_start); + const float height_finish = height_at(abs_finish); - setTileHeight(absStart.x, absStart.y, heightStart); - setTileHeight(absFinish.x, absFinish.y, heightFinish); + set_tile_height(abs_start.x, abs_start.y, height_start); + set_tile_height(abs_finish.x, abs_finish.y, height_finish); const float drop = - (heightStart - heightFinish) / (xmax + ymax - xmin - ymin); + (height_start - height_finish) / (xmax + ymax - xmin - ymin); debug() << "drop=" << drop; int i = 0; - for (Point it = absStart; it != absFinish; i++, it += step) { - const bool trackAffected = raiseWillCoverTrack(it.x, it.y); + for (Point it = abs_start; it != abs_finish; i++, it += step) { + const bool track_affected = raise_will_coverTrack(it.x, it.y); int indexes[4]; - tileVertices(it.x, it.y, indexes); + tile_vertices(it.x, it.y, indexes); int targets[2]; if (xmin == xmax) { @@ -1223,70 +1225,70 @@ void Map::smoothArea(Point start, Point finish) } for (int j = 0; j < 2; j++) { - const float newHeight = heightStart - (i * drop); + const float new_height = height_start - (i * drop); - if (trackAffected - && abs(heightMap[indexes[targets[j]]].pos.y - newHeight) > 0.01f) { + if (track_affected + && abs(height_map[indexes[targets[j]]].pos.y - new_height) > 0.01f) { warn() << "Cannot change terrain under track"; return; } else - heightMap[indexes[targets[j]]].pos.y = newHeight; + height_map[indexes[targets[j]]].pos.y = new_height; } - fixNormals(it.x, it.y); - dirtyTile(it.x, it.y); + fix_normals(it.x, it.y); + dirty_tile(it.x, it.y); } } -void Map::raiseArea(const Point& aStartPos, - const Point& aFinishPos) +void Map::raise_area(const Point& a_start_pos, + const Point& a_finish_pos) { - changeAreaHeight(aStartPos, aFinishPos, 0.1f); + change_area_height(a_start_pos, a_finish_pos, 0.1f); } -void Map::lowerArea(const Point& aStartPos, - const Point& aFinishPos) +void Map::lower_area(const Point& a_start_pos, + const Point& a_finish_pos) { - changeAreaHeight(aStartPos, aFinishPos, -0.1f); + change_area_height(a_start_pos, a_finish_pos, -0.1f); } -void Map::addScenery(Point where, ISceneryPtr s) +void Map::add_scenery(Point where, ISceneryPtr s) { - if (tileAt(where.x, where.y).track) + if (tile_at(where.x, where.y).track) warn() << "Cannot place scenery on track"; else { - tileAt(where.x, where.y).scenery = s; - s->setPosition(static_cast(where.x), - heightAt(where), + tile_at(where.x, where.y).scenery = s; + s->set_position(static_cast(where.x), + height_at(where), static_cast(where.y)); - dirtyTile(where.x, where.y); + dirty_tile(where.x, where.y); } } // Either extend an existing station which borders this area // or build a new station -IStationPtr Map::extendStation(Point aStartPos, Point aFinishPos) +IStationPtr Map::extend_station(Point a_start_pos, Point a_finish_pos) { - const int xmin = min(aStartPos.x, aFinishPos.x); - const int xmax = max(aStartPos.x, aFinishPos.x); + const int xmin = min(a_start_pos.x, a_finish_pos.x); + const int xmax = max(a_start_pos.x, a_finish_pos.x); - const int ymin = min(aStartPos.y, aFinishPos.y); - const int ymax = max(aStartPos.y, aFinishPos.y); + const int ymin = min(a_start_pos.y, a_finish_pos.y); + const int ymax = max(a_start_pos.y, a_finish_pos.y); // Find all the tiles containing track in this region typedef list > PointList; - PointList trackInArea; + PointList track_in_area; for (int x = xmin; x <= xmax; x++) { for (int y = ymin; y <= ymax; y++) { - if (tileAt(x, y).track) - trackInArea.push_back(makePoint(x, y)); + if (tile_at(x, y).track) + track_in_area.push_back(make_point(x, y)); } } - if (trackInArea.empty()) { + if (track_in_area.empty()) { warn() << "Stations must be placed on track"; return IStationPtr(); } @@ -1294,24 +1296,24 @@ IStationPtr Map::extendStation(Point aStartPos, Point aFinishPos) IStationPtr station; // See if any of these track segments are adjacent to a station - for (PointList::const_iterator it = trackInArea.begin(); - it != trackInArea.end(); ++it) { + for (PointList::const_iterator it = track_in_area.begin(); + it != track_in_area.end(); ++it) { const Point near[] = { - makePoint(0, 0), - makePoint(1, 0), - makePoint(0, 1), - makePoint(-1, 0), - makePoint(0, -1) + make_point(0, 0), + make_point(1, 0), + make_point(0, 1), + make_point(-1, 0), + make_point(0, -1) }; for (int i = 0; i < 5; i++) { Point neighbour = *it + near[i]; - if (neighbour.x >= 0 && neighbour.x < myWidth - && neighbour.y >= 0 && neighbour.y < myDepth - && tileAt(neighbour.x, neighbour.y).station) { + if (neighbour.x >= 0 && neighbour.x < my_width + && neighbour.y >= 0 && neighbour.y < my_depth + && tile_at(neighbour.x, neighbour.y).station) { - IStationPtr candidate = tileAt(neighbour.x, neighbour.y).station; + IStationPtr candidate = tile_at(neighbour.x, neighbour.y).station; // Maybe extend this station if (station && station != candidate) { @@ -1331,12 +1333,12 @@ IStationPtr Map::extendStation(Point aStartPos, Point aFinishPos) else { debug() << "Creating new station"; - station = makeStation(); + station = make_station(); } - for (PointList::iterator it = trackInArea.begin(); - it != trackInArea.end(); ++it) - tileAt((*it).x, (*it).y).station = station; + for (PointList::iterator it = track_in_area.begin(); + it != track_in_area.end(); ++it) + tile_at((*it).x, (*it).y).station = station; return station; } @@ -1346,24 +1348,24 @@ IStationPtr Map::extendStation(Point aStartPos, Point aFinishPos) // Bytes 0-3 Width of map // Bytes 4-7 Depth of map // Bytes 8+ Raw height data -void Map::writeHeightMap() const +void Map::write_height_map() const { using namespace boost; - IResource::Handle h = resource->writeFile(resource->name() + ".bin"); + IResource::Handle h = resource->write_file(resource->name() + ".bin"); - log() << "Writing terrain height map to " << h.fileName(); + log() << "Writing terrain height map to " << h.file_name(); try { ofstream& of = h.wstream(); - const int32_t wl = static_cast(myWidth); - const int32_t dl = static_cast(myDepth); + const int32_t wl = static_cast(my_width); + const int32_t dl = static_cast(my_depth); of.write(reinterpret_cast(&wl), sizeof(int32_t)); of.write(reinterpret_cast(&dl), sizeof(int32_t)); - for (int i = 0; i < (myWidth + 1) * (myDepth + 1); i++) - of.write(reinterpret_cast(&heightMap[i].pos.y), + for (int i = 0; i < (my_width + 1) * (my_depth + 1); i++) + of.write(reinterpret_cast(&height_map[i].pos.y), sizeof(float)); } catch (std::exception& e) { @@ -1373,115 +1375,115 @@ void Map::writeHeightMap() const } // Read the height data back out of a binary file -void Map::readHeightMap(IResource::Handle aHandle) +void Map::read_height_map(IResource::Handle a_handle) { using namespace boost; - log() << "Reading height map from " << aHandle.fileName(); + log() << "Reading height map from " << a_handle.file_name(); - istream& is = aHandle.rstream(); + istream& is = a_handle.rstream(); // Check the dimensions of the binary file match the XML file int32_t wl, dl; is.read(reinterpret_cast(&wl), sizeof(int32_t)); is.read(reinterpret_cast(&dl), sizeof(int32_t)); - if (wl != myWidth || dl != myDepth) { - error() << "Expected width " << myWidth << " got " << wl; - error() << "Expected height " << myDepth << " got " << dl; + if (wl != my_width || dl != my_depth) { + error() << "Expected width " << my_width << " got " << wl; + error() << "Expected height " << my_depth << " got " << dl; throw runtime_error - ("Binary file " + aHandle.fileName() + " dimensions are incorrect"); + ("Binary file " + a_handle.file_name() + " dimensions are incorrect"); } - for (int i = 0; i < (myWidth + 1) * (myDepth + 1); i++) - is.read(reinterpret_cast(&heightMap[i].pos.y), + for (int i = 0; i < (my_width + 1) * (my_depth + 1); i++) + is.read(reinterpret_cast(&height_map[i].pos.y), sizeof(float)); - for (int x = 0; x < myWidth; x++) { - for (int y = 0; y < myDepth; y++) - fixNormals(x, y); + for (int x = 0; x < my_width; x++) { + for (int y = 0; y < my_depth; y++) + fix_normals(x, y); } } -void Map::saveTo(ostream& of) +void Map::save_to(ostream& of) { xml::element root("map"); - root.addAttribute("width", myWidth); - root.addAttribute("height", myDepth); + root.add_attribute("width", my_width); + root.add_attribute("height", my_depth); - root.addChild(xml::element("name").addText("No Name")); + root.add_child(xml::element("name").add_text("No Name")); - root.addChild + root.add_child (xml::element("start") - .addAttribute("x", startLocation.x) - .addAttribute("y", startLocation.y) - .addAttribute("dirX", startDirection.x) - .addAttribute("dirY", startDirection.z)); + .add_attribute("x", start_location.x) + .add_attribute("y", start_location.y) + .add_attribute("dirX", start_direction.x) + .add_attribute("dirY", start_direction.z)); // Write out all the stations - set seenStations; + set seen_stations; - for (int x = 0; x < myWidth; x++) { - for (int y = 0; y < myDepth; y++) { - IStationPtr s = tileAt(x, y).station; + for (int x = 0; x < my_width; x++) { + for (int y = 0; y < my_depth; y++) { + IStationPtr s = tile_at(x, y).station; - if (s && seenStations.find(s) == seenStations.end()) { + if (s && seen_stations.find(s) == seen_stations.end()) { // Not seen this station before - root.addChild + root.add_child (xml::element("station") - .addAttribute("id", s->id()) - .addChild(xml::element("name").addText(s->name()))); + .add_attribute("id", s->id()) + .add_child(xml::element("name").add_text(s->name()))); - seenStations.insert(s); + seen_stations.insert(s); } } } // Generate the height map - writeHeightMap(); + write_height_map(); - root.addChild + root.add_child (xml::element("heightmap") - .addText(resource->name() + ".bin")); + .add_text(resource->name() + ".bin")); xml::element tileset("tileset"); - for (int x = 0; x < myWidth; x++) { - for (int y = 0; y < myDepth; y++) { - const Tile& tile = tileAt(x, y); + for (int x = 0; x < my_width; x++) { + for (int y = 0; y < my_depth; y++) { + const Tile& tile = tile_at(x, y); bool useful = false; - xml::element tileXml("tile"); + xml::element tile_xml("tile"); - tileXml.addAttribute("x", x); - tileXml.addAttribute("y", y); + tile_xml.add_attribute("x", x); + tile_xml.add_attribute("y", y); if (tile.track && tile.track->originX() == x && tile.track->originY() == y) { - tileXml.addChild(tile.track->get()->toXml()); + tile_xml.add_child(tile.track->get()->to_xml()); useful = true; } if (tile.station) { - tileXml.addChild - (xml::element("stationPart") - .addAttribute("id", tile.station->id())); + tile_xml.add_child + (xml::element("station_part") + .add_attribute("id", tile.station->id())); useful = true; } if (tile.scenery) { - tileXml.addChild(tile.scenery->toXml()); + tile_xml.add_child(tile.scenery->to_xml()); useful = true; } if (useful) - tileset.addChild(tileXml); + tileset.add_child(tile_xml); } } - root.addChild(tileset); + root.add_child(tileset); of << xml::document(root); } @@ -1491,14 +1493,14 @@ void Map::save() { using namespace boost::filesystem; - IResource::Handle h = resource->writeFile(resource->name() + ".xml"); + IResource::Handle h = resource->write_file(resource->name() + ".xml"); - log() << "Saving map to " << h.fileName(); + log() << "Saving map to " << h.file_name(); ofstream& of = h.wstream(); try { - saveTo(of); + save_to(of); } catch (exception& e) { h.rollback(); @@ -1506,12 +1508,12 @@ void Map::save() } } -IMapPtr makeEmptyMap(const string& aResId, int aWidth, int aDepth) +IMapPtr make_empty_map(const string& a_res_id, int a_width, int a_depth) { - IResourcePtr res = makeNewResource(aResId, "maps"); + IResourcePtr res = make_new_resource(a_res_id, "maps"); shared_ptr ptr(new Map(res)); - ptr->resetMap(aWidth, aDepth); + ptr->reset_map(a_width, a_depth); ptr->save(); return IMapPtr(ptr); } @@ -1519,89 +1521,88 @@ IMapPtr makeEmptyMap(const string& aResId, int aWidth, int aDepth) // Build a map through XML callbacks class MapLoader : public IXMLCallback { public: - MapLoader(shared_ptr aMap, IResourcePtr aRes) - : myMap(aMap), tile(makePoint(0, 0)), - resource(aRes) {} + MapLoader(shared_ptr a_map, IResourcePtr a_res) + : my_map(a_map), tile(make_point(0, 0)), + resource(a_res) {} - void startElement(const std::string& localName, - const AttributeSet& attrs) + void start_element(const string& local_name, const AttributeSet& attrs) { - if (localName == "map") - handleMap(attrs); - else if (localName == "tile") - handleTile(attrs); - else if (localName == "start") - handleStart(attrs); - else if (localName == "straightTrack") - handleStraightTrack(attrs); - else if (localName == "curvedTrack") - handleCurvedTrack(attrs); - else if (localName == "crossoverTrack") - handleCrossoverTrack(attrs); - else if (localName == "points") - handlePoints(attrs); - else if (localName == "slopeTrack") - handleSlopeTrack(attrs); - else if (localName == "sbendTrack") + if (local_name == "map") + handle_map(attrs); + else if (local_name == "tile") + handle_tile(attrs); + else if (local_name == "start") + handle_start(attrs); + else if (local_name == "straightTrack") + handle_straight_track(attrs); + else if (local_name == "curvedTrack") + handle_curved_track(attrs); + else if (local_name == "crossoverTrack") + handle_crossover_track(attrs); + else if (local_name == "points") + handle_points(attrs); + else if (local_name == "slopeTrack") + handle_slope_track(attrs); + else if (local_name == "sbendTrack") handleSBendTrack(attrs); - else if (localName == "stationPart") - handleStationPart(attrs); - else if (localName == "station") - handleStation(attrs); - else if (localName == "building") - handleBuilding(attrs); - else if (localName == "tree") - handleTree(attrs); + else if (local_name == "stationPart") + handle_station_part(attrs); + else if (local_name == "station") + handle_station(attrs); + else if (local_name == "building") + handle_building(attrs); + else if (local_name == "tree") + handle_tree(attrs); } - void endElement(const string& localName) + void end_element(const string& local_name) { - if (localName == "station") - myActiveStation.reset(); + if (local_name == "station") + my_active_station.reset(); } - void text(const string& localName, const string& aString) + void text(const string& local_name, const string& a_string) { - if (localName == "heightmap") - myMap->readHeightMap(resource->openFile(aString)); - else if (myActiveStation) { - if (localName == "name") - myActiveStation->setName(aString); + if (local_name == "heightmap") + my_map->read_height_map(resource->open_file(a_string)); + else if (my_active_station) { + if (local_name == "name") + my_active_station->set_name(a_string); } } private: - void handleMap(const AttributeSet& attrs) + void handle_map(const AttributeSet& attrs) { int width, height; attrs.get("width", width); attrs.get("height", height); - myMap->resetMap(width, height); + my_map->reset_map(width, height); } - void handleBuilding(const AttributeSet& attrs) + void handle_building(const AttributeSet& attrs) { - myMap->addScenery(tile, loadBuilding(attrs)); + my_map->add_scenery(tile, load_building(attrs)); } - void handleTree(const AttributeSet& attrs) + void handle_tree(const AttributeSet& attrs) { - myMap->addScenery(tile, loadTree(attrs)); + my_map->add_scenery(tile, load_tree(attrs)); } - void handleStation(const AttributeSet& attrs) + void handle_station(const AttributeSet& attrs) { - myActiveStation = makeStation(); + my_active_station = make_station(); int id; attrs.get("id", id); - myActiveStation->setId(id); + my_active_station->set_id(id); - myStations[id] = myActiveStation; + my_stations[id] = my_active_station; } - void handleStart(const AttributeSet& attrs) + void handle_start(const AttributeSet& attrs) { int x, y, dirX, dirY; attrs.get("x", x); @@ -1609,39 +1610,39 @@ private: attrs.get("dirX", dirX); attrs.get("dirY", dirY); - myMap->setStart(x, y, dirX, dirY); + my_map->set_start(x, y, dirX, dirY); } - void handleTile(const AttributeSet& attrs) + void handle_tile(const AttributeSet& attrs) { attrs.get("x", tile.x); attrs.get("y", tile.y); } - void handleStationPart(const AttributeSet& attrs) + void handle_station_part(const AttributeSet& attrs) { int id; attrs.get("id", id); - map::iterator it = myStations.find(id); - if (it == myStations.end()) + map::iterator it = my_stations.find(id); + if (it == my_stations.end()) throw runtime_error("No station definition for ID " + boost::lexical_cast(id)); else - myMap->setStationAt(tile, (*it).second); + my_map->set_station_at(tile, (*it).second); } - void handleStraightTrack(const AttributeSet& attrs) + void handle_straight_track(const AttributeSet& attrs) { string align; attrs.get("align", align); track::Direction axis = align == "x" ? axis::X : axis::Y; - myMap->setTrackAt(tile, makeStraightTrack(axis)); + my_map->set_track_at(tile, make_straight_track(axis)); } - void handleSlopeTrack(const AttributeSet& attrs) + void handle_slope_track(const AttributeSet& attrs) { string align; attrs.get("align", align); @@ -1649,17 +1650,17 @@ private: track::Direction axis = align == "x" ? axis::X : axis::Y; bool level; - Vector slope = myMap->slopeAt(tile, axis, level); + Vector slope = my_map->slope_at(tile, axis, level); - bool aValid, bValid; - Vector slopeBefore = myMap->slopeBefore(tile, axis, bValid); - Vector slopeAfter = myMap->slopeAfter(tile, axis, aValid); + bool a_valid, b_valid; + Vector slope_before = my_map->slope_before(tile, axis, b_valid); + Vector slope_after = my_map->slope_after(tile, axis, a_valid); - if (!aValid || !bValid || !level) + if (!a_valid || !b_valid || !level) throw runtime_error("SlopeTrack in invalid location"); - myMap->setTrackAt(tile, - makeSlopeTrack(axis, slope, slopeBefore, slopeAfter)); + my_map->set_track_at(tile, + make_slope_track(axis, slope, slope_before, slope_after)); } void handleSBendTrack(const AttributeSet attrs) @@ -1673,10 +1674,10 @@ private: attrs.get("offset", offset); attrs.get("straight", straight); - myMap->setTrackAt(tile, makeSBend(axis, straight, offset)); + my_map->set_track_at(tile, makeSBend(axis, straight, offset)); } - void handlePoints(const AttributeSet& attrs) + void handle_points(const AttributeSet& attrs) { string align; attrs.get("align", align); @@ -1689,44 +1690,44 @@ private: : (align == "-x" ? -axis::X : (align == "y" ? axis::Y : -axis::Y)); - myMap->setTrackAt(tile, makePoints(dir, reflect)); + my_map->set_track_at(tile, make_points(dir, reflect)); } - void handleCurvedTrack(const AttributeSet& attrs) + void handle_curved_track(const AttributeSet& attrs) { - int startAngle, finishAngle, radius; - attrs.get("startAngle", startAngle); - attrs.get("finishAngle", finishAngle); + int start_angle, finish_angle, radius; + attrs.get("start_angle", start_angle); + attrs.get("finish_angle", finish_angle); attrs.get("radius", radius); - myMap->setTrackAt(tile, makeCurvedTrack(startAngle, finishAngle, radius)); + my_map->set_track_at(tile, make_curved_track(start_angle, finish_angle, radius)); } - void handleCrossoverTrack(const AttributeSet& attrs) + void handle_crossover_track(const AttributeSet& attrs) { - myMap->setTrackAt(tile, makeCrossoverTrack()); + my_map->set_track_at(tile, make_crossover_track()); } - shared_ptr myMap; - map myStations; - IStationPtr myActiveStation; + shared_ptr my_map; + map my_stations; + IStationPtr my_active_station; Point tile; IResourcePtr resource; }; -IMapPtr loadMap(const string& aResId) +IMapPtr load_map(const string& a_res_id) { - IResourcePtr res = findResource(aResId, "maps"); + IResourcePtr res = find_resource(a_res_id, "maps"); shared_ptr map(new Map(res)); - log() << "Loading map from file " << res->xmlFileName(); + log() << "Loading map from file " << res->xml_file_name(); - static IXMLParserPtr xmlParser = makeXMLParser("schemas/map.xsd"); + static IXMLParserPtr xml_parser = makeXMLParser("schemas/map.xsd"); MapLoader loader(map, res); - xmlParser->parse(res->xmlFileName(), loader); + xml_parser->parse(res->xml_file_name(), loader); return IMapPtr(map); } diff --git a/src/Maths.cpp b/src/Maths.cpp index f57521c..b7072aa 100644 --- a/src/Maths.cpp +++ b/src/Maths.cpp @@ -21,8 +21,8 @@ #include // A utility function for debugging normal calculation -void drawNormal(const Vector& aPosition, - const Vector& aNormal) +void draw_normal(const Vector& a_position, + const Vector& a_normal) { glPushAttrib(GL_ENABLE_BIT); @@ -32,12 +32,12 @@ void drawNormal(const Vector& aPosition, glPushAttrib(GL_CURRENT_BIT); glColor3d(1.0, 0.0, 0.0); - Vector normPos = aPosition + aNormal; + Vector norm_pos = a_position + a_normal; glBegin(GL_LINES); - glVertex3d(aPosition.x, aPosition.y, aPosition.z); - glVertex3d(normPos.x, normPos.y, normPos.z); + glVertex3d(a_position.x, a_position.y, a_position.z); + glVertex3d(norm_pos.x, norm_pos.y, norm_pos.z); glEnd(); @@ -46,15 +46,15 @@ void drawNormal(const Vector& aPosition, } // A rough guess at the gradient at a point on a curve -float approxGradient(function aFunc, float x) +float approx_gradient(function a_func, float x) { const float delta = 0.01f; const float x1 = x - delta; const float x2 = x + delta; - const float y1 = aFunc(x1); - const float y2 = aFunc(x2); + const float y1 = a_func(x1); + const float y2 = a_func(x2); return (y2 - y1) / (x2 - x1); } diff --git a/src/Mesh.cpp b/src/Mesh.cpp index eb93aad..f92d44f 100644 --- a/src/Mesh.cpp +++ b/src/Mesh.cpp @@ -32,8 +32,8 @@ using namespace boost; namespace { - int frameCounter = 0; - int triangleCount = 0; + int frame_counter = 0; + int triangle_count = 0; } // Concrete implementation of mesh buffers @@ -41,31 +41,31 @@ struct MeshBuffer : IMeshBuffer { MeshBuffer(); ~MeshBuffer() {} - size_t vertexCount() const { return vertices.size(); } + size_t vertex_count() const { return vertices.size(); } void add(const Vertex& vertex, const Normal& normal); void add(const Vertex& vertex, const Normal& normal, - const TexCoord& aTexCoord); + const TexCoord& a_tex_coord); void add(const Vertex& vertex, const Normal& normal, const Colour& colour); - void addQuad(Vertex a, Vertex b, Vertex c, Vertex d, + void add_quad(Vertex a, Vertex b, Vertex c, Vertex d, Colour colour); - void addQuad(Vertex a, Vertex b, Vertex c, Vertex d, + void add_quad(Vertex a, Vertex b, Vertex c, Vertex d, Normal na, Normal nb, Normal nc, Normal nd, Colour colour); - void bindMaterial(const Material& aMaterial); - void merge(IMeshBufferPtr other, Vector off, float yAngle); + void bind_material(const Material& a_material); + void merge(IMeshBufferPtr other, Vector off, float y_angle); - void printStats() const; + void print_stats() const; - static MeshBuffer* get(IMeshBufferPtr aPtr) + static MeshBuffer* get(IMeshBufferPtr a_ptr) { - return polymorphic_cast(aPtr.get()); + return polymorphic_cast(a_ptr.get()); } - static bool mergeVector(const Vector& v1, const Vector& v2) + static bool merge_vector(const Vector& v1, const Vector& v2) { const float tolerance = 0.001f; @@ -78,26 +78,26 @@ struct MeshBuffer : IMeshBuffer { vector normals; vector colours; vector indices; - vector texCoords; - bool hasTexture, hasMaterial; + vector tex_coords; + bool has_texture, has_material; Material material; int reused; }; MeshBuffer::MeshBuffer() - : hasTexture(false), hasMaterial(false), reused(0) + : has_texture(false), has_material(false), reused(0) { } -void MeshBuffer::bindMaterial(const Material& aMaterial) +void MeshBuffer::bind_material(const Material& a_material) { - material = aMaterial; - hasTexture = aMaterial.texture; - hasMaterial = true; + material = a_material; + has_texture = a_material.texture; + has_material = true; } -void MeshBuffer::merge(IMeshBufferPtr other, Vector off, float yAngle) +void MeshBuffer::merge(IMeshBufferPtr other, Vector off, float y_angle) { const MeshBuffer& obuf = dynamic_cast(*other); @@ -106,7 +106,7 @@ void MeshBuffer::merge(IMeshBufferPtr other, Vector off, float yAngle) const Matrix translate = Matrix::translation(off.x, off.y, off.z); const Matrix rotate = - Matrix::rotation(yAngle, 0.0f, 1.0f, 0.0f); + Matrix::rotation(y_angle, 0.0f, 1.0f, 0.0f); const Matrix compose = translate * rotate; @@ -117,7 +117,7 @@ void MeshBuffer::merge(IMeshBufferPtr other, Vector off, float yAngle) vertices.push_back(compose.transform(v)); normals.push_back(rotate.transform(n).normalise()); - if (obuf.hasTexture) { + if (obuf.has_texture) { colours.push_back(colour::WHITE); } else { @@ -132,7 +132,7 @@ void MeshBuffer::merge(IMeshBufferPtr other, Vector off, float yAngle) } } -void MeshBuffer::printStats() const +void MeshBuffer::print_stats() const { debug() << "Mesh: " << vertices.size() << " vertices, " << reused << " reused"; @@ -140,19 +140,19 @@ void MeshBuffer::printStats() const void MeshBuffer::add(const Vertex& vertex, const Normal& normal) { - if (hasTexture) + if (has_texture) throw runtime_error("MeshBuffer::add called without texture coordinate " "on a mesh which has a texture"); - if (!hasMaterial) + if (!has_material) throw runtime_error("MeshBuffer::add called without colour on a mesh " " without a material"); // See if this vertex has already been added for (vector::iterator it = indices.begin(); it != indices.end(); ++it) { - if (mergeVector(vertex, vertices[*it]) - && mergeVector(normal, normals[*it])) { + if (merge_vector(vertex, vertices[*it]) + && merge_vector(normal, normals[*it])) { const Colour& other = colours[*it]; if (abs(other.r - material.diffuseR) < 0.01f @@ -171,7 +171,7 @@ void MeshBuffer::add(const Vertex& vertex, const Normal& normal) normals.push_back(normal); indices.push_back(index); colours.push_back( - makeColour(material.diffuseR, + make_colour(material.diffuseR, material.diffuseG, material.diffuseB)); } @@ -179,19 +179,19 @@ void MeshBuffer::add(const Vertex& vertex, const Normal& normal) void MeshBuffer::add(const Vertex& vertex, const Normal& normal, const Colour& colour) { - if (hasTexture) + if (has_texture) throw runtime_error("MeshBuffer::add called without texture coordinate " "on a mesh which has a texture"); - if (hasMaterial) + if (has_material) throw runtime_error("MeshBuffer::add called with a colour on a mesh " " with a material"); // See if this vertex has already been added for (vector::iterator it = indices.begin(); it != indices.end(); ++it) { - if (mergeVector(vertex, vertices[*it]) - && mergeVector(normal, normals[*it])) { + if (merge_vector(vertex, vertices[*it]) + && merge_vector(normal, normals[*it])) { const Colour& other = colours[*it]; if (abs(other.r - colour.r) < 0.01f @@ -213,9 +213,9 @@ void MeshBuffer::add(const Vertex& vertex, const Normal& normal, } void MeshBuffer::add(const Vertex& vertex, const Normal& normal, - const TexCoord& aTexCoord) + const TexCoord& a_tex_coord) { - if (!hasTexture) + if (!has_texture) throw runtime_error( "MeshBuffer::add called with a texture coordinate " "on a mesh without a texture"); @@ -223,11 +223,11 @@ void MeshBuffer::add(const Vertex& vertex, const Normal& normal, // See if this vertex has already been added for (vector::iterator it = indices.begin(); it != indices.end(); ++it) { - if (mergeVector(vertex, vertices[*it]) - && mergeVector(normal, normals[*it])) { - TexCoord& tc = texCoords[*it]; - if (abs(tc.x - aTexCoord.x) < 0.001f - && abs(tc.y - aTexCoord.y) < 0.001f) { + if (merge_vector(vertex, vertices[*it]) + && merge_vector(normal, normals[*it])) { + TexCoord& tc = tex_coords[*it]; + if (abs(tc.x - a_tex_coord.x) < 0.001f + && abs(tc.y - a_tex_coord.y) < 0.001f) { indices.push_back(*it); reused++; return; @@ -238,15 +238,15 @@ void MeshBuffer::add(const Vertex& vertex, const Normal& normal, const size_t index = vertices.size(); vertices.push_back(vertex); normals.push_back(normal); - texCoords.push_back(aTexCoord); + tex_coords.push_back(a_tex_coord); indices.push_back(index); } -void MeshBuffer::addQuad(Vertex a, Vertex b, Vertex c, +void MeshBuffer::add_quad(Vertex a, Vertex b, Vertex c, Vertex d, Colour colour) { - Vector n1 = surfaceNormal(b, c, d); - Vector n2 = surfaceNormal(d, a, b); + Vector n1 = surface_normal(b, c, d); + Vector n2 = surface_normal(d, a, b); add(b, n1, colour); add(c, n1, colour); @@ -257,7 +257,7 @@ void MeshBuffer::addQuad(Vertex a, Vertex b, Vertex c, add(b, n2, colour); } -void MeshBuffer::addQuad(Vertex a, Vertex b, Vertex c, Vertex d, +void MeshBuffer::add_quad(Vertex a, Vertex b, Vertex c, Vertex d, Normal na, Normal nb, Normal nc, Normal nd, Colour colour) { @@ -310,23 +310,23 @@ void Material::apply() const // Simple implementation using display lists class DisplayListMesh : public IMesh { public: - DisplayListMesh(IMeshBufferPtr aBuffer); + DisplayListMesh(IMeshBufferPtr a_buffer); ~DisplayListMesh(); void render() const; private: - GLuint myDisplayList; + GLuint my_display_list; }; -DisplayListMesh::DisplayListMesh(IMeshBufferPtr aBuffer) +DisplayListMesh::DisplayListMesh(IMeshBufferPtr a_buffer) { - myDisplayList = glGenLists(1); + my_display_list = glGenLists(1); - glNewList(myDisplayList, GL_COMPILE); + glNewList(my_display_list, GL_COMPILE); - const MeshBuffer* buf = MeshBuffer::get(aBuffer); + const MeshBuffer* buf = MeshBuffer::get(a_buffer); - if (buf->hasMaterial) + if (buf->has_material) buf->material.apply(); else glEnable(GL_COLOR_MATERIAL); @@ -337,7 +337,7 @@ DisplayListMesh::DisplayListMesh(IMeshBufferPtr aBuffer) for (it = buf->indices.begin(); it != buf->indices.end(); ++it) { - if (!buf->hasMaterial) { + if (!buf->has_material) { gl::colour(buf->colours[*it]); } @@ -354,7 +354,7 @@ DisplayListMesh::DisplayListMesh(IMeshBufferPtr aBuffer) it != buf->indices.end(); ++it) { const MeshBuffer::Vertex& v = buf->vertices[*it]; const MeshBuffer::Normal& n = buf->normals[*it]; - drawNormal(v, n); + draw_normal(v, n); } glEndList(); @@ -362,7 +362,7 @@ DisplayListMesh::DisplayListMesh(IMeshBufferPtr aBuffer) DisplayListMesh::~DisplayListMesh() { - glDeleteLists(myDisplayList, 1); + glDeleteLists(my_display_list, 1); } void DisplayListMesh::render() const @@ -372,7 +372,7 @@ void DisplayListMesh::render() const glDisable(GL_BLEND); glEnable(GL_CULL_FACE); - glCallList(myDisplayList); + glCallList(my_display_list); glPopAttrib(); } @@ -390,10 +390,10 @@ BOOST_STATIC_ASSERT(sizeof(VertexData) == 64); namespace { // Get the vertex data out of a mesh buffer into a VertexData array - void copyVertexData(const MeshBuffer* buf, VertexData* vertexData) + void copy_vertex_data(const MeshBuffer* buf, VertexData* vertex_data) { for (size_t i = 0; i < buf->vertices.size(); i++) { - VertexData* vd = &vertexData[i]; + VertexData* vd = &vertex_data[i]; vd->x = buf->vertices[i].x; vd->y = buf->vertices[i].y; @@ -403,9 +403,9 @@ namespace { vd->ny = buf->normals[i].y; vd->nz = buf->normals[i].z; - if (buf->hasTexture) { - vd->tx = buf->texCoords[i].x; - vd->ty = 1.0f - buf->texCoords[i].y; + if (buf->has_texture) { + vd->tx = buf->tex_coords[i].x; + vd->ty = 1.0f - buf->tex_coords[i].y; } else { vd->r = buf->colours[i].r; @@ -419,43 +419,43 @@ namespace { // Implementation of meshes using client side vertex arrays class VertexArrayMesh : public IMesh { public: - VertexArrayMesh(IMeshBufferPtr aBuffer); + VertexArrayMesh(IMeshBufferPtr a_buffer); ~VertexArrayMesh(); void render() const; private: Material material; - bool hasMaterial, hasTexture; - size_t myVertexCount; - VertexData* myVertexData; - size_t myIndexCount; - GLushort* myIndices; + bool has_material, has_texture; + size_t my_vertex_count; + VertexData* my_vertex_data; + size_t my_index_count; + GLushort* my_indices; }; -VertexArrayMesh::VertexArrayMesh(IMeshBufferPtr aBuffer) +VertexArrayMesh::VertexArrayMesh(IMeshBufferPtr a_buffer) { - const MeshBuffer* buf = MeshBuffer::get(aBuffer); + const MeshBuffer* buf = MeshBuffer::get(a_buffer); material = buf->material; - hasMaterial = buf->hasMaterial; - hasTexture = buf->hasTexture; + has_material = buf->has_material; + has_texture = buf->has_texture; - myVertexCount = buf->vertices.size(); - myVertexData = new VertexData[myVertexCount]; + my_vertex_count = buf->vertices.size(); + my_vertex_data = new VertexData[my_vertex_count]; - copyVertexData(buf, myVertexData); + copy_vertex_data(buf, my_vertex_data); - myIndexCount = buf->indices.size(); - myIndices = new GLushort[myIndexCount]; + my_index_count = buf->indices.size(); + my_indices = new GLushort[my_index_count]; - copy(buf->indices.begin(), buf->indices.end(), myIndices); + copy(buf->indices.begin(), buf->indices.end(), my_indices); } VertexArrayMesh::~VertexArrayMesh() { - delete[] myVertexData; - delete[] myIndices; + delete[] my_vertex_data; + delete[] my_indices; } void VertexArrayMesh::render() const @@ -465,31 +465,31 @@ void VertexArrayMesh::render() const glDisable(GL_BLEND); - if (hasMaterial) + if (has_material) material.apply(); else { glEnable(GL_COLOR_MATERIAL); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(3, GL_FLOAT, sizeof(VertexData), - reinterpret_cast(&myVertexData->r)); + reinterpret_cast(&my_vertex_data->r)); } - if (hasTexture) { + if (has_texture) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(VertexData), - reinterpret_cast(&myVertexData->tx)); + reinterpret_cast(&my_vertex_data->tx)); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(VertexData), - reinterpret_cast(myVertexData)); + reinterpret_cast(my_vertex_data)); glNormalPointer(GL_FLOAT, sizeof(VertexData), - reinterpret_cast(&myVertexData->nx)); + reinterpret_cast(&my_vertex_data->nx)); - glDrawElements(GL_TRIANGLES, static_cast(myIndexCount), - GL_UNSIGNED_SHORT, myIndices); + glDrawElements(GL_TRIANGLES, static_cast(my_index_count), + GL_UNSIGNED_SHORT, my_indices); glPopClientAttrib(); glPopAttrib(); @@ -498,63 +498,63 @@ void VertexArrayMesh::render() const // Implementation of meshes using server side VBOs class VBOMesh : public IMesh { public: - VBOMesh(IMeshBufferPtr aBuffer); + VBOMesh(IMeshBufferPtr a_buffer); ~VBOMesh(); void render() const; private: - GLuint vboBuf, indexBuf; + GLuint vbo_buf, index_buf; ITexturePtr texture; - size_t indexCount; + size_t index_count; }; -VBOMesh::VBOMesh(IMeshBufferPtr aBuffer) +VBOMesh::VBOMesh(IMeshBufferPtr a_buffer) { // Get the data out of the buffer; - const MeshBuffer* buf = MeshBuffer::get(aBuffer); + const MeshBuffer* buf = MeshBuffer::get(a_buffer); texture = buf->material.texture; - const size_t vertexCount = buf->vertices.size(); - VertexData* pVertexData = new VertexData[vertexCount]; + const size_t vertex_count = buf->vertices.size(); + VertexData* p_vertex_data = new VertexData[vertex_count]; - copyVertexData(buf, pVertexData); + copy_vertex_data(buf, p_vertex_data); // Generate the VBO - glGenBuffersARB(1, &vboBuf); - glBindBufferARB(GL_ARRAY_BUFFER, vboBuf); - glBufferDataARB(GL_ARRAY_BUFFER, vertexCount * sizeof(VertexData), + glGenBuffersARB(1, &vbo_buf); + glBindBufferARB(GL_ARRAY_BUFFER, vbo_buf); + glBufferDataARB(GL_ARRAY_BUFFER, vertex_count * sizeof(VertexData), NULL, GL_STATIC_DRAW); // Copy the vertex data in glBufferSubDataARB(GL_ARRAY_BUFFER, 0, - vertexCount * sizeof(VertexData), pVertexData); + vertex_count * sizeof(VertexData), p_vertex_data); // Copy the indices into a temporary array - indexCount = buf->indices.size(); - GLshort* pIndices = new GLshort[indexCount]; + index_count = buf->indices.size(); + GLshort* p_indices = new GLshort[index_count]; - copy(buf->indices.begin(), buf->indices.end(), pIndices); + copy(buf->indices.begin(), buf->indices.end(), p_indices); // Build the index buffer - glGenBuffersARB(1, &indexBuf); - glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, indexBuf); - glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(GLushort), + glGenBuffersARB(1, &index_buf); + glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, index_buf); + glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER, index_count * sizeof(GLushort), NULL, GL_STATIC_DRAW); glBufferSubDataARB(GL_ELEMENT_ARRAY_BUFFER, 0, - indexCount * sizeof(GLushort), pIndices); + index_count * sizeof(GLushort), p_indices); glBindBufferARB(GL_ARRAY_BUFFER, 0); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, 0); - delete[] pVertexData; - delete[] pIndices; + delete[] p_vertex_data; + delete[] p_indices; } VBOMesh::~VBOMesh() { - glDeleteBuffersARB(1, &vboBuf); - glDeleteBuffersARB(1, &indexBuf); + glDeleteBuffersARB(1, &vbo_buf); + glDeleteBuffersARB(1, &index_buf); } void VBOMesh::render() const @@ -565,8 +565,8 @@ void VBOMesh::render() const if (!glIsEnabled(GL_CULL_FACE)) glEnable(GL_CULL_FACE); - glBindBufferARB(GL_ARRAY_BUFFER, vboBuf); - glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, indexBuf); + glBindBufferARB(GL_ARRAY_BUFFER, vbo_buf); + glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, index_buf); if (glIsEnabled(GL_BLEND)) glDisable(GL_BLEND); @@ -598,39 +598,39 @@ void VBOMesh::render() const glVertexPointer(3, GL_FLOAT, sizeof(VertexData), reinterpret_cast(0)); - glDrawElements(GL_TRIANGLES, static_cast(indexCount), - GL_UNSIGNED_SHORT, 0); + glDrawElements(GL_TRIANGLES, static_cast(index_count), + GL_UNSIGNED_SHORT, 0); glPopClientAttrib(); glPopAttrib(); - ::triangleCount += indexCount / 3; + ::triangle_count += index_count / 3; } -IMeshPtr makeMesh(IMeshBufferPtr aBuffer) +IMeshPtr make_mesh(IMeshBufferPtr a_buffer) { - //aBuffer->printStats(); + //a_buffer->print_stats(); // Prefer VBOs for all meshes if (GLEW_ARB_vertex_buffer_object) - return IMeshPtr(new VBOMesh(aBuffer)); + return IMeshPtr(new VBOMesh(a_buffer)); else - return IMeshPtr(new VertexArrayMesh(aBuffer)); + return IMeshPtr(new VertexArrayMesh(a_buffer)); } -IMeshBufferPtr makeMeshBuffer() +IMeshBufferPtr make_mesh_buffer() { return IMeshBufferPtr(new MeshBuffer); } -void updateRenderStats() +void update_render_stats() { - ::frameCounter++; + ::frame_counter++; } -int getAverageTriangleCount() +int get_average_triangleCount() { - int avg = ::triangleCount / ::frameCounter; - ::triangleCount = ::frameCounter = 0; + int avg = ::triangle_count / ::frame_counter; + ::triangle_count = ::frame_counter = 0; return avg; } diff --git a/src/MessageArea.cpp b/src/MessageArea.cpp index 5fadc3f..c21a103 100644 --- a/src/MessageArea.cpp +++ b/src/MessageArea.cpp @@ -47,7 +47,7 @@ private: MessageArea::MessageArea() { - font = gui::loadFont("fonts/Vera.ttf", 18); + font = gui::load_font("fonts/Vera.ttf", 18); } void MessageArea::render() const @@ -55,8 +55,8 @@ void MessageArea::render() const if (active) { const string& text = active.get().text; - const int screenH = getGameWindow()->height(); - const int screenW = getGameWindow()->width(); + const int screenH = get_game_window()->height(); + const int screenW = get_game_window()->width(); const int len = font->text_width(text); float alpha = 1.0f; @@ -67,7 +67,7 @@ void MessageArea::render() const alpha = 1.0f - (static_cast(-delay) / FADE_OUT_TIME); } - const Colour col = makeColour(1.0f, 1.0f, 1.0f, alpha); + const Colour col = make_colour(1.0f, 1.0f, 1.0f, alpha); font->print((screenW - len)/2, screenH - 50, col, text); } @@ -93,7 +93,7 @@ void MessageArea::post(const string& mess, int priority, int delay) active = m; } -IMessageAreaPtr makeMessageArea() +IMessageAreaPtr make_message_area() { return IMessageAreaPtr(new MessageArea); } diff --git a/src/Model.cpp b/src/Model.cpp index b0348c3..342edfe 100644 --- a/src/Model.cpp +++ b/src/Model.cpp @@ -39,32 +39,32 @@ using namespace boost; // Cache of already loaded models namespace { typedef map ModelCache; - ModelCache theCache; + ModelCache the_cache; } // Abstracts a WaveFront material file class MaterialFile { public: - MaterialFile(const string& aFileName, IResourcePtr aRes); + MaterialFile(const string& a_file_name, IResourcePtr a_res); ~MaterialFile() {} - const Material& get(const string& aName) const; + const Material& get(const string& a_name) const; private: typedef map MaterialSet; - MaterialSet myMaterials; + MaterialSet my_materials; }; typedef std::tr1::shared_ptr MaterialFilePtr; -MaterialFile::MaterialFile(const string& aFileName, IResourcePtr aRes) +MaterialFile::MaterialFile(const string& a_file_name, IResourcePtr a_res) { - IResource::Handle h = aRes->openFile(aFileName); + IResource::Handle h = a_res->open_file(a_file_name); - log() << "Loading materials from " << h.fileName(); + log() << "Loading materials from " << h.file_name(); istream& is = h.rstream(); - string activeMaterial; + string active_material; while (!is.eof()) { string word; is >> word; @@ -74,28 +74,28 @@ MaterialFile::MaterialFile(const string& aFileName, IResourcePtr aRes) continue; } else if (word == "newmtl") { - is >> activeMaterial; + is >> active_material; - myMaterials[activeMaterial] = Material(); + my_materials[active_material] = Material(); } else if (word == "map_Kd") { // Texture is >> word; - myMaterials[activeMaterial].texture = loadTexture(aRes, word); + my_materials[active_material].texture = load_texture(a_res, word); } else if (word == "Kd") { // Diffuse colour - Material& m = myMaterials[activeMaterial]; + Material& m = my_materials[active_material]; is >> m.diffuseR >> m.diffuseG >> m.diffuseB; } else if (word == "Ka") { // Ambient colour - Material& m = myMaterials[activeMaterial]; + Material& m = my_materials[active_material]; is >> m.ambientR >> m.ambientG >> m.ambientB; } else if (word == "Ks") { // Specular colour - Material& m = myMaterials[activeMaterial]; + Material& m = my_materials[active_material]; is >> m.specularR >> m.specularG >> m.specularB; } else { @@ -105,11 +105,11 @@ MaterialFile::MaterialFile(const string& aFileName, IResourcePtr aRes) } } -const Material& MaterialFile::get(const string& aName) const +const Material& MaterialFile::get(const string& a_name) const { - MaterialSet::const_iterator it = myMaterials.find(aName); - if (it == myMaterials.end()) - throw runtime_error("No material named " + aName); + MaterialSet::const_iterator it = my_materials.find(a_name); + if (it == my_materials.end()) + throw runtime_error("No material named " + a_name); return (*it).second; } @@ -124,11 +124,11 @@ public: // IModel interface void render() const; void cache(); - void merge(IMeshBufferPtr into, Vector off, float yAngle) const; + void merge(IMeshBufferPtr into, Vector off, float y_angle) const; Vector dimensions() const { return dimensions_; } private: - void compileMesh() const; + void compile_mesh() const; Vector dimensions_; mutable IMeshPtr mesh; @@ -143,55 +143,55 @@ Model::~Model() void Model::cache() { if (!mesh) - compileMesh(); + compile_mesh(); } void Model::render() const { if (!mesh) - compileMesh(); + compile_mesh(); mesh->render(); } -void Model::merge(IMeshBufferPtr into, Vector off, float yAngle) const +void Model::merge(IMeshBufferPtr into, Vector off, float y_angle) const { - into->merge(buffer, off, yAngle); + into->merge(buffer, off, y_angle); } -void Model::compileMesh() const +void Model::compile_mesh() const { // Const as may be called during render - mesh = makeMesh(buffer); + mesh = make_mesh(buffer); } // Load a model from a resource -IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, float aScale) +IModelPtr load_model(IResourcePtr a_res, const string& a_file_name, float a_scale) { // Make a unique cache name - const string cacheName = aRes->name() + ":" + aFileName; + const string cache_name = a_res->name() + ":" + a_file_name; // Check the cache for the model - ModelCache::iterator it = theCache.find(cacheName); - if (it != theCache.end()) + ModelCache::iterator it = the_cache.find(cache_name); + if (it != the_cache.end()) return (*it).second; // Not in the cache, load it from the resource - IResource::Handle h = aRes->openFile(aFileName); - log() << "Loading model " << h.fileName(); + IResource::Handle h = a_res->open_file(a_file_name); + log() << "Loading model " << h.file_name(); vector vertices; vector normals; - vector textureOffs; + vector texture_offs; - IMeshBufferPtr buffer = makeMeshBuffer(); + IMeshBufferPtr buffer = make_mesh_buffer(); - bool foundVertex = false; + bool found_vertex = false; float ymin = 0, ymax = 0, xmin = 0, xmax = 0, zmin = 0, zmax = 0; - int faceCount = 0; + int face_count = 0; - MaterialFilePtr materialFile; + MaterialFilePtr material_file; ifstream& f = h.rstream(); @@ -204,27 +204,27 @@ IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, float aScale) } else if (first == "o") { // New object - string objName; - f >> objName; + string obj_name; + f >> obj_name; } else if (first == "mtllib") { // Material file - string fileName; - f >> fileName; + string file_name; + f >> file_name; - materialFile = - MaterialFilePtr(new MaterialFile(fileName, aRes)); + material_file = + MaterialFilePtr(new MaterialFile(file_name, a_res)); } else if (first == "v") { // Vertex float x, y, z; f >> x >> y >> z; - x *= aScale; - y *= aScale; - z *= aScale; + x *= a_scale; + y *= a_scale; + z *= a_scale; - if (foundVertex) { + if (found_vertex) { xmin = min(x, xmin); xmax = max(x, xmax); @@ -239,24 +239,24 @@ IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, float aScale) ymin = ymax = y; zmin = zmax = z; - foundVertex = true; + found_vertex = true; } - vertices.push_back(makeVector(x, y, z)); + vertices.push_back(make_vector(x, y, z)); } else if (first == "vn") { // Normal float x, y, z; f >> x >> y >> z; - normals.push_back(makeVector(x, y, z)); + normals.push_back(make_vector(x, y, z)); } else if (first == "vt") { // Texture coordinate float x, y; f >> x >> y; - textureOffs.push_back(makePoint(x, y)); + texture_offs.push_back(make_point(x, y)); } else if (first == "g") { // Groups used to correspond to sub-meshes but now @@ -264,12 +264,12 @@ IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, float aScale) } else if (first == "usemtl") { // Set the material for this group - string materialName; - f >> materialName; + string material_name; + f >> material_name; - if (materialFile) { + if (material_file) { assert(buffer); - buffer->bindMaterial(materialFile->get(materialName)); + buffer->bind_material(material_file->get(material_name)); } } else if (first == "f") { @@ -278,7 +278,7 @@ IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, float aScale) getline(f, line); istringstream ss(line); - int vInThisFace = 0; + int v_in_thisFace = 0; while (!ss.eof()) { char delim1, delim2; @@ -287,9 +287,9 @@ IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, float aScale) if (ss.fail()) break; - if (++vInThisFace > 3) + if (++v_in_thisFace > 3) warn () << "All model faces must be triangles " - << "(face with " << vInThisFace << " vertices)"; + << "(face with " << v_in_thisFace << " vertices)"; // Texture coordinate may be omitted ss >> vti; @@ -306,15 +306,15 @@ IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, float aScale) assert(buffer); - if (vti - 1 < textureOffs.size()) { - Point& vt = textureOffs[vti - 1]; + if (vti - 1 < texture_offs.size()) { + Point& vt = texture_offs[vti - 1]; buffer->add(v, vn, vt); } else buffer->add(v, vn); } - faceCount++; + face_count++; // Don't discard the next line continue; @@ -324,14 +324,14 @@ IModelPtr loadModel(IResourcePtr aRes, const string& aFileName, float aScale) getline(f, first); } - Vector dim = makeVector(xmax - xmin, ymax - ymin, zmax - zmin); + Vector dim = make_vector(xmax - xmin, ymax - ymin, zmax - zmin); log() << "Model loaded: " << vertices.size() << " vertices, " - << faceCount << " faces"; + << face_count << " faces"; IModelPtr ptr(new Model(dim, buffer)); - theCache[cacheName] = ptr; + the_cache[cache_name] = ptr; return ptr; } diff --git a/src/OpenGLHelper.cpp b/src/OpenGLHelper.cpp index 0a81428..c83fcc3 100644 --- a/src/OpenGLHelper.cpp +++ b/src/OpenGLHelper.cpp @@ -39,7 +39,7 @@ void checkGLError() } } -void drawGLScene(IWindowPtr aWindow, IGraphicsPtr aContext, IScreenPtr aScreen) +void drawGLScene(IWindowPtr a_window, IGraphicsPtr a_context, IScreenPtr a_screen) { using namespace boost; @@ -47,10 +47,10 @@ void drawGLScene(IWindowPtr aWindow, IGraphicsPtr aContext, IScreenPtr aScreen) glMatrixMode(GL_PROJECTION); glLoadIdentity(); - const int w = aWindow->width(); - const int h = aWindow->height(); + const int w = a_window->width(); + const int h = a_window->height(); - IConfigPtr cfg = getConfig(); + IConfigPtr cfg = get_config(); gluPerspective(45.0f, (GLfloat)w/(GLfloat)h, cfg->get("NearClip"), cfg->get("FarClip")); @@ -71,7 +71,7 @@ void drawGLScene(IWindowPtr aWindow, IGraphicsPtr aContext, IScreenPtr aScreen) glLoadIdentity(); // Draw the 3D part - aScreen->display(aContext); + a_screen->display(a_context); // Set up for 2D glMatrixMode(GL_PROJECTION); @@ -88,7 +88,7 @@ void drawGLScene(IWindowPtr aWindow, IGraphicsPtr aContext, IScreenPtr aScreen) glDisable(GL_CULL_FACE); // Draw the 2D part - aScreen->overlay(); + a_screen->overlay(); // Check for OpenGL errors checkGLError(); @@ -113,7 +113,7 @@ void initGL() glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Clear to the sky colour - //glClearColor(0.6f, 0.7f, 0.8f, 1.0f); + //glClear_color(0.6f, 0.7f, 0.8f, 1.0f); glClearColor(176.0f/255.0f, 196.0f/255.0f, 222.0f/255.0f, 1.0f); // Check for OpenGL extensions @@ -125,19 +125,19 @@ void initGL() } // Set the current viewport -void resizeGLScene(IWindowPtr aWindow) +void resizeGLScene(IWindowPtr a_window) { - glViewport(0, 0, aWindow->width(), aWindow->height()); + glViewport(0, 0, a_window->width(), a_window->height()); } -void beginPick(IWindowPtr aWindow, unsigned* aBuffer, int x, int y) +void begin_pick(IWindowPtr a_window, unsigned* a_buffer, int x, int y) { // Set up selection buffer - glSelectBuffer(128, aBuffer); + glSelectBuffer(128, a_buffer); // Get viewport coordinates - GLint viewportCoords[4]; - glGetIntegerv(GL_VIEWPORT, viewportCoords); + GLint viewport_coords[4]; + glGetIntegerv(GL_VIEWPORT, viewport_coords); // Switch to projection matrix glMatrixMode(GL_PROJECTION); @@ -148,11 +148,11 @@ void beginPick(IWindowPtr aWindow, unsigned* aBuffer, int x, int y) glLoadIdentity(); // Set picking matrix - gluPickMatrix(x, viewportCoords[3] - y, 2, 2, viewportCoords); + gluPickMatrix(x, viewport_coords[3] - y, 2, 2, viewport_coords); // Just set the perspective - IConfigPtr cfg = getConfig(); - gluPerspective(45.0f, (GLfloat)(aWindow->width())/(GLfloat)(aWindow->height()), + IConfigPtr cfg = get_config(); + gluPerspective(45.0f, (GLfloat)(a_window->width())/(GLfloat)(a_window->height()), cfg->get("NearClip"), cfg->get("FarClip")); @@ -163,9 +163,9 @@ void beginPick(IWindowPtr aWindow, unsigned* aBuffer, int x, int y) glLoadIdentity(); } -unsigned endPick(unsigned* aBuffer) +unsigned end_pick(unsigned* a_buffer) { - int objectsFound = glRenderMode(GL_RENDER); + int objects_found = glRenderMode(GL_RENDER); // Go back to normal glMatrixMode(GL_PROJECTION); @@ -173,22 +173,22 @@ unsigned endPick(unsigned* aBuffer) glMatrixMode(GL_MODELVIEW); // See if we found any objects - if (objectsFound > 0) { + if (objects_found > 0) { // Find the object with the lowest depth - unsigned int lowestDepth = aBuffer[1]; - int selectedObject = aBuffer[3]; + unsigned int lowest_depth = a_buffer[1]; + int selected_object = a_buffer[3]; // Go through all the objects found - for (int i = 1; i < objectsFound; i++) { + for (int i = 1; i < objects_found; i++) { // See if it's closer than the current nearest - if (aBuffer[(i*4) + 1] < lowestDepth) { // 4 values for each object - lowestDepth = aBuffer[(i * 4) + 1]; - selectedObject = aBuffer[(i * 4) + 3]; + if (a_buffer[(i*4) + 1] < lowest_depth) { // 4 values for each object + lowest_depth = a_buffer[(i * 4) + 1]; + selected_object = a_buffer[(i * 4) + 3]; } } // Return closest object - return selectedObject; + return selected_object; } else return 0; diff --git a/src/Points.cpp b/src/Points.cpp index 79d1127..1a7a337 100644 --- a/src/Points.cpp +++ b/src/Points.cpp @@ -33,77 +33,77 @@ class Points : public ITrackSegment, private SleeperHelper, private BezierHelper { public: - Points(track::Direction aDirection, bool reflect); + Points(track::Direction a_direction, bool reflect); // ITrackSegment interface void render() const; void merge(IMeshBufferPtr buf) const; - void setOrigin(int x, int y, float h) { myX = x; myY = y; height = h; } - float segmentLength(const track::TravelToken& aToken) const; - bool isValidDirection(const track::Direction& aDirection) const; - track::Connection nextPosition(const track::TravelToken& aToken) const; - void getEndpoints(vector >& aList) const; - void getCovers(vector >& output) const; - ITrackSegmentPtr mergeExit(Point where, track::Direction dir); - track::TravelToken getTravelToken(track::Position aPosition, - track::Direction aDirection) const; - void nextState(); - void prevState(); - bool hasMultipleStates() const { return true; } - void setStateRenderHint(); + void set_origin(int x, int y, float h) { myX = x; myY = y; height = h; } + float segment_length(const track::TravelToken& a_token) const; + bool is_valid_direction(const track::Direction& a_direction) const; + track::Connection next_position(const track::TravelToken& a_token) const; + void get_endpoints(vector >& a_list) const; + void get_covers(vector >& output) const; + ITrackSegmentPtr merge_exit(Point where, track::Direction dir); + track::TravelToken get_travel_token(track::Position a_position, + track::Direction a_direction) const; + void next_state(); + void prev_state(); + bool has_multiple_states() const { return true; } + void set_state_renderHint(); // IXMLSerialisable interface - xml::element toXml() const; + xml::element to_xml() const; private: - void transform(const track::TravelToken& aToken, float aDelta) const; - void ensureValidDirection(track::Direction aDirection) const; - void renderArrow() const; + void transform(const track::TravelToken& a_token, float a_delta) const; + void ensure_valid_direction(track::Direction a_direction) const; + void render_arrow() const; - Point displacedEndpoint() const; - Point straightEndpoint() const; + Point displaced_endpoint() const; + Point straight_endpoint() const; enum State { TAKEN, NOT_TAKEN }; int myX, myY; - track::Direction myAxis; + track::Direction my_axis; bool reflected; State state; float height; // Draw the arrow over the points if true - mutable bool stateRenderHint; + mutable bool state_render_hint; - static const BezierCurve myCurve, myReflectedCurve; + static const BezierCurve my_curve, my_reflected_curve; }; -const BezierCurve Points::myCurve = makeBezierCurve - (makeVector(0.0f, 0.0f, 0.0f), - makeVector(1.0f, 0.0f, 0.0f), - makeVector(2.0f, 0.0f, 1.0f), - makeVector(3.0f, 0.0f, 1.0f)); - -const BezierCurve Points::myReflectedCurve = makeBezierCurve - (makeVector(0.0f, 0.0f, 0.0f), - makeVector(1.0f, 0.0f, 0.0f), - makeVector(2.0f, 0.0f, -1.0f), - makeVector(3.0f, 0.0f, -1.0f)); +const BezierCurve Points::my_curve = make_bezier_curve + (make_vector(0.0f, 0.0f, 0.0f), + make_vector(1.0f, 0.0f, 0.0f), + make_vector(2.0f, 0.0f, 1.0f), + make_vector(3.0f, 0.0f, 1.0f)); + +const BezierCurve Points::my_reflected_curve = make_bezier_curve + (make_vector(0.0f, 0.0f, 0.0f), + make_vector(1.0f, 0.0f, 0.0f), + make_vector(2.0f, 0.0f, -1.0f), + make_vector(3.0f, 0.0f, -1.0f)); -Points::Points(track::Direction aDirection, bool reflect) +Points::Points(track::Direction a_direction, bool reflect) : myX(0), myY(0), - myAxis(aDirection), reflected(reflect), + my_axis(a_direction), reflected(reflect), state(NOT_TAKEN), height(0.0f), - stateRenderHint(false) + state_render_hint(false) { } -void Points::setStateRenderHint() +void Points::set_state_renderHint() { - stateRenderHint = true; + state_render_hint = true; } -void Points::renderArrow() const +void Points::render_arrow() const { glPushMatrix(); glPushAttrib(GL_ENABLE_BIT); @@ -113,30 +113,30 @@ void Points::renderArrow() const glTranslatef(-0.5f, 0.11f, 0.0f); glColor4f(0.2f, 0.1f, 0.9f, 0.7f); - const float headWidth = 0.25f; + const float head_width = 0.25f; if (state == TAKEN) { const BezierCurve& curve = - reflected ? myReflectedCurve : myCurve; + reflected ? my_reflected_curve : my_curve; const float step = 0.1f; - const float arrowLen = 0.7f; + const float arrow_len = 0.7f; glDisable(GL_CULL_FACE); - for (float t = 0.0f; t < arrowLen; t += step) { + for (float t = 0.0f; t < arrow_len; t += step) { const Vector v1 = curve(t); const Vector v2 = curve(t + step); - if (t >= arrowLen - step) { + if (t >= arrow_len - step) { // Arrow head glBegin(GL_TRIANGLES); { - glVertex3f(v1.x, 0.0f, v1.z - headWidth); + glVertex3f(v1.x, 0.0f, v1.z - head_width); glVertex3f(v2.x, 0.0f, v2.z); - glVertex3f(v1.x, 0.0f, v1.z + headWidth); + glVertex3f(v1.x, 0.0f, v1.z + head_width); } glEnd(); } @@ -153,13 +153,13 @@ void Points::renderArrow() const } } else { - const float headLength = 0.3f; + const float head_length = 0.3f; glBegin(GL_QUADS); { glVertex3f(0.0f, 0.0f, 0.1f); - glVertex3f(2.0f - headLength, 0.0f, 0.1f); - glVertex3f(2.0f - headLength, 0.0f, -0.1f); + glVertex3f(2.0f - head_length, 0.0f, 0.1f); + glVertex3f(2.0f - head_length, 0.0f, -0.1f); glVertex3f(0.0f, 0.0f, -0.1f); } glEnd(); @@ -167,9 +167,9 @@ void Points::renderArrow() const // Draw the arrow head glBegin(GL_TRIANGLES); { - glVertex3f(2.0f - headLength, 0.0f, headWidth); + glVertex3f(2.0f - head_length, 0.0f, head_width); glVertex3f(2.0f, 0.0f, 0.0f); - glVertex3f(2.0f - headLength, 0.0f, -headWidth); + glVertex3f(2.0f - head_length, 0.0f, -head_width); } glEnd(); } @@ -180,66 +180,66 @@ void Points::renderArrow() const void Points::merge(IMeshBufferPtr buf) const { - static IMeshBufferPtr railBuf = makeBezierRailMesh(myCurve); - static IMeshBufferPtr reflectBuf = makeBezierRailMesh(myReflectedCurve); + static IMeshBufferPtr rail_buf = make_bezier_railMesh(my_curve); + static IMeshBufferPtr reflect_buf = make_bezier_railMesh(my_reflected_curve); - Vector off = makeVector( + Vector off = make_vector( static_cast(myX), height, static_cast(myY)); - float yAngle = 0.0f; + float y_angle = 0.0f; - if (myAxis == -axis::X) - yAngle = 180.0f; - else if (myAxis == -axis::Y) - yAngle = 90.0f; - else if (myAxis == axis::Y) - yAngle = 270.0f; + if (my_axis == -axis::X) + y_angle = 180.0f; + else if (my_axis == -axis::Y) + y_angle = 90.0f; + else if (my_axis == axis::Y) + y_angle = 270.0f; // Render the rails - buf->merge(reflected ? reflectBuf : railBuf, - off + rotateY(makeVector(-0.5f, 0.0f, 0.0f), yAngle), - yAngle); + buf->merge(reflected ? reflect_buf : rail_buf, + off + rotateY(make_vector(-0.5f, 0.0f, 0.0f), y_angle), + y_angle); { Vector t = off; for (int i = 0; i < 3; i++) { - const float a = yAngle + 90.0f; - mergeStraightRail(buf, t, a); + const float a = y_angle + 90.0f; + merge_straight_rail(buf, t, a); - t += rotateY(makeVector(0.0f, 0.0f, 1.0f), a); + t += rotateY(make_vector(0.0f, 0.0f, 1.0f), a); } } // Draw the curved sleepers for (float i = 0.25f; i < 1.0f; i += 0.08f) { - Vector v = (reflected ? myReflectedCurve : myCurve)(i); + Vector v = (reflected ? my_reflected_curve : my_curve)(i); - Vector t = makeVector(v.x - 0.5f, 0.0f, v.z); - Vector soff = off + rotateY(t, yAngle); + Vector t = make_vector(v.x - 0.5f, 0.0f, v.z); + Vector soff = off + rotateY(t, y_angle); const Vector deriv = - (reflected ? myReflectedCurve : myCurve).deriv(i); + (reflected ? my_reflected_curve : my_curve).deriv(i); const float angle = - radToDeg(atanf(deriv.z / deriv.x)); + rad_to_deg(atanf(deriv.z / deriv.x)); - mergeSleeper(buf, soff, yAngle - angle); + merge_sleeper(buf, soff, y_angle - angle); } // Draw the straight sleepers - off -= rotateY(makeVector(0.4f, 0.0f, 0.0f), yAngle); + off -= rotateY(make_vector(0.4f, 0.0f, 0.0f), y_angle); for (int i = 0; i < 12; i++) { - mergeSleeper(buf, off, yAngle); - off += rotateY(makeVector(0.25f, 0.0f, 0.0f), yAngle); + merge_sleeper(buf, off, y_angle); + off += rotateY(make_vector(0.25f, 0.0f, 0.0f), y_angle); } } void Points::render() const { - if (stateRenderHint) { + if (state_render_hint) { glPushMatrix(); glTranslatef( @@ -247,149 +247,149 @@ void Points::render() const height, static_cast(myY)); - if (myAxis == -axis::X) + if (my_axis == -axis::X) glRotatef(180.0f, 0.0f, 1.0f, 0.0f); - else if (myAxis == -axis::Y) + else if (my_axis == -axis::Y) glRotatef(90.0f, 0.0f, 1.0f, 0.0f); - else if (myAxis == axis::Y) + else if (my_axis == axis::Y) glRotatef(270.0f, 0.0f, 1.0f, 0.0f); - renderArrow(); - stateRenderHint = false; + render_arrow(); + state_render_hint = false; glPopMatrix(); } } -float Points::segmentLength(const track::TravelToken& aToken) const +float Points::segment_length(const track::TravelToken& a_token) const { - if (aToken.position == displacedEndpoint()) - return myCurve.length; + if (a_token.position == displaced_endpoint()) + return my_curve.length; else return 3.0f; } -track::TravelToken Points::getTravelToken(track::Position position, +track::TravelToken Points::get_travel_token(track::Position position, track::Direction direction) const { using namespace placeholders; - ensureValidDirection(direction); + ensure_valid_direction(direction); - const int nExits = position.x == myX && position.y == myY ? 2 : 1; + const int n_exits = position.x == myX && position.y == myY ? 2 : 1; track::TravelToken tok = { direction, position, bind(&Points::transform, this, _1, _2), - track::flatGradientFunc, - nExits + track::flat_gradient_func, + n_exits }; return tok; } -void Points::transform(const track::TravelToken& aToken, float delta) const +void Points::transform(const track::TravelToken& a_token, float delta) const { - const float len = segmentLength(aToken); + const float len = segment_length(a_token); assert(delta < len); - if (myX == aToken.position.x && myY == aToken.position.y + if (myX == a_token.position.x && myY == a_token.position.y && state == NOT_TAKEN) { - if (aToken.direction == myAxis - && (myAxis == -axis::X || myAxis == -axis::Y)) + if (a_token.direction == my_axis + && (my_axis == -axis::X || my_axis == -axis::Y)) delta -= 1.0f; - const float xTrans = - myAxis == axis::X ? delta - : (myAxis == -axis::X ? -delta : 0.0f); - const float yTrans = - myAxis == axis::Y ? delta - : (myAxis == -axis::Y ? -delta : 0.0f); + const float x_trans = + my_axis == axis::X ? delta + : (my_axis == -axis::X ? -delta : 0.0f); + const float y_trans = + my_axis == axis::Y ? delta + : (my_axis == -axis::Y ? -delta : 0.0f); - glTranslatef(static_cast(myX) + xTrans, + glTranslatef(static_cast(myX) + x_trans, height, - static_cast(myY) + yTrans); + static_cast(myY) + y_trans); - if (myAxis == axis::Y || myAxis == -axis::Y) + if (my_axis == axis::Y || my_axis == -axis::Y) glRotated(-90.0, 0.0, 1.0, 0.0); glTranslated(-0.5, 0.0, 0.0); } - else if (aToken.position == straightEndpoint()) { + else if (a_token.position == straight_endpoint()) { delta = 2.0f - delta; - if (aToken.direction == -myAxis - && (myAxis == axis::X || myAxis == axis::Y)) + if (a_token.direction == -my_axis + && (my_axis == axis::X || my_axis == axis::Y)) delta += 1.0f; - const float xTrans = - myAxis == axis::X ? delta - : (myAxis == -axis::X ? -delta : 0.0f); - const float yTrans = - myAxis == axis::Y ? delta - : (myAxis == -axis::Y ? -delta : 0.0f); + const float x_trans = + my_axis == axis::X ? delta + : (my_axis == -axis::X ? -delta : 0.0f); + const float y_trans = + my_axis == axis::Y ? delta + : (my_axis == -axis::Y ? -delta : 0.0f); - glTranslatef(static_cast(myX) + xTrans, + glTranslatef(static_cast(myX) + x_trans, height, - static_cast(myY) + yTrans); + static_cast(myY) + y_trans); - if (myAxis == axis::Y || myAxis == -axis::Y) + if (my_axis == axis::Y || my_axis == -axis::Y) glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); glTranslatef(-0.5f, 0.0f, 0.0f); } - else if (aToken.position == displacedEndpoint() || state == TAKEN) { + else if (a_token.position == displaced_endpoint() || state == TAKEN) { // Curving onto the straight section - float xTrans, yTrans, rotate; + float x_trans, y_trans, rotate; // We have a slight problem in that the domain of the curve // function is [0,1] but the delta is in [0,len] so we have // to compress the delta into [0,1] here - const float curveDelta = delta / len; + const float curve_delta = delta / len; - bool backwards = aToken.position == displacedEndpoint(); + bool backwards = a_token.position == displaced_endpoint(); - const float fValue = backwards ? 1.0f - curveDelta : curveDelta; - const Vector curveValue = myCurve(fValue); + const float f_value = backwards ? 1.0f - curve_delta : curve_delta; + const Vector curve_value = my_curve(f_value); // Calculate the angle that the tangent to the curve at this // point makes to (one of) the axis at this point - const Vector deriv = myCurve.deriv(fValue); + const Vector deriv = my_curve.deriv(f_value); const float angle = - radToDeg(atanf(deriv.z / deriv.x)); + rad_to_deg(atanf(deriv.z / deriv.x)); - if (myAxis == -axis::X) { - xTrans = 1.0f - curveValue.x; - yTrans = reflected ? curveValue.z : -curveValue.z; + if (my_axis == -axis::X) { + x_trans = 1.0f - curve_value.x; + y_trans = reflected ? curve_value.z : -curve_value.z; rotate = reflected ? angle : -angle; } - else if (myAxis == axis::X) { - xTrans = curveValue.x; - yTrans = reflected ? -curveValue.z : curveValue.z; + else if (my_axis == axis::X) { + x_trans = curve_value.x; + y_trans = reflected ? -curve_value.z : curve_value.z; rotate = reflected ? angle : -angle; } - else if (myAxis == -axis::Y) { - xTrans = reflected ? -curveValue.z : curveValue.z; - yTrans = 1.0f - curveValue.x; + else if (my_axis == -axis::Y) { + x_trans = reflected ? -curve_value.z : curve_value.z; + y_trans = 1.0f - curve_value.x; rotate = reflected ? angle : -angle; } - else if (myAxis == axis::Y) { - xTrans = reflected ? curveValue.z: -curveValue.z; - yTrans = curveValue.x; + else if (my_axis == axis::Y) { + x_trans = reflected ? curve_value.z: -curve_value.z; + y_trans = curve_value.x; rotate = reflected ? angle : -angle; } else assert(false); glTranslatef( - static_cast(myX) + xTrans, + static_cast(myX) + x_trans, height, - static_cast(myY) + yTrans); + static_cast(myY) + y_trans); - if (myAxis == axis::Y || myAxis == -axis::Y) + if (my_axis == axis::Y || my_axis == -axis::Y) glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); glTranslatef(-0.5f, 0.0f, 0.0f); @@ -399,98 +399,98 @@ void Points::transform(const track::TravelToken& aToken, float delta) const else assert(false); - if (aToken.direction == -axis::X || aToken.direction == -axis::Y) + if (a_token.direction == -axis::X || a_token.direction == -axis::Y) glRotated(-180.0, 0.0, 1.0, 0.0); } -void Points::ensureValidDirection(track::Direction aDirection) const +void Points::ensure_valid_direction(track::Direction a_direction) const { - if (!isValidDirection(aDirection)) + if (!is_valid_direction(a_direction)) throw runtime_error ("Invalid direction on points: " - + boost::lexical_cast(aDirection) + + boost::lexical_cast(a_direction) + " (should be parallel to " - + boost::lexical_cast(myAxis) + ")"); + + boost::lexical_cast(my_axis) + ")"); } -bool Points::isValidDirection(const track::Direction& aDirection) const +bool Points::is_valid_direction(const track::Direction& a_direction) const { - if (myAxis == axis::X || myAxis == -axis::X) - return aDirection == axis::X || -aDirection == axis::X; + if (my_axis == axis::X || my_axis == -axis::X) + return a_direction == axis::X || -a_direction == axis::X; else - return aDirection == axis::Y || -aDirection == axis::Y; + return a_direction == axis::Y || -a_direction == axis::Y; } -track::Connection Points::nextPosition(const track::TravelToken& aToken) const +track::Connection Points::next_position(const track::TravelToken& a_token) const { const bool branching = state == TAKEN; - if (myAxis == axis::X) { - if (aToken.direction == -axis::X) { + if (my_axis == axis::X) { + if (a_token.direction == -axis::X) { // Two possible entry points - return make_pair(makePoint(myX - 1, myY), -axis::X); + return make_pair(make_point(myX - 1, myY), -axis::X); } else { // Two possible exits if (branching) { if (reflected) - return make_pair(makePoint(myX + 3, myY - 1), axis::X); + return make_pair(make_point(myX + 3, myY - 1), axis::X); else - return make_pair(makePoint(myX + 3, myY + 1), axis::X); + return make_pair(make_point(myX + 3, myY + 1), axis::X); } else - return make_pair(makePoint(myX + 3, myY), axis::X); + return make_pair(make_point(myX + 3, myY), axis::X); } } - else if (myAxis == -axis::X) { - if (aToken.direction == -axis::X) { + else if (my_axis == -axis::X) { + if (a_token.direction == -axis::X) { // Two possible exits if (branching) { if (reflected) - return make_pair(makePoint(myX - 3, myY + 1), -axis::X); + return make_pair(make_point(myX - 3, myY + 1), -axis::X); else - return make_pair(makePoint(myX - 3, myY - 1), -axis::X); + return make_pair(make_point(myX - 3, myY - 1), -axis::X); } else - return make_pair(makePoint(myX - 3, myY), -axis::X); + return make_pair(make_point(myX - 3, myY), -axis::X); } else { // Two possible entry points - return make_pair(makePoint(myX + 1, myY), axis::X); + return make_pair(make_point(myX + 1, myY), axis::X); } } - else if (myAxis == axis::Y) { - if (aToken.direction == -axis::Y) { + else if (my_axis == axis::Y) { + if (a_token.direction == -axis::Y) { // Two possible entry points - return make_pair(makePoint(myX, myY - 1), -axis::Y); + return make_pair(make_point(myX, myY - 1), -axis::Y); } else { // Two possible exits if (branching) { if (reflected) - return make_pair(makePoint(myX + 1, myY + 3), axis::Y); + return make_pair(make_point(myX + 1, myY + 3), axis::Y); else - return make_pair(makePoint(myX - 1, myY + 3), axis::Y); + return make_pair(make_point(myX - 1, myY + 3), axis::Y); } else - return make_pair(makePoint(myX, myY + 3), axis::Y); + return make_pair(make_point(myX, myY + 3), axis::Y); } } - else if (myAxis == -axis::Y) { - if (aToken.direction == -axis::Y) { + else if (my_axis == -axis::Y) { + if (a_token.direction == -axis::Y) { // Two possible exits if (branching) { if (reflected) - return make_pair(makePoint(myX - 1, myY - 3), -axis::Y); + return make_pair(make_point(myX - 1, myY - 3), -axis::Y); else - return make_pair(makePoint(myX + 1, myY - 3), -axis::Y); + return make_pair(make_point(myX + 1, myY - 3), -axis::Y); } else - return make_pair(makePoint(myX, myY - 3), -axis::Y); + return make_pair(make_point(myX, myY - 3), -axis::Y); } else { // Two possible entry points - return make_pair(makePoint(myX, myY + 1), axis::Y); + return make_pair(make_point(myX, myY + 1), axis::Y); } } else @@ -498,96 +498,96 @@ track::Connection Points::nextPosition(const track::TravelToken& aToken) const } // Get the endpoint that follows the curve -Point Points::displacedEndpoint() const +Point Points::displaced_endpoint() const { const int reflect = reflected ? -1 : 1; - if (myAxis == axis::X) - return makePoint(myX + 2, myY + 1*reflect); - else if (myAxis == -axis::X) - return makePoint(myX - 2, myY - 1*reflect); - else if (myAxis == axis::Y) - return makePoint(myX - 1*reflect, myY + 2); - else if (myAxis == -axis::Y) - return makePoint(myX + 1*reflect, myY - 2); + if (my_axis == axis::X) + return make_point(myX + 2, myY + 1*reflect); + else if (my_axis == -axis::X) + return make_point(myX - 2, myY - 1*reflect); + else if (my_axis == axis::Y) + return make_point(myX - 1*reflect, myY + 2); + else if (my_axis == -axis::Y) + return make_point(myX + 1*reflect, myY - 2); else assert(false); } // Get the endpoint that follows the straight track -Point Points::straightEndpoint() const +Point Points::straight_endpoint() const { - if (myAxis == axis::X) - return makePoint(myX + 2, myY); - else if (myAxis == -axis::X) - return makePoint(myX - 2, myY); - else if (myAxis == axis::Y) - return makePoint(myX, myY + 2); - else if (myAxis == -axis::Y) - return makePoint(myX, myY - 2); + if (my_axis == axis::X) + return make_point(myX + 2, myY); + else if (my_axis == -axis::X) + return make_point(myX - 2, myY); + else if (my_axis == axis::Y) + return make_point(myX, myY + 2); + else if (my_axis == -axis::Y) + return make_point(myX, myY - 2); else assert(false); } -void Points::getEndpoints(vector >& aList) const +void Points::get_endpoints(vector >& a_list) const { - aList.push_back(makePoint(myX, myY)); - aList.push_back(straightEndpoint()); - aList.push_back(displacedEndpoint()); + a_list.push_back(make_point(myX, myY)); + a_list.push_back(straight_endpoint()); + a_list.push_back(displaced_endpoint()); } -void Points::getCovers(vector >& output) const +void Points::get_covers(vector >& output) const { const int reflect = reflected ? -1 : 1; - if (myAxis == axis::X) { - output.push_back(makePoint(myX + 1, myY + 1*reflect)); - output.push_back(makePoint(myX + 1, myY)); + if (my_axis == axis::X) { + output.push_back(make_point(myX + 1, myY + 1*reflect)); + output.push_back(make_point(myX + 1, myY)); } - else if (myAxis == -axis::X) { - output.push_back(makePoint(myX - 1, myY - 1*reflect)); - output.push_back(makePoint(myX - 1, myY)); + else if (my_axis == -axis::X) { + output.push_back(make_point(myX - 1, myY - 1*reflect)); + output.push_back(make_point(myX - 1, myY)); } - else if (myAxis == axis::Y) { - output.push_back(makePoint(myX - 1*reflect, myY + 1)); - output.push_back(makePoint(myX, myY + 1)); + else if (my_axis == axis::Y) { + output.push_back(make_point(myX - 1*reflect, myY + 1)); + output.push_back(make_point(myX, myY + 1)); } - else if (myAxis == -axis::Y) { - output.push_back(makePoint(myX + 1*reflect, myY - 1)); - output.push_back(makePoint(myX, myY - 1)); + else if (my_axis == -axis::Y) { + output.push_back(make_point(myX + 1*reflect, myY - 1)); + output.push_back(make_point(myX, myY - 1)); } else assert(false); } -ITrackSegmentPtr Points::mergeExit(Point where, track::Direction dir) +ITrackSegmentPtr Points::merge_exit(Point where, track::Direction dir) { // Cant merge with anything return ITrackSegmentPtr(); } -xml::element Points::toXml() const +xml::element Points::to_xml() const { return xml::element("points") - .addAttribute("align", - myAxis == axis::X ? "x" - : (myAxis == -axis::X ? "-x" - : (myAxis == axis::Y ? "y" - : (myAxis == -axis::Y ? "-y" : "?")))) - .addAttribute("reflect", reflected); + .add_attribute("align", + my_axis == axis::X ? "x" + : (my_axis == -axis::X ? "-x" + : (my_axis == axis::Y ? "y" + : (my_axis == -axis::Y ? "-y" : "?")))) + .add_attribute("reflect", reflected); } -void Points::nextState() +void Points::next_state() { state = reflected ? NOT_TAKEN : TAKEN; } -void Points::prevState() +void Points::prev_state() { state = reflected ? TAKEN : NOT_TAKEN; } -ITrackSegmentPtr makePoints(track::Direction aDirection, bool reflect) +ITrackSegmentPtr make_points(track::Direction a_direction, bool reflect) { - return ITrackSegmentPtr(new Points(aDirection, reflect)); + return ITrackSegmentPtr(new Points(a_direction, reflect)); } diff --git a/src/QuadTree.cpp b/src/QuadTree.cpp index a068bb9..e34a9f5 100644 --- a/src/QuadTree.cpp +++ b/src/QuadTree.cpp @@ -27,46 +27,46 @@ using namespace std; class QuadTree : public IQuadTree { public: - QuadTree(ISectorRenderablePtr aRenderable); + QuadTree(ISectorRenderablePtr a_renderable); ~QuadTree(); - void buildTree(int width, int height); + void build_tree(int width, int height); - void render(IGraphicsPtr aContext); - int leafSize() const { return QT_LEAF_SIZE; } + void render(IGraphicsPtr a_context); + int leaf_size() const { return QT_LEAF_SIZE; } private: enum QuadType { QT_LEAF, QT_BRANCH }; struct Sector { - Point botLeft, topRight; + Point bot_left, top_right; unsigned int id; unsigned int children[4]; QuadType type; } *sectors; - int calcNumSectors(int aWidth); - int buildNode(int anId, int aParent, int x1, int y1, int x2, int y2); - void visibleSectors(IGraphicsPtr aContext, list& aList, int aSector); + int calc_num_sectors(int a_width); + int build_node(int an_id, int a_parent, int x1, int y1, int x2, int y2); + void visible_sectors(IGraphicsPtr a_context, list& a_list, int a_sector); - int size, numSectors, usedSectors; + int size, num_sectors, used_sectors; ISectorRenderablePtr renderer; // We support non-square maps using a kludge where we make a quad tree // of size equal to the the largest dimension and then ignore sectors // that fall outside the real dimensions - int realWidth, realHeight; + int real_width, real_height; - int killCount; + int kill_count; static const int QT_LEAF_SIZE = 8; // Number of tiles in a QuadTree leaf }; -QuadTree::QuadTree(ISectorRenderablePtr aRenderable) - : sectors(NULL), size(0), numSectors(0), usedSectors(0), - renderer(aRenderable), - realWidth(0), realHeight(0), - killCount(0) +QuadTree::QuadTree(ISectorRenderablePtr a_renderable) + : sectors(NULL), size(0), num_sectors(0), used_sectors(0), + renderer(a_renderable), + real_width(0), real_height(0), + kill_count(0) { } @@ -77,84 +77,84 @@ QuadTree::~QuadTree() delete[] sectors; } -void QuadTree::render(IGraphicsPtr aContext) +void QuadTree::render(IGraphicsPtr a_context) { list visible; - killCount = 0; - visibleSectors(aContext, visible, 0); + kill_count = 0; + visible_sectors(a_context, visible, 0); list::const_iterator it; for (it = visible.begin(); it != visible.end(); ++it) - renderer->renderSector(aContext, (*it)->id, - (*it)->botLeft, (*it)->topRight); + renderer->render_sector(a_context, (*it)->id, + (*it)->bot_left, (*it)->top_right); for (it = visible.begin(); it != visible.end(); ++it) - renderer->postRenderSector(aContext, (*it)->id, - (*it)->botLeft, (*it)->topRight); + renderer->post_render_sector(a_context, (*it)->id, + (*it)->bot_left, (*it)->top_right); } // Creates a blank QuadTree -void QuadTree::buildTree(int width, int height) +void QuadTree::build_tree(int width, int height) { size = max(width, height); - realWidth = width; - realHeight = height; + real_width = width; + real_height = height; // Error checking if (size % QT_LEAF_SIZE != 0) throw runtime_error("Invalid QuadTree dimensions!"); // Allocate memory - numSectors = calcNumSectors(size); - usedSectors = 0; + num_sectors = calc_num_sectors(size); + used_sectors = 0; if (sectors) delete[] sectors; - sectors = new Sector[numSectors]; + sectors = new Sector[num_sectors]; // Build the tree - buildNode(0, 0, 0, 0, size, size); + build_node(0, 0, 0, 0, size, size); } // Builds a node in the tree -int QuadTree::buildNode(int anId, int aParent, int x1, int y1, int x2, int y2) +int QuadTree::build_node(int an_id, int a_parent, int x1, int y1, int x2, int y2) { // Store this sector's data - sectors[anId].id = anId; - sectors[anId].botLeft.x = x1; - sectors[anId].botLeft.y = y1; - sectors[anId].topRight.x = x2; - sectors[anId].topRight.y = y2; + sectors[an_id].id = an_id; + sectors[an_id].bot_left.x = x1; + sectors[an_id].bot_left.y = y1; + sectors[an_id].top_right.x = x2; + sectors[an_id].top_right.y = y2; // Check to see if it's a leaf if (abs(x1 - x2) == QT_LEAF_SIZE && abs(y1 - y2) == QT_LEAF_SIZE) - sectors[anId].type = QT_LEAF; + sectors[an_id].type = QT_LEAF; else { - sectors[anId].type = QT_BRANCH; + sectors[an_id].type = QT_BRANCH; int w = x2 - x1; int h = y2 - y1; // Build children - unsigned int* c = sectors[anId].children; - c[0] = buildNode(++usedSectors, anId, x1, y1, x1+w/2, y1+h/2); - c[1] = buildNode(++usedSectors, anId, x1, y1+h/2, x1+w/2, y2 ); - c[3] = buildNode(++usedSectors, anId, x1+w/2, y1+h/2, x2, y2 ); - c[2] = buildNode(++usedSectors, anId, x1+w/2, y1, x2, y1+h/2); + unsigned int* c = sectors[an_id].children; + c[0] = build_node(++used_sectors, an_id, x1, y1, x1+w/2, y1+h/2); + c[1] = build_node(++used_sectors, an_id, x1, y1+h/2, x1+w/2, y2 ); + c[3] = build_node(++used_sectors, an_id, x1+w/2, y1+h/2, x2, y2 ); + c[2] = build_node(++used_sectors, an_id, x1+w/2, y1, x2, y1+h/2); } - return anId; + return an_id; } // Work out how many sectors are required in the QuadTree -int QuadTree::calcNumSectors(int aWidth) +int QuadTree::calc_num_sectors(int a_width) { int count = 0; - if (aWidth > QT_LEAF_SIZE) { + if (a_width > QT_LEAF_SIZE) { for (int i = 0; i < 4; i++) - count += calcNumSectors(aWidth/2); + count += calc_num_sectors(a_width/2); return count + 1; } else @@ -162,51 +162,51 @@ int QuadTree::calcNumSectors(int aWidth) } // Find all the visible sectors -void QuadTree::visibleSectors(IGraphicsPtr aContext, list& aList, - int aSector) +void QuadTree::visible_sectors(IGraphicsPtr a_context, list& a_list, + int a_sector) { - if (aSector >= numSectors) { + if (a_sector >= num_sectors) { ostringstream ss; - ss << "displaySector(" << aSector << ") out of range"; + ss << "display_sector(" << a_sector << ") out of range"; throw runtime_error(ss.str()); } - Sector& s = sectors[aSector]; + Sector& s = sectors[a_sector]; - bool botLeftOutside = - s.botLeft.x >= realWidth - || s.botLeft.y >= realHeight; - if (botLeftOutside) { + bool bot_left_outside = + s.bot_left.x >= real_width + || s.bot_left.y >= real_height; + if (bot_left_outside) { // A non-square map return; } // See if it's a leaf if (s.type == QT_LEAF) - aList.push_back(&s); + a_list.push_back(&s); else { // Loop through each sector for (int i = 3; i >= 0; i--) { int childID = s.children[i]; Sector* child = §ors[childID]; - int w = child->topRight.x - child->botLeft.x; - int h = child->topRight.y - child->botLeft.y; + int w = child->top_right.x - child->bot_left.x; + int h = child->top_right.y - child->bot_left.y; - int x = child->botLeft.x + w/2; - int y = child->botLeft.y + h/2; + int x = child->bot_left.x + w/2; + int y = child->bot_left.y + h/2; - if (aContext->cubeInViewFrustum((float)x, 0.0f, (float)y, (float)w/2)) - visibleSectors(aContext, aList, childID); + if (a_context->cube_in_viewFrustum((float)x, 0.0f, (float)y, (float)w/2)) + visible_sectors(a_context, a_list, childID); else - killCount++; + kill_count++; } } } -IQuadTreePtr makeQuadTree(ISectorRenderablePtr aRenderer, int width, int height) +IQuadTreePtr make_quad_tree(ISectorRenderablePtr a_renderer, int width, int height) { - auto_ptr ptr(new QuadTree(aRenderer)); - ptr->buildTree(width, height); + auto_ptr ptr(new QuadTree(a_renderer)); + ptr->build_tree(width, height); return IQuadTreePtr(ptr); } diff --git a/src/Resource.cpp b/src/Resource.cpp index b799c34..a3d2255 100644 --- a/src/Resource.cpp +++ b/src/Resource.cpp @@ -29,69 +29,69 @@ using namespace boost::filesystem; // A resource that reads data from a filesystem directory class FilesystemResource : public IResource { public: - FilesystemResource(const path& aPath) - : myPath(aPath) + FilesystemResource(const path& a_path) + : my_path(a_path) { } // IResource interface - string name() const { return myPath.filename(); } - string xmlFileName() const + string name() const { return my_path.filename(); } + string xml_file_name() const { - return (myPath / (name() + ".xml")).file_string(); + return (my_path / (name() + ".xml")).file_string(); } - Handle openFile(const string& aFileName) + Handle open_file(const string& a_file_name) { - return Handle((myPath / aFileName).file_string(), Handle::READ); + return Handle((my_path / a_file_name).file_string(), Handle::READ); } - Handle writeFile(const string& aFileName) + Handle write_file(const string& a_file_name) { - return Handle((myPath / aFileName).file_string(), Handle::WRITE); + return Handle((my_path / a_file_name).file_string(), Handle::WRITE); } private: - const path myPath; + const path my_path; }; -IResource::Handle::Handle(const string& fileName, Mode mode) - : fileName_(fileName), mode_(mode), aborted(false) +IResource::Handle::Handle(const string& file_name, Mode mode) + : file_name_(file_name), mode_(mode), aborted(false) { if (mode == READ) { - readStream = shared_ptr(new ifstream(fileName.c_str())); + read_stream = shared_ptr(new ifstream(file_name.c_str())); - if (!readStream->good()) - throw runtime_error("Failed to open resource file " + fileName); + if (!read_stream->good()) + throw runtime_error("Failed to open resource file " + file_name); } else if (mode == WRITE) { - const string tmp = tmpFileName(); - writeStream = shared_ptr(new ofstream(tmp.c_str())); + const string tmp = tmp_file_name(); + write_stream = shared_ptr(new ofstream(tmp.c_str())); - if (!writeStream->good()) - throw runtime_error("Failed to open resource file " + fileName); + if (!write_stream->good()) + throw runtime_error("Failed to open resource file " + file_name); } else throw runtime_error("Bad mode for Handle"); } -string IResource::Handle::tmpFileName() const +string IResource::Handle::tmp_file_name() const { - return fileName() + ".tmp"; + return file_name() + ".tmp"; } void IResource::Handle::rollback() { - remove(tmpFileName()); + remove(tmp_file_name()); aborted = true; } void IResource::Handle::commit() { if (mode() == WRITE && !aborted) { - remove(fileName()); - rename(tmpFileName(), fileName()); - remove(tmpFileName()); + remove(file_name()); + rename(tmp_file_name(), file_name()); + remove(tmp_file_name()); } } @@ -102,55 +102,55 @@ namespace { }; typedef map ResourceMap; - ResourceMap theResources; + ResourceMap the_resources; - ResourceList& resClassList(const string& aClass) + ResourceList& res_class_list(const string& a_class) { - if (theResources.find(aClass) == theResources.end()) - theResources[aClass] = ResourceList(); - return theResources[aClass]; + if (the_resources.find(a_class) == the_resources.end()) + the_resources[a_class] = ResourceList(); + return the_resources[a_class]; } - void addResource(const string& aClass, IResourcePtr aRes) + void add_resource(const string& a_class, IResourcePtr a_res) { - resClassList(aClass).push_back(aRes); + res_class_list(a_class).push_back(a_res); } - void addResourceDir(const char* aClass, const path& aPath) + void add_resource_dir(const char* a_class, const path& a_path) { - const path xmlFile = aPath / (aPath.filename() + ".xml"); + const path xml_file = a_path / (a_path.filename() + ".xml"); - if (!exists(xmlFile)) - warn() << "Missing resource XML file: " << xmlFile; + if (!exists(xml_file)) + warn() << "Missing resource XML file: " << xml_file; else - addResource(aClass, IResourcePtr(new FilesystemResource(aPath))); + add_resource(a_class, IResourcePtr(new FilesystemResource(a_path))); } - void lookInDir(const path& aPath) + void look_in_dir(const path& a_path) { - log() << "Looking for resources in " << aPath; + log() << "Looking for resources in " << a_path; for (const char** p = classes; *p != NULL; ++p) { - if (exists(aPath / *p)) { - for (directory_iterator it(aPath / *p); + if (exists(a_path / *p)) { + for (directory_iterator it(a_path / *p); it != directory_iterator(); ++it) if (is_directory(it->status())) - addResourceDir(*p, *it); + add_resource_dir(*p, *it); } } } } // Set up the resource database and cache available objects -void initResources() +void init_resources() { - lookInDir(current_path()); + look_in_dir(current_path()); ostringstream ss; ss << "Found "; for (const char **it = classes; *it; ++it) { - const ResourceList& lst = resClassList(*it); + const ResourceList& lst = res_class_list(*it); if (it != classes) ss << ", "; @@ -161,20 +161,20 @@ void initResources() } // Find all the resources of the given type -void enumResources(const string& aClass, ResourceList& aList) +void enum_resources(const string& a_class, ResourceList& a_list) { - ResourceList& lst = resClassList(aClass); - copy(lst.begin(), lst.end(), back_inserter(aList)); + ResourceList& lst = res_class_list(a_class); + copy(lst.begin(), lst.end(), back_inserter(a_list)); } namespace { // Find a resource of a particular type // Returns null pointer on failure - IResourcePtr maybeFindResource(const string& aResId, const string& aClass) + IResourcePtr maybe_find_resource(const string& a_res_id, const string& a_class) { - ResourceList& rlist = resClassList(aClass); + ResourceList& rlist = res_class_list(a_class); for (ResourceListIt it = rlist.begin(); it != rlist.end(); ++it) { - if ((*it)->name() == aResId) + if ((*it)->name() == a_res_id) return *it; } @@ -183,37 +183,37 @@ namespace { } // Find a resource or throw an exception on failure -IResourcePtr findResource(const string& aResId, const string& aClass) +IResourcePtr find_resource(const string& a_res_id, const string& a_class) { - IResourcePtr r = maybeFindResource(aResId, aClass); + IResourcePtr r = maybe_find_resource(a_res_id, a_class); if (r) return r; else - throw runtime_error("Failed to find resource " + aResId - + " in class " + aClass); + throw runtime_error("Failed to find resource " + a_res_id + + " in class " + a_class); } // True if the given resource exists -bool resourceExists(const string& aResId, const string& aClass) +bool resource_exists(const string& a_res_id, const string& a_class) { - return maybeFindResource(aResId, aClass); + return maybe_find_resource(a_res_id, a_class); } // Create an empty resource directory -IResourcePtr makeNewResource(const string& aResId, const string& aClass) +IResourcePtr make_new_resource(const string& a_res_id, const string& a_class) { - const path p = path(aClass) / aResId; + const path p = path(a_class) / a_res_id; if (exists(p)) - throw runtime_error("Cannot create resource " + aResId - + " in class " + aClass + ": already exists!"); + throw runtime_error("Cannot create resource " + a_res_id + + " in class " + a_class + ": already exists!"); if (!create_directories(p)) throw runtime_error("Failed to create resource directory " + p.file_string()); IResourcePtr r = IResourcePtr(new FilesystemResource(p)); - addResource(aClass, r); + add_resource(a_class, r); return r; } diff --git a/src/SBend.cpp b/src/SBend.cpp index dbcfa77..00d8a06 100644 --- a/src/SBend.cpp +++ b/src/SBend.cpp @@ -38,26 +38,26 @@ public: // ITrackSegment interface void render() const {} void merge(IMeshBufferPtr buf) const; - void setOrigin(int x, int y, float h); - float segmentLength(const track::TravelToken& token) const; - bool isValidDirection(const track::Direction& dir) const; - track::Connection nextPosition(const track::TravelToken& token) const; - void getEndpoints(vector >& output) const; - void getCovers(vector >& output) const; - ITrackSegmentPtr mergeExit(Point where, track::Direction dir); - track::TravelToken getTravelToken(track::Position pos, + void set_origin(int x, int y, float h); + float segment_length(const track::TravelToken& token) const; + bool is_valid_direction(const track::Direction& dir) const; + track::Connection next_position(const track::TravelToken& token) const; + void get_endpoints(vector >& output) const; + void get_covers(vector >& output) const; + ITrackSegmentPtr merge_exit(Point where, track::Direction dir); + track::TravelToken get_travel_token(track::Position pos, track::Direction dir) const; - void nextState() {} - void prevState() {} - bool hasMultipleStates() const { return false; } - void setStateRenderHint() {} + void next_state() {} + void prev_state() {} + bool has_multiple_states() const { return false; } + void set_state_renderHint() {} // IXMLSerialisable interface - xml::element toXml() const; + xml::element to_xml() const; private: void transform(const track::TravelToken& token, float delta) const; - void ensureValidDirection(track::Direction dir) const; + void ensure_valid_direction(track::Direction dir) const; Point origin; const int straight, offset; @@ -65,14 +65,14 @@ private: track::Direction axis; BezierCurve curve; - IMeshBufferPtr railBuf; + IMeshBufferPtr rail_buf; typedef tuple Parameters; typedef map MeshCache; - static MeshCache meshCache; + static MeshCache mesh_cache; }; -SBend::MeshCache SBend::meshCache; +SBend::MeshCache SBend::mesh_cache; SBend::SBend(track::Direction dir, int straight, int off) : straight(straight), offset(off), @@ -88,63 +88,63 @@ SBend::SBend(track::Direction dir, int straight, int off) const float offsetF = static_cast(offset * reflect); const float straightF = static_cast(straight); - Vector p1 = makeVector(0.0f, 0.0f, 0.0f); - Vector p2 = makeVector(pinch, 0.0f, 0.0f); - Vector p3 = makeVector(straightF - pinch, 0.0f, offsetF); - Vector p4 = makeVector(straightF, 0.0f, offsetF); + Vector p1 = make_vector(0.0f, 0.0f, 0.0f); + Vector p2 = make_vector(pinch, 0.0f, 0.0f); + Vector p3 = make_vector(straightF - pinch, 0.0f, offsetF); + Vector p4 = make_vector(straightF, 0.0f, offsetF); - curve = makeBezierCurve(p1, p2, p3, p4); + curve = make_bezier_curve(p1, p2, p3, p4); Parameters parms = make_tuple(straight, offset * reflect); - MeshCache::iterator it = meshCache.find(parms); - if (it == meshCache.end()) { - railBuf = makeBezierRailMesh(curve); - meshCache[parms] = railBuf; + MeshCache::iterator it = mesh_cache.find(parms); + if (it == mesh_cache.end()) { + rail_buf = make_bezier_railMesh(curve); + mesh_cache[parms] = rail_buf; } else - railBuf = (*it).second; + rail_buf = (*it).second; } -void SBend::setOrigin(int x, int y, float h) +void SBend::set_origin(int x, int y, float h) { - origin = makePoint(x, y); + origin = make_point(x, y); height = h; } void SBend::merge(IMeshBufferPtr buf) const { - Vector off = makeVector( + Vector off = make_vector( static_cast(origin.x), height, static_cast(origin.y)); - float yAngle = axis == axis::Y ? -90.0f : 0.0f; + float y_angle = axis == axis::Y ? -90.0f : 0.0f; { - Vector t = makeVector(-0.5f, 0.0f, 0.0f); - buf->merge(railBuf, off + rotateY(t, yAngle), yAngle); + Vector t = make_vector(-0.5f, 0.0f, 0.0f); + buf->merge(rail_buf, off + rotateY(t, y_angle), y_angle); } // Draw the sleepers for (float i = 0.2f; i < curve.length; i += 0.25f) { Vector v = curve(i / curve.length); - Vector t = makeVector(v.x - 0.5f, 0.0f, v.z); + Vector t = make_vector(v.x - 0.5f, 0.0f, v.z); const Vector deriv = curve.deriv(i / curve.length); const float angle = - radToDeg(atanf(deriv.z / deriv.x)); + rad_to_deg(atanf(deriv.z / deriv.x)); - mergeSleeper(buf, off + rotateY(t, yAngle), yAngle - angle); + merge_sleeper(buf, off + rotateY(t, y_angle), y_angle - angle); } } -float SBend::segmentLength(const track::TravelToken& token) const +float SBend::segment_length(const track::TravelToken& token) const { return curve.length; } -bool SBend::isValidDirection(const track::Direction& dir) const +bool SBend::is_valid_direction(const track::Direction& dir) const { if (axis == axis::X) return dir == axis::X || -dir == axis::X; @@ -152,59 +152,59 @@ bool SBend::isValidDirection(const track::Direction& dir) const return dir == axis::Y || -dir == axis::Y; } -track::Connection SBend::nextPosition(const track::TravelToken& token) const +track::Connection SBend::next_position(const track::TravelToken& token) const { - ensureValidDirection(token.direction); + ensure_valid_direction(token.direction); Point disp; if (token.direction == axis::X) - disp = makePoint(straight, offset); + disp = make_point(straight, offset); else if (token.direction == -axis::X) - disp = makePoint(-1, 0); + disp = make_point(-1, 0); else if (token.direction == axis::Y) - disp = makePoint(offset, straight); + disp = make_point(offset, straight); else if (token.direction == -axis::Y) - disp = makePoint(0, -1); + disp = make_point(0, -1); else assert(false); return make_pair(origin + disp, token.direction); } -void SBend::getEndpoints(vector >& output) const +void SBend::get_endpoints(vector >& output) const { output.push_back(origin); if (axis == axis::X) - output.push_back(origin + makePoint(straight - 1, offset)); + output.push_back(origin + make_point(straight - 1, offset)); else - output.push_back(origin + makePoint(offset, straight - 1)); + output.push_back(origin + make_point(offset, straight - 1)); } -void SBend::getCovers(vector >& output) const +void SBend::get_covers(vector >& output) const { vector > exits; - getEndpoints(exits); + get_endpoints(exits); set > tmp; for (float f = 0.0f; f < 1.0f; f += 0.1f) { - Vector curveValue = curve(f); + Vector curve_value = curve(f); - curveValue.z += 0.5f; + curve_value.z += 0.5f; int x, y; if (axis == axis::X) { - x = static_cast(floor(curveValue.x + origin.x)); - y = static_cast(floor(curveValue.z + origin.y)); + x = static_cast(floor(curve_value.x + origin.x)); + y = static_cast(floor(curve_value.z + origin.y)); } else { - x = -static_cast(floor(curveValue.z - origin.x)); - y = static_cast(floor(curveValue.x + origin.y)); + x = -static_cast(floor(curve_value.z - origin.x)); + y = static_cast(floor(curve_value.x + origin.y)); } - Point p = makePoint(x, y); + Point p = make_point(x, y); if (p != exits.at(0) && p != exits.at(1)) tmp.insert(p); @@ -213,23 +213,23 @@ void SBend::getCovers(vector >& output) const copy(tmp.begin(), tmp.end(), back_inserter(output)); } -ITrackSegmentPtr SBend::mergeExit(Point where, track::Direction dir) +ITrackSegmentPtr SBend::merge_exit(Point where, track::Direction dir) { return ITrackSegmentPtr(); } -track::TravelToken SBend::getTravelToken(track::Position pos, +track::TravelToken SBend::get_travel_token(track::Position pos, track::Direction dir) const { using namespace placeholders; - ensureValidDirection(dir); + ensure_valid_direction(dir); track::TravelToken tok = { dir, pos, bind(&SBend::transform, this, _1, _2), - track::flatGradientFunc, + track::flat_gradient_func, 1 }; return tok; @@ -243,30 +243,30 @@ void SBend::transform(const track::TravelToken& token, float delta) const if (backwards) delta = curve.length - delta; - const float curveDelta = delta / curve.length; + const float curve_delta = delta / curve.length; - Vector curveValue = curve(curveDelta); + Vector curve_value = curve(curve_delta); - const Vector deriv = curve.deriv(curveDelta); + const Vector deriv = curve.deriv(curve_delta); const float angle = - radToDeg(atanf(deriv.z / deriv.x)); + rad_to_deg(atanf(deriv.z / deriv.x)); - float xTrans, yTrans; + float x_trans, y_trans; if (axis == axis::X) { - xTrans = curveValue.x; - yTrans = curveValue.z; + x_trans = curve_value.x; + y_trans = curve_value.z; } else if (axis == axis::Y) { - xTrans = -curveValue.z; - yTrans = curveValue.x; + x_trans = -curve_value.z; + y_trans = curve_value.x; } else assert(false); glTranslatef( - static_cast(origin.x) + xTrans, + static_cast(origin.x) + x_trans, height, - static_cast(origin.y) + yTrans); + static_cast(origin.y) + y_trans); if (axis == axis::Y) glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); @@ -279,9 +279,9 @@ void SBend::transform(const track::TravelToken& token, float delta) const glRotatef(180.0f, 0.0f, 1.0f, 0.0f); } -void SBend::ensureValidDirection(track::Direction dir) const +void SBend::ensure_valid_direction(track::Direction dir) const { - if (!isValidDirection(dir)) + if (!is_valid_direction(dir)) throw runtime_error ("Invalid direction on s-bend track: " + boost::lexical_cast(dir) @@ -289,12 +289,12 @@ void SBend::ensureValidDirection(track::Direction dir) const + boost::lexical_cast(axis) + ")"); } -xml::element SBend::toXml() const +xml::element SBend::to_xml() const { - return xml::element("sbendTrack") - .addAttribute("align", axis == axis::X ? "x" : "y") - .addAttribute("offset", offset) - .addAttribute("straight", straight); + return xml::element("sbend_track") + .add_attribute("align", axis == axis::X ? "x" : "y") + .add_attribute("offset", offset) + .add_attribute("straight", straight); } ITrackSegmentPtr makeSBend(track::Direction dir, int straight, int off) diff --git a/src/SDLWindow.cpp b/src/SDLWindow.cpp index 1f2a7b1..2cb1891 100644 --- a/src/SDLWindow.cpp +++ b/src/SDLWindow.cpp @@ -43,106 +43,106 @@ public: ~SDLWindow(); // IWindow interface - void run(IScreenPtr aScreen); - void switchScreen(IScreenPtr aScreen); + void run(IScreenPtr a_screen); + void switch_screen(IScreenPtr a_screen); void quit(); - void takeScreenShot(); + void take_screen_shot(); int width() const { return width_; } int height() const { return height_; } - void redrawHint() {} + void redraw_hint() {} // IGraphics interface - bool cuboidInViewFrustum(float x, float y, float z, + bool cuboid_in_viewFrustum(float x, float y, float z, float sizeX, float sizeY, float sizeZ); - bool cubeInViewFrustum(float x, float y, float z, float size); - bool pointInViewFrustum(float x, float y, float z); - void setCamera(const Vector& aPos, - const Vector& aRotation); - void lookAt(const Vector anEyePoint, - const Vector aTargetPoint); + bool cube_in_viewFrustum(float x, float y, float z, float size); + bool point_in_viewFrustum(float x, float y, float z); + void set_camera(const Vector& a_pos, + const Vector& a_rotation); + void look_at(const Vector an_eye_point, + const Vector a_target_point); // IPickBuffer interface - IGraphicsPtr beginPick(int x, int y); - unsigned endPick(); + IGraphicsPtr begin_pick(int x, int y); + unsigned end_pick(); private: - void processInput(); + void process_input(); MouseButton fromSDLButton(Uint8 aSDLButton) const; - void captureFrame() const; + void capture_frame() const; - bool amRunning; + bool am_running; int width_, height_; IScreenPtr screen; - bool willSkipNextFrame; - bool willTakeScreenShot; - Frustum viewFrustum; + bool will_skip_nextFrame; + bool will_take_screenShot; + Frustum view_frustum; // Picking data static const int SELECT_BUFFER_SZ = 128; - GLuint mySelectBuffer[SELECT_BUFFER_SZ]; + GLuint my_select_buffer[SELECT_BUFFER_SZ]; }; // Calculation and display of the FPS rate namespace { - int theFrameCounter = 0; - int theLastFPS = 0; + int the_frame_counter = 0; + int the_lastFPS = 0; - Uint32 updateFPS(Uint32 anInterval, void* thread); + Uint32 updateFPS(Uint32 an_interval, void* thread); // A wrapper around SDL times struct FrameTimerThread { FrameTimerThread() { - myTimer = SDL_AddTimer(1000, updateFPS, this); + my_timer = SDL_AddTimer(1000, updateFPS, this); } ~FrameTimerThread() { // Finalise properly when an exception is thrown - SDL_RemoveTimer(myTimer); + SDL_RemoveTimer(my_timer); } // Should be called from the main thread - void updateTitle() + void update_title() { - if (shouldUpdateTitle) { - int avgTriangles = getAverageTriangleCount(); + if (should_update_title) { + int avg_triangles = get_average_triangleCount(); const string title = - "Trains! @ " + lexical_cast(theLastFPS) - + " FPS [" + lexical_cast(avgTriangles) + "Trains! @ " + lexical_cast(the_lastFPS) + + " FPS [" + lexical_cast(avg_triangles) + " triangles]"; SDL_WM_SetCaption(title.c_str(), title.c_str()); } } - SDL_TimerID myTimer; - bool shouldUpdateTitle; + SDL_TimerID my_timer; + bool should_update_title; }; - Uint32 updateFPS(Uint32 anInterval, void* thread) + Uint32 updateFPS(Uint32 an_interval, void* thread) { - theLastFPS = theFrameCounter; - theFrameCounter = 0; + the_lastFPS = the_frame_counter; + the_frame_counter = 0; - static_cast(thread)->shouldUpdateTitle = true; + static_cast(thread)->should_update_title = true; - return anInterval; + return an_interval; } - void frameComplete() + void frame_complete() { - theFrameCounter++; + the_frame_counter++; - updateRenderStats(); + update_render_stats(); } } // Create the game window SDLWindow::SDLWindow() - : amRunning(false), willSkipNextFrame(false), - willTakeScreenShot(false) + : am_running(false), will_skip_nextFrame(false), + will_take_screenShot(false) { - IConfigPtr cfg = getConfig(); + IConfigPtr cfg = get_config(); // Start SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) { @@ -183,64 +183,64 @@ SDLWindow::~SDLWindow() } // Make a screen capture at the end of this frame -void SDLWindow::takeScreenShot() +void SDLWindow::take_screen_shot() { - willTakeScreenShot = true; + will_take_screenShot = true; } // Change the active screen while the game is running -void SDLWindow::switchScreen(IScreenPtr aScreen) +void SDLWindow::switch_screen(IScreenPtr a_screen) { - assert(amRunning); + assert(am_running); - screen = aScreen; - willSkipNextFrame = true; + screen = a_screen; + will_skip_nextFrame = true; } // Run the game until the user quits -void SDLWindow::run(IScreenPtr aScreen) +void SDLWindow::run(IScreenPtr a_screen) { - assert(!amRunning); + assert(!am_running); - screen = aScreen; + screen = a_screen; - FrameTimerThread fpsTimer; + FrameTimerThread fps_timer; - unsigned lastTick = SDL_GetTicks(); + unsigned last_tick = SDL_GetTicks(); // Wait a few milliseconds to get a reasonable tick delta SDL_Delay(1); - amRunning = true; + am_running = true; do { - unsigned tickStart = SDL_GetTicks(); - int delta = static_cast(tickStart - lastTick); + unsigned tick_start = SDL_GetTicks(); + int delta = static_cast(tick_start - last_tick); try { - processInput(); + process_input(); screen->update(shared_from_this(), delta); - if (!willSkipNextFrame) { + if (!will_skip_nextFrame) { drawGLScene(shared_from_this(), shared_from_this(), screen); SDL_GL_SwapBuffers(); } else - willSkipNextFrame = false; + will_skip_nextFrame = false; } catch (runtime_error& e) { error() << "Caught exception: " << e.what(); - amRunning = false; + am_running = false; } - if (willTakeScreenShot) { - captureFrame(); - willTakeScreenShot = false; + if (will_take_screenShot) { + capture_frame(); + will_take_screenShot = false; } - frameComplete(); - fpsTimer.updateTitle(); - lastTick = tickStart; - } while (amRunning); + frame_complete(); + fps_timer.update_title(); + last_tick = tick_start; + } while (am_running); screen.reset(); } @@ -248,7 +248,7 @@ void SDLWindow::run(IScreenPtr aScreen) // Stop the game cleanly void SDLWindow::quit() { - amRunning = false; + am_running = false; } // Convert an SDL button constant to a MouseButton @@ -266,12 +266,12 @@ MouseButton SDLWindow::fromSDLButton(Uint8 aSDLButton) const } // Check for SDL input events -void SDLWindow::processInput() +void SDLWindow::process_input() { SDL_Event e; // Send only one mouse motion event per frame - bool haveSentMouseMotion = false; + bool have_sent_mouseMotion = false; while (SDL_PollEvent(&e)) { switch (e.type) { @@ -282,30 +282,30 @@ void SDLWindow::processInput() break; case SDL_KEYDOWN: - screen->onKeyDown(e.key.keysym.sym); + screen->on_key_down(e.key.keysym.sym); break; case SDL_KEYUP: - screen->onKeyUp(e.key.keysym.sym); + screen->on_key_up(e.key.keysym.sym); break; case SDL_MOUSEMOTION: - if (!haveSentMouseMotion) { - screen->onMouseMove(shared_from_this(), + if (!have_sent_mouseMotion) { + screen->on_mouse_move(shared_from_this(), e.motion.x, e.motion.y, e.motion.xrel, e.motion.yrel); - haveSentMouseMotion = true; + have_sent_mouseMotion = true; } break; case SDL_MOUSEBUTTONDOWN: - screen->onMouseClick(shared_from_this(), + screen->on_mouse_click(shared_from_this(), e.button.x, e.button.y, fromSDLButton(e.button.button)); break; case SDL_MOUSEBUTTONUP: - screen->onMouseRelease(shared_from_this(), + screen->on_mouse_release(shared_from_this(), e.button.x, e.button.y, fromSDLButton(e.button.button)); break; @@ -321,69 +321,69 @@ void SDLWindow::processInput() } // Set up OpenGL to pick out objects -IGraphicsPtr SDLWindow::beginPick(int x, int y) +IGraphicsPtr SDLWindow::begin_pick(int x, int y) { - ::beginPick(shared_from_this(), mySelectBuffer, x, y); + ::begin_pick(shared_from_this(), my_select_buffer, x, y); return shared_from_this(); } // Finish picking and return the name of the clicked object or zero // It's *very* important that this is called exactly once for every -// beginPick or things will get very messed up -unsigned SDLWindow::endPick() +// begin_pick or things will get very messed up +unsigned SDLWindow::end_pick() { - return ::endPick(mySelectBuffer); + return ::end_pick(my_select_buffer); } // Called to set the camera position -void SDLWindow::setCamera(const Vector& aPos, - const Vector& aRotation) +void SDLWindow::set_camera(const Vector& a_pos, + const Vector& a_rotation) { - glRotatef(aRotation.x, 1.0f, 0.0f, 0.0f); - glRotatef(aRotation.y, 0.0f, 1.0f, 0.0f); - glRotatef(aRotation.z, 0.0f, 0.0f, 1.0f); - glTranslatef(aPos.x, aPos.y, aPos.z); + glRotatef(a_rotation.x, 1.0f, 0.0f, 0.0f); + glRotatef(a_rotation.y, 0.0f, 1.0f, 0.0f); + glRotatef(a_rotation.z, 0.0f, 0.0f, 1.0f); + glTranslatef(a_pos.x, a_pos.y, a_pos.z); - viewFrustum = getViewFrustum(); + view_frustum = get_view_frustum(); } -// A wrapper around gluLookAt -void SDLWindow::lookAt(const Vector anEyePoint, - const Vector aTargetPoint) +// A wrapper around glu_look_at +void SDLWindow::look_at(const Vector an_eye_point, + const Vector a_target_point) { - gluLookAt(anEyePoint.x, anEyePoint.y, anEyePoint.z, - aTargetPoint.x, aTargetPoint.y, aTargetPoint.z, + gluLookAt(an_eye_point.x, an_eye_point.y, an_eye_point.z, + a_target_point.x, a_target_point.y, a_target_point.z, 0, 1, 0); - viewFrustum = getViewFrustum(); + view_frustum = get_view_frustum(); } // Intersect a cuboid with the current view frustum -bool SDLWindow::cuboidInViewFrustum(float x, float y, float z, +bool SDLWindow::cuboid_in_viewFrustum(float x, float y, float z, float sizeX, float sizeY, float sizeZ) { - return viewFrustum.cuboidInFrustum(x, y, z, sizeX, sizeY, sizeZ); + return view_frustum.cuboid_in_frustum(x, y, z, sizeX, sizeY, sizeZ); } // Intersect a cube with the current view frustum -bool SDLWindow::cubeInViewFrustum(float x, float y, float z, float size) +bool SDLWindow::cube_in_viewFrustum(float x, float y, float z, float size) { - return viewFrustum.cubeInFrustum(x, y, z, size); + return view_frustum.cube_in_frustum(x, y, z, size); } // True if the point is contained within the view frustum -bool SDLWindow::pointInViewFrustum(float x, float y, float z) +bool SDLWindow::point_in_viewFrustum(float x, float y, float z) { - return viewFrustum.pointInFrustum(x, y, z); + return view_frustum.point_in_frustum(x, y, z); } // Capture the OpenGL pixels and save them to a file -void SDLWindow::captureFrame() const +void SDLWindow::capture_frame() const { - static int fileNumber = 1; + static int file_number = 1; - const string fileName - ("screenshot" + lexical_cast(fileNumber++) + ".bmp"); + const string file_name + ("screenshot" + lexical_cast(file_number++) + ".bmp"); SDL_Surface* temp = SDL_CreateRGBSurface (SDL_SWSURFACE, width_, height_, 24, @@ -405,10 +405,10 @@ void SDLWindow::captureFrame() const memcpy(((char*)temp->pixels) + temp->pitch * i, pixels + 3*w * (h-i-1), w*3); delete[] pixels; - SDL_SaveBMP(temp, fileName.c_str()); + SDL_SaveBMP(temp, file_name.c_str()); SDL_FreeSurface(temp); - log() << "Wrote screen shot to " << fileName; + log() << "Wrote screen shot to " << file_name; } // Construct and initialise an OpenGL SDL window diff --git a/src/SceneryPicker.cpp b/src/SceneryPicker.cpp index a7b6465..de123ef 100644 --- a/src/SceneryPicker.cpp +++ b/src/SceneryPicker.cpp @@ -26,101 +26,101 @@ class SceneryPicker : public ISceneryPicker { public: SceneryPicker(gui::ILayoutPtr l, - const string& resourceClass, const string& guiPath, - const string& btnGuiPath); + const string& resource_class, const string& gui_path, + const string& btn_gui_path); protected: void next(); void prev(); void rotate(); - void renderPreview(gui::Widget& canvas); + void render_preview(gui::Widget& canvas); void show(); void hide(); - void changeActive(const string& newResName); - void selectFirstItem(); + void change_active(const string& new_res_name); + void select_first_item(); - ResourceList resourceList; - ResourceList::const_iterator resourceIt; - ISceneryPtr activeItem; + ResourceList resource_list; + ResourceList::const_iterator resource_it; + ISceneryPtr active_item; gui::ILayoutPtr layout; float rotation; - string resName, guiPath, resClass; + string res_name, gui_path, res_class; }; SceneryPicker::SceneryPicker(gui::ILayoutPtr l, - const string& resourceClass, const string& guiPath, - const string& btnGuiPath) + const string& resource_class, const string& gui_path, + const string& btn_gui_path) : layout(l), rotation(0.0f), - guiPath(guiPath), - resClass(resourceClass) + gui_path(gui_path), + res_class(resource_class) { using namespace placeholders; - enumResources(resourceClass, resourceList); + enum_resources(resource_class, resource_list); - layout->get(guiPath + "/preview").connect(gui::Widget::SIG_RENDER, - bind(&SceneryPicker::renderPreview, this, _1)); - layout->get(guiPath + "/next").connect(gui::Widget::SIG_CLICK, + layout->get(gui_path + "/preview").connect(gui::Widget::SIG_RENDER, + bind(&SceneryPicker::render_preview, this, _1)); + layout->get(gui_path + "/next").connect(gui::Widget::SIG_CLICK, bind(&SceneryPicker::next, this)); - layout->get(guiPath + "/prev").connect(gui::Widget::SIG_CLICK, + layout->get(gui_path + "/prev").connect(gui::Widget::SIG_CLICK, bind(&SceneryPicker::prev, this)); - if (layout->exists(guiPath + "/rotate")) - layout->get(guiPath + "/rotate").connect(gui::Widget::SIG_CLICK, + if (layout->exists(gui_path + "/rotate")) + layout->get(gui_path + "/rotate").connect(gui::Widget::SIG_CLICK, bind(&SceneryPicker::rotate, this)); - layout->get(btnGuiPath).connect(gui::Widget::SIG_ENTER, + layout->get(btn_gui_path).connect(gui::Widget::SIG_ENTER, bind(&SceneryPicker::show, this)); - layout->get(btnGuiPath).connect(gui::Widget::SIG_LEAVE, + layout->get(btn_gui_path).connect(gui::Widget::SIG_LEAVE, bind(&SceneryPicker::hide, this)); hide(); } -void SceneryPicker::selectFirstItem() +void SceneryPicker::select_first_item() { // A kludge to avoid calling the pure virtual get() in constructor - if (resourceList.empty()) - warn() << "No scenery found in class " << resClass; + if (resource_list.empty()) + warn() << "No scenery found in class " << res_class; else { - resourceIt = resourceList.begin(); - changeActive((*resourceIt)->name()); + resource_it = resource_list.begin(); + change_active((*resource_it)->name()); } } void SceneryPicker::next() { - if (++resourceIt == resourceList.end()) - resourceIt = resourceList.begin(); + if (++resource_it == resource_list.end()) + resource_it = resource_list.begin(); - changeActive((*resourceIt)->name()); + change_active((*resource_it)->name()); } void SceneryPicker::prev() { - if (resourceIt == resourceList.begin()) - resourceIt = resourceList.end(); - resourceIt--; + if (resource_it == resource_list.begin()) + resource_it = resource_list.end(); + resource_it--; - changeActive((*resourceIt)->name()); + change_active((*resource_it)->name()); } void SceneryPicker::show() { - layout->get(guiPath).visible(true); + layout->get(gui_path).visible(true); } void SceneryPicker::hide() { - layout->get(guiPath).visible(false); + layout->get(gui_path).visible(false); } -void SceneryPicker::renderPreview(gui::Widget& canvas) +void SceneryPicker::render_preview(gui::Widget& canvas) { - static ILightPtr sun = makeSunLight(); + static ILightPtr sun = make_sun_light(); glRotatef(45.0f, 1.0f, 0.0f, 0.0f); glRotatef(45.0f, 0.0f, 1.0f, 0.0f); @@ -128,17 +128,17 @@ void SceneryPicker::renderPreview(gui::Widget& canvas) glColor3f(1.0f, 1.0f, 1.0f); sun->apply(); - activeItem->render(); + active_item->render(); } -void SceneryPicker::changeActive(const string& newResName) +void SceneryPicker::change_active(const string& new_res_name) { - if (newResName != resName) { - resName = newResName; - activeItem = this->get(); + if (new_res_name != res_name) { + res_name = new_res_name; + active_item = this->get(); - layout->cast(guiPath + "/name") - .text(activeItem->name()); + layout->cast(gui_path + "/name") + .text(active_item->name()); } } @@ -148,7 +148,7 @@ void SceneryPicker::rotate() if (rotation >= 350.0f) rotation = 0.0f; - activeItem->setAngle(rotation); + active_item->set_angle(rotation); } class BuildingPicker : public SceneryPicker { @@ -157,12 +157,12 @@ public: : SceneryPicker(layout, "buildings", "/building_wnd", "/tool_wnd/tools/building") { - selectFirstItem(); + select_first_item(); } virtual ISceneryPtr get() const { - return loadBuilding(resName, rotation); + return load_building(res_name, rotation); } }; @@ -172,21 +172,21 @@ public: : SceneryPicker(layout, "trees", "/tree_wnd", "/tool_wnd/tools/tree") { - selectFirstItem(); + select_first_item(); } virtual ISceneryPtr get() const { - return loadTree(resName); + return load_tree(res_name); } }; -ISceneryPickerPtr makeTreePicker(gui::ILayoutPtr layout) +ISceneryPickerPtr make_tree_picker(gui::ILayoutPtr layout) { return ISceneryPickerPtr(new TreePicker(layout)); } -ISceneryPickerPtr makeBuildingPicker(gui::ILayoutPtr layout) +ISceneryPickerPtr make_building_picker(gui::ILayoutPtr layout) { return ISceneryPickerPtr(new BuildingPicker(layout)); } diff --git a/src/SkyBox.cpp b/src/SkyBox.cpp index 23f3f28..50090bd 100644 --- a/src/SkyBox.cpp +++ b/src/SkyBox.cpp @@ -24,38 +24,38 @@ // Concrete implementation of skyboxes class SkyBox : public ISkyBox { public: - SkyBox(const string& aBaseName); + SkyBox(const string& a_base_name); // ISkyBox interface - void apply(float anAngle) const; + void apply(float an_angle) const; private: - void loadSkyTexture(int anIndex, const string& aSuffix); + void load_sky_texture(int an_index, const string& a_suffix); ITexturePtr textures[6]; - const string baseName; + const string base_name; }; // The base name is used to generate the file names of all six // textures -SkyBox::SkyBox(const string& aBaseName) - : baseName(aBaseName) +SkyBox::SkyBox(const string& a_base_name) + : base_name(a_base_name) { - loadSkyTexture(0, "bottom"); - loadSkyTexture(1, "top"); - loadSkyTexture(2, "front"); - loadSkyTexture(3, "front"); - loadSkyTexture(4, "front"); - loadSkyTexture(5, "front"); + load_sky_texture(0, "bottom"); + load_sky_texture(1, "top"); + load_sky_texture(2, "front"); + load_sky_texture(3, "front"); + load_sky_texture(4, "front"); + load_sky_texture(5, "front"); } -void SkyBox::loadSkyTexture(int anIndex, const string& aSuffix) +void SkyBox::load_sky_texture(int an_index, const string& a_suffix) { - textures[anIndex] = - loadTexture("images/" + baseName + "_" + aSuffix + ".png"); + textures[an_index] = + load_texture("images/" + base_name + "_" + a_suffix + ".png"); } -void SkyBox::apply(float anAngle) const +void SkyBox::apply(float an_angle) const { glColor3f(1.0f, 1.0f, 1.0f); @@ -70,7 +70,7 @@ void SkyBox::apply(float anAngle) const glPushMatrix(); glLoadIdentity(); - glRotatef(radToDeg(anAngle), 0.0f, 1.0f, 0.0f); + glRotatef(rad_to_deg(an_angle), 0.0f, 1.0f, 0.0f); // Bottom textures[0]->bind(); @@ -130,7 +130,7 @@ void SkyBox::apply(float anAngle) const glPopAttrib(); } -ISkyBoxPtr makeSkyBox(const string& aBaseName) +ISkyBoxPtr make_sky_box(const string& a_base_name) { - return ISkyBoxPtr(new SkyBox(aBaseName)); + return ISkyBoxPtr(new SkyBox(a_base_name)); } diff --git a/src/SlopeTrack.cpp b/src/SlopeTrack.cpp index 2a71d02..6aab36e 100644 --- a/src/SlopeTrack.cpp +++ b/src/SlopeTrack.cpp @@ -36,115 +36,115 @@ class SlopeTrack : public ITrackSegment, private BezierHelper { public: SlopeTrack(track::Direction axis, Vector slope, - Vector slopeBefore, Vector slopeAfter); + Vector slope_before, Vector slope_after); // ITrackSegment interface void render() const {} void merge(IMeshBufferPtr buf) const; - void setOrigin(int x, int y, float h); - float segmentLength(const track::TravelToken& token) const; - track::TravelToken getTravelToken(track::Position pos, + void set_origin(int x, int y, float h); + float segment_length(const track::TravelToken& token) const; + track::TravelToken get_travel_token(track::Position pos, track::Direction dir) const; - bool isValidDirection(const track::Direction& dir) const; - track::Connection nextPosition(const track::TravelToken& token) const; - void getEndpoints(vector >& output) const; - void getCovers(vector >& output) const {}; - ITrackSegmentPtr mergeExit(Point where, track::Direction dir); + bool is_valid_direction(const track::Direction& dir) const; + track::Connection next_position(const track::TravelToken& token) const; + void get_endpoints(vector >& output) const; + void get_covers(vector >& output) const {}; + ITrackSegmentPtr merge_exit(Point where, track::Direction dir); - bool hasMultipleStates() const { return false; } - void nextState() {} - void prevState() {} - void setStateRenderHint() {} + bool has_multiple_states() const { return false; } + void next_state() {} + void prev_state() {} + void set_state_renderHint() {} // IXMLSerialisable inteface - xml::element toXml() const; + xml::element to_xml() const; private: - void ensureValidDirection(const track::Direction& dir) const; + void ensure_valid_direction(const track::Direction& dir) const; void transform(const track::TravelToken& token, float delta) const; float gradient(const track::TravelToken& token, float delta) const; Point origin; float height; - IMeshBufferPtr railBuf; + IMeshBufferPtr rail_buf; track::Direction axis; - float length, yOffset; + float length, y_offset; BezierCurve curve; }; SlopeTrack::SlopeTrack(track::Direction axis, Vector slope, - Vector slopeBefore, Vector slopeAfter) - : height(0.0f), axis(axis), yOffset(0.0f) + Vector slope_before, Vector slope_after) + : height(0.0f), axis(axis), y_offset(0.0f) { const float OFF = 0.1f; assert(axis == axis::X || axis == axis::Y); - const Vector avgBefore = (slope + slopeBefore) / 2.0f; - const Vector avgAfter = (slope + slopeAfter) / 2.0f; + const Vector avg_before = (slope + slope_before) / 2.0f; + const Vector avg_after = (slope + slope_after) / 2.0f; if (slope.y < 0.0f) - yOffset = abs(slope.y); + y_offset = abs(slope.y); - const float hFactor0 = sqrt(OFF / (1 + avgBefore.y * avgBefore.y)); - const float hFactor1 = sqrt(OFF / (1 + avgAfter.y * avgAfter.y)); + const float h_factor0 = sqrt(OFF / (1 + avg_before.y * avg_before.y)); + const float h_factor1 = sqrt(OFF / (1 + avg_after.y * avg_after.y)); - const float xDelta0 = hFactor0; - const float yDelta0 = hFactor0 * avgBefore.y; + const float x_delta0 = h_factor0; + const float y_delta0 = h_factor0 * avg_before.y; - const float xDelta1 = hFactor1; - const float yDelta1 = hFactor1 * avgAfter.y; + const float x_delta1 = h_factor1; + const float y_delta1 = h_factor1 * avg_after.y; - Vector p1 = makeVector(0.0f, 0.0f, 0.0f); - Vector p2 = makeVector(xDelta0, yDelta0, 0.0f); - Vector p3 = makeVector(1.0f - xDelta1, slope.y - yDelta1, 0.0f); - Vector p4 = makeVector(1.0f, slope.y, 0.0f); + Vector p1 = make_vector(0.0f, 0.0f, 0.0f); + Vector p2 = make_vector(x_delta0, y_delta0, 0.0f); + Vector p3 = make_vector(1.0f - x_delta1, slope.y - y_delta1, 0.0f); + Vector p4 = make_vector(1.0f, slope.y, 0.0f); - curve = makeBezierCurve(p1, p2, p3, p4); + curve = make_bezier_curve(p1, p2, p3, p4); length = curve.length; - railBuf = makeBezierRailMesh(curve); + rail_buf = make_bezier_railMesh(curve); } void SlopeTrack::merge(IMeshBufferPtr buf) const { - Vector off = makeVector( + Vector off = make_vector( static_cast(origin.x), height, static_cast(origin.y)); - float yAngle = axis == axis::Y ? -90.0f : 0.0f; + float y_angle = axis == axis::Y ? -90.0f : 0.0f; - off += rotateY(makeVector(-0.5f, 0.0f, 0.0f), yAngle); + off += rotateY(make_vector(-0.5f, 0.0f, 0.0f), y_angle); - buf->merge(railBuf, off, yAngle); + buf->merge(rail_buf, off, y_angle); // Draw the sleepers for (float t = 0.1f; t < 1.0f; t += 0.25f) { - const Vector curveValue = curve(t); + const Vector curve_value = curve(t); const Vector deriv = curve.deriv(t); const float angle = - radToDeg(atanf(deriv.y / deriv.x)); + rad_to_deg(atanf(deriv.y / deriv.x)); - Vector t = makeVector(curveValue.x, curveValue.y, 0.0f); + Vector t = make_vector(curve_value.x, curve_value.y, 0.0f); - mergeSleeper(buf, off + rotateY(t, yAngle), yAngle + angle); + merge_sleeper(buf, off + rotateY(t, y_angle), y_angle + angle); } } -void SlopeTrack::setOrigin(int x, int y, float h) +void SlopeTrack::set_origin(int x, int y, float h) { - origin = makePoint(x, y); - height = h + yOffset; + origin = make_point(x, y); + height = h + y_offset; } -float SlopeTrack::segmentLength(const track::TravelToken& token) const +float SlopeTrack::segment_length(const track::TravelToken& token) const { return length; } -bool SlopeTrack::isValidDirection(const track::Direction& dir) const +bool SlopeTrack::is_valid_direction(const track::Direction& dir) const { if (axis == axis::X) return dir == axis::X || -dir == axis::X; @@ -152,9 +152,9 @@ bool SlopeTrack::isValidDirection(const track::Direction& dir) const return dir == axis::Y || -dir == axis::Y; } -void SlopeTrack::ensureValidDirection(const track::Direction& dir) const +void SlopeTrack::ensure_valid_direction(const track::Direction& dir) const { - if (!isValidDirection(dir)) + if (!is_valid_direction(dir)) throw runtime_error ("Invalid direction on straight track: " + boost::lexical_cast(dir) @@ -162,29 +162,29 @@ void SlopeTrack::ensureValidDirection(const track::Direction& dir) const + boost::lexical_cast(axis) + ")"); } -track::Connection SlopeTrack::nextPosition( +track::Connection SlopeTrack::next_position( const track::TravelToken& token) const { - ensureValidDirection(token.direction); + ensure_valid_direction(token.direction); if (token.direction == axis::X) - return make_pair(makePoint(origin.x + 1, origin.y), axis::X); + return make_pair(make_point(origin.x + 1, origin.y), axis::X); else if (token.direction == -axis::X) - return make_pair(makePoint(origin.x - 1, origin.y), -axis::X); + return make_pair(make_point(origin.x - 1, origin.y), -axis::X); else if (token.direction == axis::Y) - return make_pair(makePoint(origin.x, origin.y + 1), axis::Y); + return make_pair(make_point(origin.x, origin.y + 1), axis::Y); else if (token.direction == -axis::Y) - return make_pair(makePoint(origin.x, origin.y - 1), -axis::Y); + return make_pair(make_point(origin.x, origin.y - 1), -axis::Y); else assert(false); } -track::TravelToken SlopeTrack::getTravelToken(track::Position pos, +track::TravelToken SlopeTrack::get_travel_token(track::Position pos, track::Direction dir) const { using namespace placeholders; - ensureValidDirection(dir); + ensure_valid_direction(dir); track::TravelToken tok = { dir, @@ -223,17 +223,17 @@ void SlopeTrack::transform(const track::TravelToken& token, float delta) const if (token.direction == -axis) delta = length - delta; - const float curveDelta = delta / length; + const float curve_delta = delta / length; - const Vector curveValue = curve(curveDelta); + const Vector curve_value = curve(curve_delta); - const float xTrans = axis == axis::X ? curveValue.x : 0.0f; - const float yTrans =curveValue.y; - const float zTrans = axis == axis::Y ? curveValue.x : 0.0f; + const float x_trans = axis == axis::X ? curve_value.x : 0.0f; + const float y_trans =curve_value.y; + const float z_trans = axis == axis::Y ? curve_value.x : 0.0f; - glTranslated(static_cast(origin.x) + xTrans, - height + yTrans, - static_cast(origin.y) + zTrans); + glTranslated(static_cast(origin.x) + x_trans, + height + y_trans, + static_cast(origin.y) + z_trans); if (axis == axis::Y) glRotated(-90.0, 0.0, 1.0, 0.0); @@ -243,9 +243,9 @@ void SlopeTrack::transform(const track::TravelToken& token, float delta) const if (token.direction == -axis) glRotated(-180.0, 0.0, 1.0, 0.0); - const Vector deriv = curve.deriv(curveDelta); + const Vector deriv = curve.deriv(curve_delta); const float angle = - radToDeg(atanf(deriv.y / deriv.x)); + rad_to_deg(atanf(deriv.y / deriv.x)); if (token.direction == -axis) glRotatef(-angle, 0.0f, 0.0f, 1.0f); @@ -253,25 +253,25 @@ void SlopeTrack::transform(const track::TravelToken& token, float delta) const glRotatef(angle, 0.0f, 0.0f, 1.0f); } -void SlopeTrack::getEndpoints(vector >& output) const +void SlopeTrack::get_endpoints(vector >& output) const { output.push_back(origin); } -ITrackSegmentPtr SlopeTrack::mergeExit(Point where, track::Direction dir) +ITrackSegmentPtr SlopeTrack::merge_exit(Point where, track::Direction dir) { return ITrackSegmentPtr(); } -xml::element SlopeTrack::toXml() const +xml::element SlopeTrack::to_xml() const { - return xml::element("slopeTrack") - .addAttribute("align", axis == axis::X ? "x" : "y"); + return xml::element("slope_track") + .add_attribute("align", axis == axis::X ? "x" : "y"); } -ITrackSegmentPtr makeSlopeTrack(track::Direction axis, Vector slope, - Vector slopeBefore, Vector slopeAfter) +ITrackSegmentPtr make_slope_track(track::Direction axis, Vector slope, + Vector slope_before, Vector slope_after) { return ITrackSegmentPtr( - new SlopeTrack(axis, slope, slopeBefore, slopeAfter)); + new SlopeTrack(axis, slope, slope_before, slope_after)); } diff --git a/src/SmokeTrail.cpp b/src/SmokeTrail.cpp index c36c72a..3a2ed7c 100644 --- a/src/SmokeTrail.cpp +++ b/src/SmokeTrail.cpp @@ -29,10 +29,10 @@ public: // ISmokeTrail interface void render() const; - void setPosition(float x, float y, float z); - void update(int aDelta); - void setDelay(int aDelay) { mySpawnDelay = aDelay; } - void setVelocity(float x, float y, float z); + void set_position(float x, float y, float z); + void update(int a_delta); + void set_delay(int a_delay) { my_spawn_delay = a_delay; } + void set_velocity(float x, float y, float z); // A single smoke particle struct Particle { @@ -46,16 +46,16 @@ public: }; private: - void newParticle(); - bool moveParticle(Particle& aParticle, int aDelta); + void new_particle(); + bool move_particle(Particle& a_particle, int a_delta); list particles; float myX, myY, myZ; - ITexturePtr particleTex; + ITexturePtr particle_tex; - // New particles are created every `mySpawnDelay` - int mySpawnDelay, mySpawnCounter; + // New particles are created every `my_spawn_delay` + int my_spawn_delay, my_spawn_counter; // Velocity at which the emitter is moving float myXSpeed, myYSpeed, myZSpeed; @@ -63,28 +63,28 @@ private: SmokeTrail::SmokeTrail() : myX(0.0f), myY(0.0f), myZ(0.0f), - mySpawnDelay(500), mySpawnCounter(0), + my_spawn_delay(500), my_spawn_counter(0), myXSpeed(0.0f), myYSpeed(0.0f), myZSpeed(0.0f) { - particleTex = loadTexture("images/smoke_particle.png"); + particle_tex = load_texture("images/smoke_particle.png"); } // Returns true if the particle is dead -bool SmokeTrail::moveParticle(Particle& p, int aDelta) +bool SmokeTrail::move_particle(Particle& p, int a_delta) { - const float ySpeed = 0.4f; + const float y_speed = 0.4f; const float growth = 0.3f; const float decay = 0.3f; const float appear = 4.0f; const float slowdown = 0.1f; - const float xWind = 0.02f; - const float zWind = 0.01f; + const float x_wind = 0.02f; + const float z_wind = 0.01f; - const float time = static_cast(aDelta) / 1000.0f; + const float time = static_cast(a_delta) / 1000.0f; - p.x += p.xv + (xWind * time); - p.y += p.yv + (ySpeed * time); - p.z += p.zv + (zWind * time); + p.x += p.xv + (x_wind * time); + p.y += p.yv + (y_speed * time); + p.z += p.zv + (z_wind * time); p.xv = max(p.xv - (slowdown * time), 0.0f); p.yv = max(p.yv - (slowdown * time), 0.0f); @@ -92,9 +92,9 @@ bool SmokeTrail::moveParticle(Particle& p, int aDelta) p.scale += growth * time; - p.billboard->setPosition(p.x, p.y, p.z); - p.billboard->setColour(p.r, p.g, p.b, p.a); - p.billboard->setScale(p.scale); + p.billboard->set_position(p.x, p.y, p.z); + p.billboard->set_colour(p.r, p.g, p.b, p.a); + p.billboard->set_scale(p.scale); const float maxA = 0.8f; if (p.appearing) { @@ -110,39 +110,39 @@ bool SmokeTrail::moveParticle(Particle& p, int aDelta) } } -void SmokeTrail::update(int aDelta) +void SmokeTrail::update(int a_delta) { // Move the existing particles list::iterator it = particles.begin(); while (it != particles.end()) { - if (moveParticle(*it, aDelta)) + if (move_particle(*it, a_delta)) it = particles.erase(it); else ++it; } - mySpawnCounter -= aDelta; + my_spawn_counter -= a_delta; - if (mySpawnCounter <= 0) { + if (my_spawn_counter <= 0) { // Generate a new particle - newParticle(); + new_particle(); - mySpawnCounter = mySpawnDelay; + my_spawn_counter = my_spawn_delay; } } -void SmokeTrail::newParticle() +void SmokeTrail::new_particle() { // Random number generator for colour variance - static Normal colourRand(0.0f, 0.06f); + static Normal colour_rand(0.0f, 0.06f); // Random number generator for position variance - static Normal posRand(0.0f, 0.07f); + static Normal pos_rand(0.0f, 0.07f); - const float col = 0.7f + colourRand(); + const float col = 0.7f + colour_rand(); - const float dx = posRand(); - const float dz = posRand(); + const float dx = pos_rand(); + const float dz = pos_rand(); Particle p = { myX + dx, myY, myZ + dz, // Position @@ -152,12 +152,12 @@ void SmokeTrail::newParticle() 0.0f, // Alpha true, // Appearing - makeSphericalBillboard(particleTex) + make_spherical_billboard(particle_tex) }; - p.billboard->setPosition(p.x, p.y, p.z); - p.billboard->setColour(p.r, p.g, p.b, p.a); - p.billboard->setScale(p.scale); + p.billboard->set_position(p.x, p.y, p.z); + p.billboard->set_colour(p.r, p.g, p.b, p.a); + p.billboard->set_scale(p.scale); particles.push_back(p); } @@ -169,21 +169,21 @@ void SmokeTrail::render() const (*it).billboard->render(); } -void SmokeTrail::setPosition(float x, float y, float z) +void SmokeTrail::set_position(float x, float y, float z) { myX = x; myY = y; myZ = z; } -void SmokeTrail::setVelocity(float x, float y, float z) +void SmokeTrail::set_velocity(float x, float y, float z) { myXSpeed = x; myYSpeed = y + 0.02f; // Make smoke shoot up myZSpeed = z; } -ISmokeTrailPtr makeSmokeTrail() +ISmokeTrailPtr make_smoke_trail() { return ISmokeTrailPtr(new SmokeTrail); } diff --git a/src/Station.cpp b/src/Station.cpp index 8039772..b1fcc97 100644 --- a/src/Station.cpp +++ b/src/Station.cpp @@ -27,41 +27,41 @@ public: ~Station() {} // IStation interface - const string& name() const { return myName; } - void setName(const string& aName) { myName = aName; } - int id() const { return myId; } - void setId(int anId) { myId = anId; } - Colour highlightColour() const { return colour; } - bool highlightVisible() const { return isHighlightVisible; } - void setHighlightVisible(bool onOff); + const string& name() const { return my_name; } + void set_name(const string& a_name) { my_name = a_name; } + int id() const { return my_id; } + void set_id(int an_id) { my_id = an_id; } + Colour highlight_colour() const { return colour; } + bool highlight_visible() const { return is_highlight_visible; } + void set_highlight_visible(bool on_off); private: - string myName; + string my_name; Colour colour; - bool isHighlightVisible; - int myId; + bool is_highlight_visible; + int my_id; }; Station::Station() - : isHighlightVisible(false) + : is_highlight_visible(false) { using namespace boost; // Generate a unique station name; - static int nameCounter = 1; - myId = nameCounter++; - myName = "Station" + lexical_cast(myId); + static int name_counter = 1; + my_id = name_counter++; + my_name = "Station" + lexical_cast(my_id); // Generate a random colour - static Uniform colourRand(0.3f, 1.0f); - colour = makeColour(colourRand(), colourRand(), colourRand()); + static Uniform colour_rand(0.3f, 1.0f); + colour = make_colour(colour_rand(), colour_rand(), colour_rand()); } -void Station::setHighlightVisible(bool onOff) +void Station::set_highlight_visible(bool on_off) { - isHighlightVisible = onOff; + is_highlight_visible = on_off; } -IStationPtr makeStation() +IStationPtr make_station() { return IStationPtr(new Station); } diff --git a/src/StraightTrack.cpp b/src/StraightTrack.cpp index 10ec5d8..ede0794 100644 --- a/src/StraightTrack.cpp +++ b/src/StraightTrack.cpp @@ -37,43 +37,43 @@ class StraightTrack : public ITrackSegment, private StraightTrackHelper, private SleeperHelper { public: - StraightTrack(const Direction& aDirection); + StraightTrack(const Direction& a_direction); ~StraightTrack(); void render() const {} void merge(IMeshBufferPtr buf) const; - void setOrigin(int x, int y, float h); - float segmentLength(const track::TravelToken& token) const { return 1.0f; } + void set_origin(int x, int y, float h); + float segment_length(const track::TravelToken& token) const { return 1.0f; } - Connection nextPosition(const track::TravelToken& aDirection) const; - bool isValidDirection(const Direction& aDirection) const; - void getEndpoints(vector >& aList) const; - void getCovers(vector >& output) const { } + Connection next_position(const track::TravelToken& a_direction) const; + bool is_valid_direction(const Direction& a_direction) const; + void get_endpoints(vector >& a_list) const; + void get_covers(vector >& output) const { } - ITrackSegmentPtr mergeExit(Point where, track::Direction dir); - track::TravelToken getTravelToken(track::Position aPosition, - track::Direction aDirection) const; + ITrackSegmentPtr merge_exit(Point where, track::Direction dir); + track::TravelToken get_travel_token(track::Position a_position, + track::Direction a_direction) const; - bool hasMultipleStates() const { return false; } - void nextState() {} - void prevState() {} - void setStateRenderHint() {} + bool has_multiple_states() const { return false; } + void next_state() {} + void prev_state() {} + void set_state_renderHint() {} // IXMLSerialisable interface - xml::element toXml() const; + xml::element to_xml() const; private: - void transform(const track::TravelToken& aToken, float delta) const; - void ensureValidDirection(const track::Direction& aDirection) const; + void transform(const track::TravelToken& a_token, float delta) const; + void ensure_valid_direction(const track::Direction& a_direction) const; Point origin; // Absolute position Direction direction; float height; }; -StraightTrack::StraightTrack(const Direction& aDirection) - : direction(aDirection), height(0.0f) +StraightTrack::StraightTrack(const Direction& a_direction) + : direction(a_direction), height(0.0f) { } @@ -83,57 +83,57 @@ StraightTrack::~StraightTrack() } -void StraightTrack::setOrigin(int x, int y, float h) +void StraightTrack::set_origin(int x, int y, float h) { - origin = makePoint(x, y); + origin = make_point(x, y); height = h; } track::TravelToken -StraightTrack::getTravelToken(track::Position aPosition, - track::Direction aDirection) const +StraightTrack::get_travel_token(track::Position a_position, + track::Direction a_direction) const { - ensureValidDirection(aDirection); + ensure_valid_direction(a_direction); track::TravelToken tok = { - aDirection, - aPosition, + a_direction, + a_position, bind(&StraightTrack::transform, this, _1, _2), - track::flatGradientFunc, + track::flat_gradient_func, 1 }; return tok; } -void StraightTrack::transform(const track::TravelToken& aToken, +void StraightTrack::transform(const track::TravelToken& a_token, float delta) const { assert(delta < 1.0); - if (aToken.direction == -direction) + if (a_token.direction == -direction) delta = 1.0 - delta; - const float xTrans = direction == axis::X ? delta : 0; - const float yTrans = direction == axis::Y ? delta : 0; + const float x_trans = direction == axis::X ? delta : 0; + const float y_trans = direction == axis::Y ? delta : 0; - glTranslated(static_cast(origin.x) + xTrans, + glTranslated(static_cast(origin.x) + x_trans, height, - static_cast(origin.y) + yTrans); + static_cast(origin.y) + y_trans); if (direction == axis::Y) glRotated(-90.0, 0.0, 1.0, 0.0); glTranslated(-0.5, 0.0, 0.0); - if (aToken.direction == -direction) + if (a_token.direction == -direction) glRotated(-180.0, 0.0, 1.0, 0.0); } -ITrackSegmentPtr StraightTrack::mergeExit(Point where, +ITrackSegmentPtr StraightTrack::merge_exit(Point where, track::Direction dir) { #if 1 - debug() << "mergeExit where=" << where + debug() << "merge_exit where=" << where << " dir=" << dir << " me=" << origin << " mydir=" << direction; @@ -141,114 +141,114 @@ ITrackSegmentPtr StraightTrack::mergeExit(Point where, // See if we can make this a crossover track if (direction != dir && where == origin) - return makeCrossoverTrack(); + return make_crossover_track(); // See if we can make some points - if (isValidDirection(dir)) { + if (is_valid_direction(dir)) { // X-aligned points - if (where == origin + makePoint(-2, 1)) - return makePoints(-axis::X, true); - else if (where == origin + makePoint(-2, -1)) - return makePoints(-axis::X, false); - else if (where == origin + makePoint(2, 1)) - return makePoints(axis::X, false); - else if (where == origin + makePoint(2, -1)) - return makePoints(axis::X, true); + if (where == origin + make_point(-2, 1)) + return make_points(-axis::X, true); + else if (where == origin + make_point(-2, -1)) + return make_points(-axis::X, false); + else if (where == origin + make_point(2, 1)) + return make_points(axis::X, false); + else if (where == origin + make_point(2, -1)) + return make_points(axis::X, true); // Y-aligned points - if (where == origin + makePoint(1, -2)) - return makePoints(-axis::Y, false); - else if (where == origin + makePoint(-1, -2)) - return makePoints(-axis::Y, true); - else if (where == origin + makePoint(1, 2)) - return makePoints(axis::Y, true); - else if (where == origin + makePoint(-1, 2)) - return makePoints(axis::Y, false); + if (where == origin + make_point(1, -2)) + return make_points(-axis::Y, false); + else if (where == origin + make_point(-1, -2)) + return make_points(-axis::Y, true); + else if (where == origin + make_point(1, 2)) + return make_points(axis::Y, true); + else if (where == origin + make_point(-1, 2)) + return make_points(axis::Y, false); } // Not possible to merge return ITrackSegmentPtr(); } -bool StraightTrack::isValidDirection(const Direction& aDirection) const +bool StraightTrack::is_valid_direction(const Direction& a_direction) const { if (direction == axis::X) - return aDirection == axis::X || -aDirection == axis::X; + return a_direction == axis::X || -a_direction == axis::X; else - return aDirection == axis::Y || -aDirection == axis::Y; + return a_direction == axis::Y || -a_direction == axis::Y; } -void StraightTrack::getEndpoints(vector >& aList) const +void StraightTrack::get_endpoints(vector >& a_list) const { - aList.push_back(origin); + a_list.push_back(origin); } -void StraightTrack::ensureValidDirection(const Direction& aDirection) const +void StraightTrack::ensure_valid_direction(const Direction& a_direction) const { - if (!isValidDirection(aDirection)) + if (!is_valid_direction(a_direction)) throw runtime_error ("Invalid direction on straight track: " - + lexical_cast(aDirection) + + lexical_cast(a_direction) + " (should be parallel to " + lexical_cast(direction) + ")"); } -Connection StraightTrack::nextPosition(const track::TravelToken& aToken) const +Connection StraightTrack::next_position(const track::TravelToken& a_token) const { - ensureValidDirection(aToken.direction); - - if (aToken.direction == axis::X) - return make_pair(makePoint(origin.x + 1, origin.y), axis::X); - else if (aToken.direction == -axis::X) - return make_pair(makePoint(origin.x - 1, origin.y), -axis::X); - else if (aToken.direction == axis::Y) - return make_pair(makePoint(origin.x, origin.y + 1), axis::Y); - else if (aToken.direction == -axis::Y) - return make_pair(makePoint(origin.x, origin.y - 1), -axis::Y); + ensure_valid_direction(a_token.direction); + + if (a_token.direction == axis::X) + return make_pair(make_point(origin.x + 1, origin.y), axis::X); + else if (a_token.direction == -axis::X) + return make_pair(make_point(origin.x - 1, origin.y), -axis::X); + else if (a_token.direction == axis::Y) + return make_pair(make_point(origin.x, origin.y + 1), axis::Y); + else if (a_token.direction == -axis::Y) + return make_pair(make_point(origin.x, origin.y - 1), -axis::Y); else assert(false); } void StraightTrack::merge(IMeshBufferPtr buf) const { - Vector off = makeVector( + Vector off = make_vector( static_cast(origin.x), height, static_cast(origin.y)); - float yAngle = direction == axis::X ? 90.0f : 0.0f; + float y_angle = direction == axis::X ? 90.0f : 0.0f; - mergeStraightRail(buf, off, yAngle); + merge_straight_rail(buf, off, y_angle); - yAngle += 90.0f; + y_angle += 90.0f; - off += rotate(makeVector(-0.4f, 0.0f, 0.0f), yAngle, 0.0f, 1.0f, 0.0f); + off += rotate(make_vector(-0.4f, 0.0f, 0.0f), y_angle, 0.0f, 1.0f, 0.0f); for (int i = 0; i < 4; i++) { - mergeSleeper(buf, off, yAngle); + merge_sleeper(buf, off, y_angle); - off += rotate(makeVector(0.25f, 0.0f, 0.0f), yAngle, 0.0f, 1.0f, 0.0f); + off += rotate(make_vector(0.25f, 0.0f, 0.0f), y_angle, 0.0f, 1.0f, 0.0f); } } -xml::element StraightTrack::toXml() const +xml::element StraightTrack::to_xml() const { - return xml::element("straightTrack") - .addAttribute("align", direction == axis::X ? "x" : "y"); + return xml::element("straight_track") + .add_attribute("align", direction == axis::X ? "x" : "y"); } -ITrackSegmentPtr makeStraightTrack(const Direction& aDirection) +ITrackSegmentPtr make_straight_track(const Direction& a_direction) { - Direction realDir(aDirection); + Direction real_dir(a_direction); // Direction must either be along axis::X or axis::Y but we // allow the opositite direction here too - if (realDir == -axis::X || realDir == -axis::Y) - realDir = -realDir; + if (real_dir == -axis::X || real_dir == -axis::Y) + real_dir = -real_dir; - if (realDir != axis::X && realDir != axis::Y) + if (real_dir != axis::X && real_dir != axis::Y) throw runtime_error("Illegal straight track direction: " - + lexical_cast(aDirection)); + + lexical_cast(a_direction)); - return ITrackSegmentPtr(new StraightTrack(realDir)); + return ITrackSegmentPtr(new StraightTrack(real_dir)); } diff --git a/src/Texture.cpp b/src/Texture.cpp index af2beab..48e2f5f 100644 --- a/src/Texture.cpp +++ b/src/Texture.cpp @@ -35,52 +35,52 @@ public: Texture(const string &file); virtual ~Texture(); - GLuint texture() const { return myTexture; } + GLuint texture() const { return my_texture; } void bind() const; - int width() const { return myWidth; } - int height() const { return myHeight; } + int width() const { return my_width; } + int height() const { return my_height; } private: - GLuint myTexture; - int myWidth, myHeight; + GLuint my_texture; + int my_width, my_height; - static bool isPowerOfTwo(int n); - static bool isTextureSizeSupported(int width, int height, + static bool is_power_ofTwo(int n); + static bool is_texture_sizeSupported(int width, int height, int ncols = 4, GLenum format = GL_RGBA); }; // Texture cache namespace { - map theTextureCache; + map the_texture_cache; } -ITexturePtr loadTexture(const string& aFileName) +ITexturePtr load_texture(const string& a_file_name) { map::iterator it = - theTextureCache.find(aFileName); + the_texture_cache.find(a_file_name); - if (it != theTextureCache.end()) + if (it != the_texture_cache.end()) return (*it).second; else { - ITexturePtr ptr(new Texture(aFileName)); - theTextureCache[aFileName] = ptr; + ITexturePtr ptr(new Texture(a_file_name)); + the_texture_cache[a_file_name] = ptr; return ptr; } } -ITexturePtr loadTexture(IResourcePtr aRes, const string& aFileName) +ITexturePtr load_texture(IResourcePtr a_res, const string& a_file_name) { // Hack alert! Just use the handle to find out the file name // This should be replaced with a solution where all textures come // from resources... - string realFileName; + string real_file_name; { - IResource::Handle h = aRes->openFile(aFileName); - realFileName = h.fileName(); + IResource::Handle h = a_res->open_file(a_file_name); + real_file_name = h.file_name(); } // Handle closed here - return loadTexture(realFileName); + return load_texture(real_file_name); } Texture::Texture(const string &file) @@ -92,12 +92,12 @@ Texture::Texture(const string &file) throw runtime_error(os.str()); } - if (!isPowerOfTwo(surface->w)) + if (!is_power_ofTwo(surface->w)) warn() << file << " width not a power of 2"; - if (!isPowerOfTwo(surface->h)) + if (!is_power_ofTwo(surface->h)) warn() << file << " height not a power of 2"; - if (!isTextureSizeSupported(surface->w, surface->h)) + if (!is_texture_sizeSupported(surface->w, surface->h)) warn() << file << " bigger than max OpenGL texture"; int ncols = surface->format->BytesPerPixel; @@ -121,11 +121,11 @@ Texture::Texture(const string &file) throw runtime_error(os.str()); } - myWidth = surface->w; - myHeight = surface->h; + my_width = surface->w; + my_height = surface->h; - glGenTextures(1, &myTexture); - glBindTexture(GL_TEXTURE_2D, myTexture); + glGenTextures(1, &my_texture); + glBindTexture(GL_TEXTURE_2D, my_texture); // Use GL_NEAREST here for better performance // Or GL_LINEAR for better apppearance @@ -143,10 +143,10 @@ Texture::Texture(const string &file) Texture::~Texture() { - glDeleteTextures(1, &myTexture); + glDeleteTextures(1, &my_texture); } -bool Texture::isPowerOfTwo(int n) +bool Texture::is_power_ofTwo(int n) { int pop = 0; for (unsigned i = 0, bit = 1; @@ -158,7 +158,7 @@ bool Texture::isPowerOfTwo(int n) return pop == 1; } -bool Texture::isTextureSizeSupported(int width, int height, int ncols, GLenum format) +bool Texture::is_texture_sizeSupported(int width, int height, int ncols, GLenum format) { glTexImage2D(GL_PROXY_TEXTURE_2D, 0, ncols, width, height, 0, format, GL_UNSIGNED_BYTE, NULL); @@ -170,5 +170,5 @@ bool Texture::isTextureSizeSupported(int width, int height, int ncols, GLenum fo void Texture::bind() const { - glBindTexture(GL_TEXTURE_2D, myTexture); + glBindTexture(GL_TEXTURE_2D, my_texture); } diff --git a/src/TrackCommon.cpp b/src/TrackCommon.cpp index cd6f228..4d7722c 100644 --- a/src/TrackCommon.cpp +++ b/src/TrackCommon.cpp @@ -32,71 +32,71 @@ namespace { const float SLEEPER_LENGTH = 0.8f; - const Colour METAL = makeColour(0.5f, 0.5f, 0.5f); + const Colour METAL = make_colour(0.5f, 0.5f, 0.5f); } -IMeshBufferPtr SleeperHelper::sleeperBuf; +IMeshBufferPtr SleeperHelper::sleeper_buf; -IMeshBufferPtr SleeperHelper::generateSleeperMeshBuffer() +IMeshBufferPtr SleeperHelper::generate_sleeper_meshBuffer() { - IMeshBufferPtr buf = makeMeshBuffer(); + IMeshBufferPtr buf = make_mesh_buffer(); - const Colour brown = makeColour(0.5f, 0.3f, 0.0f); + const Colour brown = make_colour(0.5f, 0.3f, 0.0f); - const float sleeperWidth = 0.1f; - const float sleeperDepth = 0.05f; - const float sleeperOff = sleeperWidth / 2.0f; + const float sleeper_width = 0.1f; + const float sleeper_depth = 0.05f; + const float sleeper_off = sleeper_width / 2.0f; const float r = SLEEPER_LENGTH / 2.0f; // Top - buf->addQuad(makeVector(-sleeperOff, sleeperDepth, -r), - makeVector(-sleeperOff, sleeperDepth, r), - makeVector(sleeperOff, sleeperDepth, r), - makeVector(sleeperOff, sleeperDepth, -r), + buf->add_quad(make_vector(-sleeper_off, sleeper_depth, -r), + make_vector(-sleeper_off, sleeper_depth, r), + make_vector(sleeper_off, sleeper_depth, r), + make_vector(sleeper_off, sleeper_depth, -r), brown); // Side 1 - buf->addQuad(makeVector(sleeperOff, sleeperDepth, -r), - makeVector(sleeperOff, 0.0f, -r), - makeVector(-sleeperOff, 0.0f, -r), - makeVector(-sleeperOff, sleeperDepth, -r), + buf->add_quad(make_vector(sleeper_off, sleeper_depth, -r), + make_vector(sleeper_off, 0.0f, -r), + make_vector(-sleeper_off, 0.0f, -r), + make_vector(-sleeper_off, sleeper_depth, -r), brown); // Side 2 - buf->addQuad(makeVector(-sleeperOff, sleeperDepth, r), - makeVector(-sleeperOff, 0.0f, r), - makeVector(sleeperOff, 0.0f, r), - makeVector(sleeperOff, sleeperDepth, r), + buf->add_quad(make_vector(-sleeper_off, sleeper_depth, r), + make_vector(-sleeper_off, 0.0f, r), + make_vector(sleeper_off, 0.0f, r), + make_vector(sleeper_off, sleeper_depth, r), brown); // Front - buf->addQuad(makeVector(sleeperOff, 0.0f, r), - makeVector(sleeperOff, 0.0f, -r), - makeVector(sleeperOff, sleeperDepth, -r), - makeVector(sleeperOff, sleeperDepth, r), + buf->add_quad(make_vector(sleeper_off, 0.0f, r), + make_vector(sleeper_off, 0.0f, -r), + make_vector(sleeper_off, sleeper_depth, -r), + make_vector(sleeper_off, sleeper_depth, r), brown); // Back - buf->addQuad(makeVector(-sleeperOff, sleeperDepth, r), - makeVector(-sleeperOff, sleeperDepth, -r), - makeVector(-sleeperOff, 0.0f, -r), - makeVector(-sleeperOff, 0.0f, r), + buf->add_quad(make_vector(-sleeper_off, sleeper_depth, r), + make_vector(-sleeper_off, sleeper_depth, -r), + make_vector(-sleeper_off, 0.0f, -r), + make_vector(-sleeper_off, 0.0f, r), brown); return buf; } -void SleeperHelper::mergeSleeper(IMeshBufferPtr buf, - Vector off, float yAngle) const +void SleeperHelper::merge_sleeper(IMeshBufferPtr buf, + Vector off, float y_angle) const { - if (!sleeperBuf) - sleeperBuf = generateSleeperMeshBuffer(); + if (!sleeper_buf) + sleeper_buf = generate_sleeper_meshBuffer(); - buf->merge(sleeperBuf, off, yAngle); + buf->merge(sleeper_buf, off, y_angle); } -void BezierHelper::buildOneBezierRail(const BezierCurve& func, +void BezierHelper::build_one_bezierRail(const BezierCurve& func, IMeshBufferPtr buf, float p) { const float step = 0.1f; @@ -110,116 +110,116 @@ void BezierHelper::buildOneBezierRail(const BezierCurve& func, v2.z -= RAIL_WIDTH / 2.0f; // Top of rail - buf->addQuad(makeVector(v1.x, v1.y + track::RAIL_HEIGHT, v1.z), - makeVector(v1.x, v1.y + track::RAIL_HEIGHT, v1.z + RAIL_WIDTH), - makeVector(v2.x, v2.y + track::RAIL_HEIGHT, v2.z + RAIL_WIDTH), - makeVector(v2.x, v2.y + track::RAIL_HEIGHT, v2.z), + buf->add_quad(make_vector(v1.x, v1.y + track::RAIL_HEIGHT, v1.z), + make_vector(v1.x, v1.y + track::RAIL_HEIGHT, v1.z + RAIL_WIDTH), + make_vector(v2.x, v2.y + track::RAIL_HEIGHT, v2.z + RAIL_WIDTH), + make_vector(v2.x, v2.y + track::RAIL_HEIGHT, v2.z), METAL); // Outer edge - buf->addQuad(makeVector(v2.x, v2.y + track::RAIL_HEIGHT, v2.z), - makeVector(v2.x , v2.y, v2.z), - makeVector(v1.x, v1.y, v1.z), - makeVector(v1.x, v1.y + track::RAIL_HEIGHT, v1.z), + buf->add_quad(make_vector(v2.x, v2.y + track::RAIL_HEIGHT, v2.z), + make_vector(v2.x , v2.y, v2.z), + make_vector(v1.x, v1.y, v1.z), + make_vector(v1.x, v1.y + track::RAIL_HEIGHT, v1.z), METAL); // Inner edge - buf->addQuad(makeVector(v1.x, v1.y + track::RAIL_HEIGHT, v1.z + RAIL_WIDTH), - makeVector(v1.x, v1.y, v1.z + RAIL_WIDTH), - makeVector(v2.x , v2.y, v2.z + RAIL_WIDTH), - makeVector(v2.x, v2.y + track::RAIL_HEIGHT, v2.z + RAIL_WIDTH), + buf->add_quad(make_vector(v1.x, v1.y + track::RAIL_HEIGHT, v1.z + RAIL_WIDTH), + make_vector(v1.x, v1.y, v1.z + RAIL_WIDTH), + make_vector(v2.x , v2.y, v2.z + RAIL_WIDTH), + make_vector(v2.x, v2.y + track::RAIL_HEIGHT, v2.z + RAIL_WIDTH), METAL); } } -IMeshBufferPtr BezierHelper::makeBezierRailMesh( +IMeshBufferPtr BezierHelper::make_bezier_railMesh( const BezierCurve& func) const { - IMeshBufferPtr buf = makeMeshBuffer(); + IMeshBufferPtr buf = make_mesh_buffer(); - buildOneBezierRail(func, buf, GAUGE/2.0f); - buildOneBezierRail(func, buf, -GAUGE/2.0f); + build_one_bezierRail(func, buf, GAUGE/2.0f); + build_one_bezierRail(func, buf, -GAUGE/2.0f); return buf; } -IMeshBufferPtr StraightTrackHelper::railBuf; +IMeshBufferPtr StraightTrackHelper::rail_buf; -IMeshBufferPtr StraightTrackHelper::generateRailMeshBuffer() +IMeshBufferPtr StraightTrackHelper::generate_rail_meshBuffer() { - IMeshBufferPtr buf = makeMeshBuffer(); + IMeshBufferPtr buf = make_mesh_buffer(); // Top side - buf->addQuad(makeVector(-RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 0.0f), - makeVector(-RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 1.0f), - makeVector(RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 1.0f), - makeVector(RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 0.0f), + buf->add_quad(make_vector(-RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 0.0f), + make_vector(-RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 1.0f), + make_vector(RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 1.0f), + make_vector(RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 0.0f), METAL); // Outer side - buf->addQuad(makeVector(-RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 0.0f), - makeVector(-RAIL_WIDTH/2.0f, 0.0f, 0.0f), - makeVector(-RAIL_WIDTH/2.0f, 0.0f, 1.0f), - makeVector(-RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 1.0f), + buf->add_quad(make_vector(-RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 0.0f), + make_vector(-RAIL_WIDTH/2.0f, 0.0f, 0.0f), + make_vector(-RAIL_WIDTH/2.0f, 0.0f, 1.0f), + make_vector(-RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 1.0f), METAL); // Inner side - buf->addQuad(makeVector(RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 1.0f), - makeVector(RAIL_WIDTH/2.0f, 0.0f, 1.0f), - makeVector(RAIL_WIDTH/2.0f, 0.0f, 0.0f), - makeVector(RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 0.0f), + buf->add_quad(make_vector(RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 1.0f), + make_vector(RAIL_WIDTH/2.0f, 0.0f, 1.0f), + make_vector(RAIL_WIDTH/2.0f, 0.0f, 0.0f), + make_vector(RAIL_WIDTH/2.0f, track::RAIL_HEIGHT, 0.0f), METAL); return buf; } -void StraightTrackHelper::mergeOneRail(IMeshBufferPtr buf, - Vector off, float yAngle) const +void StraightTrackHelper::merge_one_rail(IMeshBufferPtr buf, + Vector off, float y_angle) const { - if (!railBuf) - railBuf = generateRailMeshBuffer(); + if (!rail_buf) + rail_buf = generate_rail_meshBuffer(); - buf->merge(railBuf, off, yAngle); + buf->merge(rail_buf, off, y_angle); } -void StraightTrackHelper::mergeStraightRail(IMeshBufferPtr buf, - Vector off, float yAngle) const +void StraightTrackHelper::merge_straight_rail(IMeshBufferPtr buf, + Vector off, float y_angle) const { - Matrix r = Matrix::rotation(yAngle, 0.0f, 1.0f, 0.0f); + Matrix r = Matrix::rotation(y_angle, 0.0f, 1.0f, 0.0f); - off += r.transform(makeVector(-GAUGE/2.0f, 0.0f, -0.5f)); - mergeOneRail(buf, off, yAngle); + off += r.transform(make_vector(-GAUGE/2.0f, 0.0f, -0.5f)); + merge_one_rail(buf, off, y_angle); - off += r.transform(makeVector(GAUGE, 0.0f, 0.0f)); - mergeOneRail(buf, off, yAngle); + off += r.transform(make_vector(GAUGE, 0.0f, 0.0f)); + merge_one_rail(buf, off, y_angle); } -CurvedTrackHelper::CurvedRailMeshMap CurvedTrackHelper::curvedRailMeshes; +CurvedTrackHelper::CurvedRailMeshMap CurvedTrackHelper::curved_rail_meshes; // Move to the origin of a curved section of track -void CurvedTrackHelper::transformToOrigin(Vector& off, - int baseRadius, track::Angle startAngle) const +void CurvedTrackHelper::transform_to_origin(Vector& off, + int base_radius, track::Angle start_angle) const { - off += makeVector( - (baseRadius-1)*-sin(degToRad(startAngle)) - 0.5f, + off += make_vector( + (base_radius-1)*-sin(deg_to_rad(start_angle)) - 0.5f, 0.0f, - (baseRadius-1)*-cos(degToRad(startAngle)) - 0.5f); + (base_radius-1)*-cos(deg_to_rad(start_angle)) - 0.5f); // There *must* be a way to incorporate this in the above translation // as a neat formula, but I really can't think of it // This is a complete a hack, but whatever... - if (startAngle >= 90 && startAngle <= 180) - off += makeVector(0.0f, 0.0f, 1.0f); + if (start_angle >= 90 && start_angle <= 180) + off += make_vector(0.0f, 0.0f, 1.0f); - if (startAngle >= 180 && startAngle <= 270) - off += makeVector(1.0f, 0.0f, 0.0f); + if (start_angle >= 180 && start_angle <= 270) + off += make_vector(1.0f, 0.0f, 0.0f); } -void CurvedTrackHelper::generateCurvedRailMesh(IMeshBufferPtr buf, - int baseRadius, RailType type) +void CurvedTrackHelper::generate_curved_railMesh(IMeshBufferPtr buf, + int base_radius, RailType type) { - const float edgeWidth = (1 - GAUGE - RAIL_WIDTH)/2.0f; - const float R = static_cast(baseRadius) - edgeWidth + const float edge_width = (1 - GAUGE - RAIL_WIDTH)/2.0f; + const float R = static_cast(base_radius) - edge_width - (type == OUTER_RAIL ? 0 : GAUGE); const float r = R - RAIL_WIDTH; @@ -227,10 +227,10 @@ void CurvedTrackHelper::generateCurvedRailMesh(IMeshBufferPtr buf, // Top of rail for (float theta = 0; theta < M_PI / 2.0f; theta += step) { - buf->addQuad(makeVector(r * cos(theta), 0.1f, r * sin(theta)), - makeVector(r * cos(theta + step), 0.1f, r * sin(theta + step)), - makeVector(R * cos(theta + step), 0.1f, R * sin(theta + step)), - makeVector(R * cos(theta), 0.1f, R * sin(theta)), + buf->add_quad(make_vector(r * cos(theta), 0.1f, r * sin(theta)), + make_vector(r * cos(theta + step), 0.1f, r * sin(theta + step)), + make_vector(R * cos(theta + step), 0.1f, R * sin(theta + step)), + make_vector(R * cos(theta), 0.1f, R * sin(theta)), METAL); } @@ -241,17 +241,17 @@ void CurvedTrackHelper::generateCurvedRailMesh(IMeshBufferPtr buf, const float sinT1 = sin(theta + step); const float cosT1 = cos(theta + step); - buf->addQuad(// Vertices - makeVector(R * cosT1, 0.1f, R * sinT1), - makeVector(R * cosT1, 0.0f, R * sinT1), - makeVector(R * cosT, 0.0f, R * sinT), - makeVector(R * cosT, 0.1f, R * sinT), + buf->add_quad(// Vertices + make_vector(R * cosT1, 0.1f, R * sinT1), + make_vector(R * cosT1, 0.0f, R * sinT1), + make_vector(R * cosT, 0.0f, R * sinT), + make_vector(R * cosT, 0.1f, R * sinT), // Normals - makeVector(cosT1, 0.0f, sinT1), - makeVector(cosT1, 0.0f, sinT1), - makeVector(cosT, 0.0f, sinT), - makeVector(cosT, 0.0f, sinT), + make_vector(cosT1, 0.0f, sinT1), + make_vector(cosT1, 0.0f, sinT1), + make_vector(cosT, 0.0f, sinT), + make_vector(cosT, 0.0f, sinT), METAL); } @@ -263,61 +263,61 @@ void CurvedTrackHelper::generateCurvedRailMesh(IMeshBufferPtr buf, const float sinT1 = sin(theta + step); const float cosT1 = cos(theta + step); - buf->addQuad(// Vertices - makeVector(r * cosT, 0.1f, r * sinT), - makeVector(r * cosT, 0.0f, r * sinT), - makeVector(r * cosT1, 0.0f, r * sinT1), - makeVector(r * cosT1, 0.1f, r * sinT1), + buf->add_quad(// Vertices + make_vector(r * cosT, 0.1f, r * sinT), + make_vector(r * cosT, 0.0f, r * sinT), + make_vector(r * cosT1, 0.0f, r * sinT1), + make_vector(r * cosT1, 0.1f, r * sinT1), // Normals - makeVector(-cosT, 0.0f, -sinT), - makeVector(-cosT, 0.0f, -sinT), - makeVector(-cosT1, 0.0f, -sinT1), - makeVector(-cosT1, 0.0f, -sinT1), + make_vector(-cosT, 0.0f, -sinT), + make_vector(-cosT, 0.0f, -sinT), + make_vector(-cosT1, 0.0f, -sinT1), + make_vector(-cosT1, 0.0f, -sinT1), METAL); } } -void CurvedTrackHelper::mergeCurvedRail(IMeshBufferPtr buf, int baseRadius, - Vector off, float yAngle) +void CurvedTrackHelper::merge_curved_rail(IMeshBufferPtr buf, int base_radius, + Vector off, float y_angle) { - IMeshBufferPtr railBuf; + IMeshBufferPtr rail_buf; - CurvedRailMeshMap::iterator it = curvedRailMeshes.find(baseRadius); - if (it != curvedRailMeshes.end()) - railBuf = (*it).second; + CurvedRailMeshMap::iterator it = curved_rail_meshes.find(base_radius); + if (it != curved_rail_meshes.end()) + rail_buf = (*it).second; else { - railBuf = makeMeshBuffer(); + rail_buf = make_mesh_buffer(); - generateCurvedRailMesh(railBuf, baseRadius, INNER_RAIL); - generateCurvedRailMesh(railBuf, baseRadius, OUTER_RAIL); + generate_curved_railMesh(rail_buf, base_radius, INNER_RAIL); + generate_curved_railMesh(rail_buf, base_radius, OUTER_RAIL); - curvedRailMeshes[baseRadius] = railBuf; + curved_rail_meshes[base_radius] = rail_buf; } - buf->merge(railBuf, off, yAngle); + buf->merge(rail_buf, off, y_angle); } -void CurvedTrackHelper::mergeCurvedTrack(IMeshBufferPtr buf, Vector off, - int baseRadius, track::Angle startAngle, track::Angle endAngle) const +void CurvedTrackHelper::merge_curved_track(IMeshBufferPtr buf, Vector off, + int base_radius, track::Angle start_angle, track::Angle end_angle) const { - transformToOrigin(off, baseRadius, startAngle); + transform_to_origin(off, base_radius, start_angle); - mergeCurvedRail(buf, baseRadius, off, static_cast(startAngle)); + merge_curved_rail(buf, base_radius, off, static_cast(start_angle)); const float length = - degToRad(static_cast(endAngle - startAngle)) * baseRadius; - const int numSleepers = static_cast(length * SLEEPERS_PER_UNIT); - const float sleeperAngle = - static_cast(endAngle - startAngle) / numSleepers; + deg_to_rad(static_cast(end_angle - start_angle)) * base_radius; + const int num_sleepers = static_cast(length * SLEEPERS_PER_UNIT); + const float sleeper_angle = + static_cast(end_angle - start_angle) / num_sleepers; - for (int i = 0; i < numSleepers; i++) { + for (int i = 0; i < num_sleepers; i++) { - float yAngle = static_cast(startAngle) + (i + 0.5f)*sleeperAngle; + float y_angle = static_cast(start_angle) + (i + 0.5f)*sleeper_angle; Vector t = - makeVector(0.0f, 0.0f, static_cast(baseRadius) - 0.5f); + make_vector(0.0f, 0.0f, static_cast(base_radius) - 0.5f); - mergeSleeper(buf, off + rotateY(t, yAngle), yAngle); + merge_sleeper(buf, off + rotateY(t, y_angle), y_angle); } } diff --git a/src/Train.cpp b/src/Train.cpp index c81fbd5..2e4fa93 100644 --- a/src/Train.cpp +++ b/src/Train.cpp @@ -32,39 +32,39 @@ // Concrete implementation of trains class Train : public ITrain { public: - Train(IMapPtr aMap); + Train(IMapPtr a_map); void render() const; - void update(int aDelta); + void update(int a_delta); Vector front() const; - ITrackSegmentPtr trackSegment() const; + ITrackSegmentPtr track_segment() const; track::Direction direction() const; - track::Position tile() const { return engine().travelToken.position; } + track::Position tile() const { return engine().travel_token.position; } double speed() const { return parts.front().vehicle->speed(); } IControllerPtr controller() { return parts.front().vehicle->controller(); } private: // The different parts of the train are on different track segments struct Part : boost::equality_comparable { - explicit Part(IRollingStockPtr aVehicle) - : vehicle(aVehicle), segmentDelta(0.0), movementSign(1.0) + explicit Part(IRollingStockPtr a_vehicle) + : vehicle(a_vehicle), segment_delta(0.0), movement_sign(1.0) {} IRollingStockPtr vehicle; // The length of a track segment can be found by calling - // segmentLength() This delta value ranges from 0 to that length and + // segment_length() This delta value ranges from 0 to that length and // indicates how far along the segment the train is ITrackSegmentPtr segment; - float segmentDelta; - track::TravelToken travelToken; + float segment_delta; + track::TravelToken travel_token; // Direction train part is travelling along the track Vector direction; // Handles reversal mid-segment - float movementSign; + float movement_sign; bool operator==(const Part& other) const { @@ -75,22 +75,22 @@ private: const Part& engine() const; Part& engine(); - void move(double aDistance); - void addPart(IRollingStockPtr aVehicle); - Vector partPosition(const Part& aPart) const; - void updateSmokePosition(int aDelta); - void movePart(Part& part, double distance); - - static track::Connection reverseToken(const track::TravelToken& token); - static void transformToPart(const Part& p); + void move(double a_distance); + void add_part(IRollingStockPtr a_vehicle); + Vector part_position(const Part& a_part) const; + void update_smoke_position(int a_delta); + void move_part(Part& part, double distance); + + static track::Connection reverse_token(const track::TravelToken& token); + static void transform_to_part(const Part& p); IMapPtr map; - ISmokeTrailPtr smokeTrail; + ISmokeTrailPtr smoke_trail; - Vector velocityVector; + Vector velocity_vector; // Move part of the train across a connection - void enterSegment(Part& aPart, const track::Connection& aConnection); + void enter_segment(Part& a_part, const track::Connection& a_connection); // Seperation between waggons static const double SEPARATION; @@ -98,28 +98,28 @@ private: const double Train::SEPARATION(0.15); -Train::Train(IMapPtr aMap) - : map(aMap), velocityVector(makeVector(0.0f, 0.0f, 0.0f)) +Train::Train(IMapPtr a_map) + : map(a_map), velocity_vector(make_vector(0.0f, 0.0f, 0.0f)) { - parts.push_front(Part(loadEngine("pclass"))); + parts.push_front(Part(load_engine("pclass"))); - enterSegment(engine(), aMap->start()); + enter_segment(engine(), a_map->start()); // Bit of a hack to put the engine in the right place move(0.275); #if 1 for (int i = 1; i <= 4; i++) - addPart(loadWaggon("coal_truck")); + add_part(load_waggon("coal_truck")); #endif - smokeTrail = makeSmokeTrail(); + smoke_trail = make_smoke_trail(); } -void Train::addPart(IRollingStockPtr aVehicle) +void Train::add_part(IRollingStockPtr a_vehicle) { - Part part(aVehicle); - enterSegment(part, map->start()); + Part part(a_vehicle); + enter_segment(part, map->start()); // Push the rest of the train along some move(part.vehicle->length() + SEPARATION); @@ -139,32 +139,32 @@ const Train::Part& Train::engine() const return parts.front(); } -void Train::movePart(Part& part, double distance) +void Train::move_part(Part& part, double distance) { // Never move in units greater than 1.0 double d = abs(distance); - double sign = (distance >= 0.0 ? 1.0 : -1.0) * part.movementSign; + double sign = (distance >= 0.0 ? 1.0 : -1.0) * part.movement_sign; const double step = 0.25; //debug() << "move d=" << distance << " s=" << sign - // << " ms=" << part.movementSign; + // << " ms=" << part.movement_sign; do { - part.segmentDelta += min(step, d) * sign; + part.segment_delta += min(step, d) * sign; - const double segmentLength = - part.segment->segmentLength(part.travelToken); - if (part.segmentDelta >= segmentLength) { + const double segment_length = + part.segment->segment_length(part.travel_token); + if (part.segment_delta >= segment_length) { // Moved onto a new piece of track - const double over = part.segmentDelta - segmentLength; - enterSegment(part, part.segment->nextPosition(part.travelToken)); - part.segmentDelta = over; + const double over = part.segment_delta - segment_length; + enter_segment(part, part.segment->next_position(part.travel_token)); + part.segment_delta = over; } - else if (part.segmentDelta < 0.0) { - track::Connection prev = reverseToken(part.travelToken); - enterSegment(part, prev); - part.segmentDelta *= -1.0; - part.movementSign *= -1.0; + else if (part.segment_delta < 0.0) { + track::Connection prev = reverse_token(part.travel_token); + enter_segment(part, prev); + part.segment_delta *= -1.0; + part.movement_sign *= -1.0; } d -= step; @@ -172,106 +172,106 @@ void Train::movePart(Part& part, double distance) } // Move the train along the line a bit -void Train::move(double aDistance) +void Train::move(double a_distance) { using namespace placeholders; for (list::iterator it = parts.begin(); it != parts.end(); ++it) - movePart(*it, aDistance); + move_part(*it, a_distance); } -void Train::updateSmokePosition(int aDelta) +void Train::update_smoke_position(int a_delta) { const Part& e = engine(); glPushMatrix(); glLoadIdentity(); - transformToPart(e); + transform_to_part(e); - const float smokeOffX = 0.63f; - const float smokeOffY = 1.04f; - glTranslatef(smokeOffX, smokeOffY, 0.0f); + const float smoke_offX = 0.63f; + const float smoke_offY = 1.04f; + glTranslatef(smoke_offX, smoke_offY, 0.0f); float matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, matrix); glPopMatrix(); - smokeTrail->setPosition(matrix[12], matrix[13], matrix[14]); - smokeTrail->setVelocity( - velocityVector.x, - velocityVector.y, - velocityVector.z); - smokeTrail->update(aDelta); + smoke_trail->set_position(matrix[12], matrix[13], matrix[14]); + smoke_trail->set_velocity( + velocity_vector.x, + velocity_vector.y, + velocity_vector.z); + smoke_trail->update(a_delta); // Make the rate at which new particles are created proportional // to the throttle of the controller const int throttle = e.vehicle->controller()->throttle(); - const int baseDelay = 200; + const int base_delay = 200; - smokeTrail->setDelay(baseDelay - (throttle * 15)); + smoke_trail->set_delay(base_delay - (throttle * 15)); } void Train::update(int delta) { - double gravitySum = 0.0; + double gravity_sum = 0.0; for (list::iterator it = parts.begin(); it != parts.end(); ++it) { - float gradient = (*it).travelToken.gradient((*it).segmentDelta); + float gradient = (*it).travel_token.gradient((*it).segment_delta); if ((*it).direction.x < 0 || (*it).direction.z < 0) gradient *= -1.0f; - gradient *= (*it).movementSign; + gradient *= (*it).movement_sign; const double g = 9.78; - gravitySum += -g * gradient * (*it).vehicle->mass(); + gravity_sum += -g * gradient * (*it).vehicle->mass(); } for (list::iterator it = parts.begin(); it != parts.end(); ++it) - (*it).vehicle->update(delta, gravitySum); + (*it).vehicle->update(delta, gravity_sum); - updateSmokePosition(delta); + update_smoke_position(delta); // How many metres does a tile correspond to? const double M_PER_UNIT = 5.0; - const Vector oldPos = partPosition(engine()); + const Vector old_pos = part_position(engine()); - const double deltaSeconds = static_cast(delta) / 1000.0f; - move(engine().vehicle->speed() * deltaSeconds / M_PER_UNIT); + const double delta_seconds = static_cast(delta) / 1000.0f; + move(engine().vehicle->speed() * delta_seconds / M_PER_UNIT); - velocityVector = partPosition(engine()) - oldPos; + velocity_vector = part_position(engine()) - old_pos; } // Called when the train enters a new segment // Resets the delta and gets the length of the new segment -void Train::enterSegment(Part& aPart, const track::Connection& aConnection) +void Train::enter_segment(Part& a_part, const track::Connection& a_connection) { Point pos; - tie(pos, aPart.direction) = aConnection; + tie(pos, a_part.direction) = a_connection; -#if 0 +#if 1 debug() << "Train part entered segment at " << pos - << " moving " << aPart.direction; + << " moving " << a_part.direction; #endif - if (!map->isValidTrack(pos)) + if (!map->is_valid_track(pos)) throw runtime_error("Train fell off end of track!"); - aPart.segmentDelta = 0.0; - aPart.segment = map->trackAt(pos); - aPart.travelToken = aPart.segment->getTravelToken(pos, aPart.direction); + a_part.segment_delta = 0.0; + a_part.segment = map->track_at(pos); + a_part.travel_token = a_part.segment->get_travel_token(pos, a_part.direction); } -void Train::transformToPart(const Part& p) +void Train::transform_to_part(const Part& p) { - p.travelToken.transform(p.segmentDelta); + p.travel_token.transform(p.segment_delta); // If we're going backwards, flip the train around - if (p.movementSign < 0.0) + if (p.movement_sign < 0.0) glRotatef(180.0f, 0.0f, 1.0f, 0.0f); } @@ -281,7 +281,7 @@ void Train::render() const it != parts.end(); ++it) { glPushMatrix(); - transformToPart(*it); + transform_to_part(*it); glTranslatef(0.0f, track::RAIL_HEIGHT, 0.0f); (*it).vehicle->render(); @@ -289,17 +289,17 @@ void Train::render() const glPopMatrix(); } - smokeTrail->render(); + smoke_trail->render(); } -ITrackSegmentPtr Train::trackSegment() const +ITrackSegmentPtr Train::track_segment() const { return engine().segment; } Vector Train::front() const { - return partPosition(engine()); + return part_position(engine()); } track::Direction Train::direction() const @@ -308,27 +308,27 @@ track::Direction Train::direction() const } // Calculate the position of any train part -Vector Train::partPosition(const Part& aPart) const +Vector Train::part_position(const Part& a_part) const { // Call the transformer to compute the world location glPushMatrix(); glLoadIdentity(); - aPart.travelToken.transform(aPart.segmentDelta); + a_part.travel_token.transform(a_part.segment_delta); float matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, matrix); glPopMatrix(); - return makeVector(matrix[12], matrix[13], matrix[14]); + return make_vector(matrix[12], matrix[13], matrix[14]); } // Compute a connection object that reverses the train's // direction of travel -track::Connection Train::reverseToken(const track::TravelToken& token) +track::Connection Train::reverse_token(const track::TravelToken& token) { - track::Position pos = makePoint( + track::Position pos = make_point( token.position.x - token.direction.x, token.position.y - token.direction.z); @@ -338,7 +338,7 @@ track::Connection Train::reverseToken(const track::TravelToken& token) } // Make an empty train -ITrainPtr makeTrain(IMapPtr aMap) +ITrainPtr make_train(IMapPtr a_map) { - return ITrainPtr(new Train(aMap)); + return ITrainPtr(new Train(a_map)); } diff --git a/src/Tree.cpp b/src/Tree.cpp index 35b25f2..cfd64dc 100644 --- a/src/Tree.cpp +++ b/src/Tree.cpp @@ -36,16 +36,16 @@ public: // IScenery interface void render() const; - void setPosition(float x, float y, float z); - void setAngle(float a) { angle = a; } + void set_position(float x, float y, float z); + void set_angle(float a) { angle = a; } const string& name() const { return name_; } void merge(IMeshBufferPtr buf); // IXMLCallback interface - void text(const string& localName, const string& content); + void text(const string& local_name, const string& content); // IXMLSerialisable interface - xml::element toXml() const; + xml::element to_xml() const; private: Vector position; @@ -54,46 +54,46 @@ private: string name_; struct ParserState { - string modelFile; + string model_file; float scale; IResourcePtr res; - } *parserState; + } *parser_state; }; Tree::Tree(IResourcePtr res) { static IXMLParserPtr parser = makeXMLParser("schemas/tree.xsd"); - parserState = new ParserState; - parserState->res = res; + parser_state = new ParserState; + parser_state->res = res; - parser->parse(res->xmlFileName(), *this); + parser->parse(res->xml_file_name(), *this); - model = loadModel(res, parserState->modelFile, parserState->scale); + model = load_model(res, parser_state->model_file, parser_state->scale); - delete parserState; + delete parser_state; } -void Tree::text(const string& localName, const string& content) +void Tree::text(const string& local_name, const string& content) { - if (localName == "model") - parserState->modelFile = content; - else if (localName == "scale") - parserState->scale = boost::lexical_cast(content); - else if (localName == "name") { - const string& expectedName = parserState->res->name(); - if (content != expectedName) + if (local_name == "model") + parser_state->model_file = content; + else if (local_name == "scale") + parser_state->scale = boost::lexical_cast(content); + else if (local_name == "name") { + const string& expected_name = parser_state->res->name(); + if (content != expected_name) throw runtime_error( - "Expected tree name to be '" + expectedName + "Expected tree name to be '" + expected_name + "' but found'" + content + "' in XML"); else name_ = content; } } -void Tree::setPosition(float x, float y, float z) +void Tree::set_position(float x, float y, float z) { - position = makeVector(x, y, z); + position = make_vector(x, y, z); } void Tree::render() const @@ -112,40 +112,40 @@ void Tree::merge(IMeshBufferPtr buf) model->merge(buf, position, angle); } -xml::element Tree::toXml() const +xml::element Tree::to_xml() const { return xml::element("tree") - .addAttribute("angle", angle) - .addAttribute("name", name_); + .add_attribute("angle", angle) + .add_attribute("name", name_); } namespace { - Tree* loadTreeXml(IResourcePtr res) + Tree* load_tree_xml(IResourcePtr res) { - log() << "Loading tree from " << res->xmlFileName(); + log() << "Loading tree from " << res->xml_file_name(); return new Tree(res); } - shared_ptr loadTreeFromCache(const string& name) + shared_ptr load_tree_fromCache(const string& name) { - static ResourceCache cache(loadTreeXml, "trees"); - return cache.loadCopy(name); + static ResourceCache cache(load_tree_xml, "trees"); + return cache.load_copy(name); } } -ISceneryPtr loadTree(const string& name) +ISceneryPtr load_tree(const string& name) { - shared_ptr tree = loadTreeFromCache(name); + shared_ptr tree = load_tree_fromCache(name); // Randomise the new tree's angle - static Uniform angleRand(0.0f, 360.0f); - tree.get()->setAngle(angleRand()); + static Uniform angle_rand(0.0f, 360.0f); + tree.get()->set_angle(angle_rand()); return ISceneryPtr(tree); } -ISceneryPtr loadTree(const AttributeSet& attrs) +ISceneryPtr load_tree(const AttributeSet& attrs) { // Unserialise a tree float angle; @@ -153,8 +153,8 @@ ISceneryPtr loadTree(const AttributeSet& attrs) attrs.get("name", name); attrs.get("angle", angle); - shared_ptr tree = loadTreeFromCache(name); - tree->setAngle(angle); + shared_ptr tree = load_tree_fromCache(name); + tree->set_angle(angle); return ISceneryPtr(tree); } diff --git a/src/UIDemo.cpp b/src/UIDemo.cpp index b8cfd1a..9877526 100644 --- a/src/UIDemo.cpp +++ b/src/UIDemo.cpp @@ -27,16 +27,16 @@ public: UIDemo(); // IScreen interface - void display(IGraphicsPtr aContext) const {} + void display(IGraphicsPtr a_context) const {} void overlay() const; - void update(IPickBufferPtr aPickBuffer, int aDelta) {} - void onKeyDown(SDLKey aKey) {} - void onKeyUp(SDLKey aKey) {} - void onMouseMove(IPickBufferPtr aPickBuffer, int x, int y, + void update(IPickBufferPtr a_pick_buffer, int a_delta) {} + void on_key_down(SDLKey a_key) {} + void on_key_up(SDLKey a_key) {} + void on_mouse_move(IPickBufferPtr a_pick_buffer, int x, int y, int xrel, int yrel) {} - void onMouseClick(IPickBufferPtr pick_buffer, int x, int y, + void on_mouse_click(IPickBufferPtr pick_buffer, int x, int y, MouseButton button); - void onMouseRelease(IPickBufferPtr pick_buffer, int x, int y, + void on_mouse_release(IPickBufferPtr pick_buffer, int x, int y, MouseButton button) {} private: @@ -49,7 +49,7 @@ UIDemo::UIDemo() { using namespace placeholders; - layout = gui::makeLayout("layouts/demo.xml"); + layout = gui::make_layout("layouts/demo.xml"); layout->get("/wnd1/btn1").connect(gui::Widget::SIG_CLICK, bind(&UIDemo::btn1Click, this, _1)); @@ -69,7 +69,7 @@ void UIDemo::overlay() const layout->render(); } -void UIDemo::onMouseClick(IPickBufferPtr pick_buffer, int x, int y, +void UIDemo::on_mouse_click(IPickBufferPtr pick_buffer, int x, int y, MouseButton button) { layout->click(x, y); diff --git a/src/Waggon.cpp b/src/Waggon.cpp index b17ccc0..835613a 100644 --- a/src/Waggon.cpp +++ b/src/Waggon.cpp @@ -29,7 +29,7 @@ using namespace std; // All cargo waggons class Waggon : public IRollingStock, public IXMLCallback { public: - Waggon(IResourcePtr aRes); + Waggon(IResourcePtr a_res); ~Waggon() {} // IRollingStock interface @@ -41,7 +41,7 @@ public: float length() const { return model->dimensions().x; } // IXMLCallback interface - void text(const string& localName, const string& aString); + void text(const string& local_name, const string& a_string); private: IModelPtr model; IResourcePtr resource; @@ -51,19 +51,19 @@ private: const float Waggon::MODEL_SCALE(0.4f); -Waggon::Waggon(IResourcePtr aRes) - : resource(aRes) +Waggon::Waggon(IResourcePtr a_res) + : resource(a_res) { static IXMLParserPtr parser = makeXMLParser("schemas/waggon.xsd"); - parser->parse(resource->xmlFileName(), *this); + parser->parse(resource->xml_file_name(), *this); } // Load information from the XML file -void Waggon::text(const string& localName, const string& aString) +void Waggon::text(const string& local_name, const string& a_string) { - if (localName == "model") { - model = loadModel(resource, aString, MODEL_SCALE); + if (local_name == "model") { + model = load_model(resource, a_string, MODEL_SCALE); model->cache(); } } @@ -84,18 +84,18 @@ IControllerPtr Waggon::controller() } namespace { - Waggon* loadWaggonXml(IResourcePtr aRes) + Waggon* load_waggon_xml(IResourcePtr a_res) { - log() << "Loading waggon from " << aRes->xmlFileName(); + log() << "Loading waggon from " << a_res->xml_file_name(); - return new Waggon(aRes); + return new Waggon(a_res); } } // Load a waggon from a resource file -IRollingStockPtr loadWaggon(const string& aResId) +IRollingStockPtr load_waggon(const string& a_res_id) { - static ResourceCache cache(loadWaggonXml, "waggons"); - return cache.loadCopy(aResId); + static ResourceCache cache(load_waggon_xml, "waggons"); + return cache.load_copy(a_res_id); } diff --git a/src/XMLParser.cpp b/src/XMLParser.cpp index 0e2a397..facb3b6 100644 --- a/src/XMLParser.cpp +++ b/src/XMLParser.cpp @@ -34,74 +34,74 @@ using namespace xercesc; // SAX2 handler to call our own methods struct SAX2WrapperHandler : public DefaultHandler { - SAX2WrapperHandler() : callbackPtr(NULL) {} + SAX2WrapperHandler() : callback_ptr(NULL) {} - void startElement(const XMLCh* const uri, + void start_element(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const Attributes& attrs) { - char* chLocalname = XMLString::transcode(localname); + char* ch_localname = XMLString::transcode(localname); - callbackPtr->startElement(chLocalname, AttributeSet(attrs)); + callback_ptr->start_element(ch_localname, AttributeSet(attrs)); - XMLString::release(&chLocalname); + XMLString::release(&ch_localname); } void characters(const XMLCh* const buf, const XMLSize_t length) { - char* chBuf = XMLString::transcode(buf); + char* ch_buf = XMLString::transcode(buf); - charBuf << chBuf; + char_buf << ch_buf; - XMLString::release(&chBuf); + XMLString::release(&ch_buf); } - void endElement(const XMLCh* const uri, + void end_element(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname) { - char* chLocalname = XMLString::transcode(localname); + char* ch_localname = XMLString::transcode(localname); - if (charBuf.str().size() > 0) { - callbackPtr->text(chLocalname, charBuf.str()); - charBuf.str(""); + if (char_buf.str().size() > 0) { + callback_ptr->text(ch_localname, char_buf.str()); + char_buf.str(""); } - callbackPtr->endElement(chLocalname); + callback_ptr->end_element(ch_localname); - XMLString::release(&chLocalname); + XMLString::release(&ch_localname); } void error(const SAXParseException& e) { throw e; } - void fatalError(const SAXParseException& e) { throw e; } + void fatal_error(const SAXParseException& e) { throw e; } - IXMLCallback* callbackPtr; - ostringstream charBuf; + IXMLCallback* callback_ptr; + ostringstream char_buf; }; // Concrete XML parser using Xerces class XercesXMLParser : public IXMLParser { public: - XercesXMLParser(const string& aSchemaFile); + XercesXMLParser(const string& a_schema_file); ~XercesXMLParser(); - void parse(const string& aFileName, IXMLCallback& aCallback); + void parse(const string& a_file_name, IXMLCallback& a_callback); private: - SAX2XMLReader* myReader; - SAX2WrapperHandler* myHandler; + SAX2XMLReader* my_reader; + SAX2WrapperHandler* my_handler; - static int ourParserCount; + static int our_parser_count; }; // Number of parsers in use -int XercesXMLParser::ourParserCount(0); +int XercesXMLParser::our_parser_count(0); -XercesXMLParser::XercesXMLParser(const string& aSchemaFile) +XercesXMLParser::XercesXMLParser(const string& a_schema_file) { - log() << "Creating parser for XML schema " << aSchemaFile; + log() << "Creating parser for XML schema " << a_schema_file; - if (ourParserCount++ == 0) { + if (our_parser_count++ == 0) { // Initialise Xerces for the first time try { XMLPlatformUtils::Initialize(); @@ -119,38 +119,38 @@ XercesXMLParser::XercesXMLParser(const string& aSchemaFile) log() << "Xerces initialised"; } - myReader = XMLReaderFactory::createXMLReader(); + my_reader = XMLReaderFactory::createXMLReader(); - myReader->setFeature(XMLUni::fgSAX2CoreValidation, true); - myReader->setFeature(XMLUni::fgSAX2CoreNameSpaces, true); - myReader->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true); - myReader->setFeature(XMLUni::fgXercesDynamic, false); - myReader->setFeature(XMLUni::fgXercesSchema, true); + my_reader->setFeature(XMLUni::fgSAX2CoreValidation, true); + my_reader->setFeature(XMLUni::fgSAX2CoreNameSpaces, true); + my_reader->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true); + my_reader->setFeature(XMLUni::fgXercesDynamic, false); + my_reader->setFeature(XMLUni::fgXercesSchema, true); // Full checking (can be slow) - myReader->setFeature(XMLUni::fgXercesSchemaFullChecking, true); + my_reader->setFeature(XMLUni::fgXercesSchemaFullChecking, true); // Enable grammar caching - myReader->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true); + my_reader->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true); - XMLCh* schemaName = XMLString::transcode(aSchemaFile.c_str()); + XMLCh* schema_name = XMLString::transcode(a_schema_file.c_str()); - myHandler = new SAX2WrapperHandler; - myReader->setContentHandler(myHandler); - myReader->setErrorHandler(myHandler); - myReader->setEntityResolver(myHandler); + my_handler = new SAX2WrapperHandler; + my_reader->setContentHandler(my_handler); + my_reader->setErrorHandler(my_handler); + my_reader->setEntityResolver(my_handler); // Cache the grammar try { - myReader->loadGrammar(schemaName, Grammar::SchemaGrammarType, true); + my_reader->loadGrammar(schema_name, Grammar::SchemaGrammarType, true); // Always use the cached grammar - myReader->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true); + my_reader->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true); } catch (const SAXParseException& e) { char* message = XMLString::transcode(e.getMessage()); error() << "SAXParseException: " << message; - error() << "At " << aSchemaFile << " line " + error() << "At " << a_schema_file << " line " << e.getLineNumber() << " col " << e.getColumnNumber(); XMLString::release(&message); @@ -158,26 +158,26 @@ XercesXMLParser::XercesXMLParser(const string& aSchemaFile) throw runtime_error("Failed to load XML schema"); } - XMLString::release(&schemaName); + XMLString::release(&schema_name); } XercesXMLParser::~XercesXMLParser() { - delete myReader; - delete myHandler; + delete my_reader; + delete my_handler; } -void XercesXMLParser::parse(const string& aFileName, IXMLCallback& aCallback) +void XercesXMLParser::parse(const string& a_file_name, IXMLCallback& a_callback) { - myHandler->callbackPtr = &aCallback; + my_handler->callback_ptr = &a_callback; try { - myReader->parse(aFileName.c_str()); + my_reader->parse(a_file_name.c_str()); } catch (const SAXParseException& e) { char* message = XMLString::transcode(e.getMessage()); error() << "SAXParseException: " << message; - error() << "At " << aFileName << " line " + error() << "At " << a_file_name << " line " << e.getLineNumber() << " col " << e.getColumnNumber(); XMLString::release(&message); @@ -185,11 +185,11 @@ void XercesXMLParser::parse(const string& aFileName, IXMLCallback& aCallback) throw runtime_error("Failed to load XML file"); } - myHandler->callbackPtr = NULL; + my_handler->callback_ptr = NULL; } // Create a Xerces parser for a schema and return a handle to it -IXMLParserPtr makeXMLParser(const std::string& aSchemaFile) +IXMLParserPtr makeXMLParser(const std::string& a_schema_file) { - return IXMLParserPtr(new XercesXMLParser(aSchemaFile)); + return IXMLParserPtr(new XercesXMLParser(a_schema_file)); } diff --git a/src/gui/Button.cpp b/src/gui/Button.cpp index 5cc947b..af68be2 100644 --- a/src/gui/Button.cpp +++ b/src/gui/Button.cpp @@ -31,7 +31,7 @@ void Button::render(RenderContext& rc) const rc.rectangle(x(), y(), width(), height(), rc.theme().background()); - IFontPtr f = rc.theme().normalFont(); + IFontPtr f = rc.theme().normal_font(); int center = (height() - f->height()) / 2; diff --git a/src/gui/Canvas3D.cpp b/src/gui/Canvas3D.cpp index cdb66a8..17e419b 100644 --- a/src/gui/Canvas3D.cpp +++ b/src/gui/Canvas3D.cpp @@ -41,7 +41,7 @@ void Canvas3D::render(RenderContext& rc) const int xo = x(), yo = y(); rc.offset(xo, yo); - glViewport(xo, getGameWindow()->height() - yo - height(), + glViewport(xo, get_game_window()->height() - yo - height(), width(), height()); glMatrixMode(GL_PROJECTION); diff --git a/src/gui/ContainerWidget.cpp b/src/gui/ContainerWidget.cpp index 397ad1d..0803287 100644 --- a/src/gui/ContainerWidget.cpp +++ b/src/gui/ContainerWidget.cpp @@ -28,8 +28,8 @@ ContainerWidget::ContainerWidget(const AttributeSet& attrs) void ContainerWidget::render(RenderContext& rc) const { - for (ChildList::const_iterator it = constBegin(); - it != constEnd(); ++it) { + for (ChildList::const_iterator it = const_begin(); + it != const_end(); ++it) { if ((*it)->visible()) { rc.scissor(*it); (*it)->render(rc); @@ -37,43 +37,43 @@ void ContainerWidget::render(RenderContext& rc) const } } -void ContainerWidget::addChild(Widget* w) +void ContainerWidget::add_child(Widget* w) { children.push_back(w); - childAdded(w); + child_added(w); } -void ContainerWidget::adjustForTheme(const Theme& theme) +void ContainerWidget::adjust_for_theme(const Theme& theme) { - for (ChildList::const_iterator it = constBegin(); - it != constEnd(); ++it) - (*it)->adjustForTheme(theme); + for (ChildList::const_iterator it = const_begin(); + it != const_end(); ++it) + (*it)->adjust_for_theme(theme); } -bool ContainerWidget::handleClick(int x, int y) +bool ContainerWidget::handle_click(int x, int y) { if (!visible()) return false; bool accepted = false; - for (ChildList::const_iterator it = constBegin(); - it != constEnd(); ++it) { + for (ChildList::const_iterator it = const_begin(); + it != const_end(); ++it) { Widget& w = **it; if (w.x() <= x && x < w.x() + w.width() && w.y() <= y && y < w.y() + w.height()) - accepted |= w.handleClick(x - w.x(), y - w.y()); + accepted |= w.handle_click(x - w.x(), y - w.y()); } - bool inContainer = this->x() <= x && x < this->x() + this->width() + bool in_container = this->x() <= x && x < this->x() + this->width() && this->y() <= y && y < this->y() + this->height(); - accepted |= inContainer; + accepted |= in_container; return accepted; } -int ContainerWidget::countChildren() +int ContainerWidget::count_children() { return children.size(); } diff --git a/src/gui/Font.cpp b/src/gui/Font.cpp index 02ce502..0b4616b 100644 --- a/src/gui/Font.cpp +++ b/src/gui/Font.cpp @@ -35,7 +35,7 @@ using namespace gui; class Glyph { public: - Glyph(FT_Face& face, FT_ULong uch, FontType type, bool dropShadow); + Glyph(FT_Face& face, FT_ULong uch, FontType type, bool drop_shadow); ~Glyph(); void render() const; @@ -48,18 +48,18 @@ public: private: static int next_power_of_2(int a); - void renderGlyph() const; + void render_glyph() const; GLuint tex; float width_, height_; float tex_xmax, tex_ymax; float top, left; float advance_x_, advance_y_; - bool dropShadow; + bool drop_shadow; }; -Glyph::Glyph(FT_Face& face, FT_ULong uch, FontType type, bool dropShadow) - : dropShadow(dropShadow) +Glyph::Glyph(FT_Face& face, FT_ULong uch, FontType type, bool drop_shadow) + : drop_shadow(drop_shadow) { int index = FT_Get_Char_Index(face, uch); @@ -153,7 +153,7 @@ Glyph::~Glyph() glDeleteTextures(1, &tex); } -void Glyph::renderGlyph() const +void Glyph::render_glyph() const { glBegin(GL_QUADS); @@ -176,19 +176,19 @@ void Glyph::render() const { glBindTexture(GL_TEXTURE_2D, tex); - if (dropShadow) { + if (drop_shadow) { glPushMatrix(); glPushAttrib(GL_CURRENT_BIT); glTranslatef(1.5f, 1.5f, 0.0f); glColor3f(0.0f, 0.0f, 0.0f); - renderGlyph(); + render_glyph(); glPopAttrib(); glPopMatrix(); } - renderGlyph(); + render_glyph(); glTranslatef(advance_x_, advance_y_, 0.0f); } @@ -206,7 +206,7 @@ namespace {// REMOVE class Font : public IFont { public: - Font(const string& file, int h, FontType type, bool dropShadow); + Font(const string& file, int h, FontType type, bool drop_shadow); ~Font(); void print(int x, int y, Colour c, const string& s) const; @@ -226,7 +226,7 @@ private: FT_Library Font::library; int Font::library_ref_count = 0; - Font::Font(const string& file, int h, FontType type, bool dropShadow) + Font::Font(const string& file, int h, FontType type, bool drop_shadow) { if (++library_ref_count == 1) { if (FT_Init_FreeType(&library)) @@ -245,7 +245,7 @@ int Font::library_ref_count = 0; 0, 0); // Default DPI for (char ch = 0; ch < 127; ch++) - glyphs.push_back(new Glyph(face, ch, type, dropShadow)); + glyphs.push_back(new Glyph(face, ch, type, drop_shadow)); int ascent = static_cast(face->size->metrics.ascender / 64.0); int descent = static_cast(face->size->metrics.descender / 64.0); @@ -299,19 +299,19 @@ int Font::text_width(const string& s) const } } -IFontPtr gui::loadFont(const string& file, int h, FontType type, - bool dropShadow) +IFontPtr gui::load_font(const string& file, int h, FontType type, + bool drop_shadow) { typedef tuple FontToken; static map cache; - FontToken t = make_tuple(file, h, dropShadow); + FontToken t = make_tuple(file, h, drop_shadow); map::iterator it = cache.find(t); if (it != cache.end()) return (*it).second; else { - IFontPtr p(new Font(file, h, type, dropShadow)); + IFontPtr p(new Font(file, h, type, drop_shadow)); cache[t] = p; return p; } diff --git a/src/gui/FromBottom.cpp b/src/gui/FromBottom.cpp index 20bf348..c73a27a 100644 --- a/src/gui/FromBottom.cpp +++ b/src/gui/FromBottom.cpp @@ -27,21 +27,21 @@ FromBottom::FromBottom(const AttributeSet& attrs) offset(attrs.get("offset")) { // It would be nice if this worked inside other widgets - int sh = getGameWindow()->height(); - int sw = getGameWindow()->width(); + int sh = get_game_window()->height(); + int sw = get_game_window()->width(); x(0); width(sw); height(offset); y(sh - offset); - dumpLocation(); + dump_location(); } void FromBottom::render(RenderContext& rc) const { - rc.pushOrigin(this); + rc.push_origin(this); ContainerWidget::render(rc); - rc.popOrigin(); + rc.pop_origin(); } diff --git a/src/gui/ImageButton.cpp b/src/gui/ImageButton.cpp index f1404e2..b8a623c 100644 --- a/src/gui/ImageButton.cpp +++ b/src/gui/ImageButton.cpp @@ -22,7 +22,7 @@ using namespace gui; ImageButton::ImageButton(const AttributeSet& attrs) : Widget(attrs) { - texture = loadTexture(attrs.get("image")); + texture = load_texture(attrs.get("image")); } void ImageButton::render(RenderContext& rc) const diff --git a/src/gui/Label.cpp b/src/gui/Label.cpp index 0f84b69..2e3b671 100644 --- a/src/gui/Label.cpp +++ b/src/gui/Label.cpp @@ -26,7 +26,7 @@ using namespace gui; Label::Label(const AttributeSet& attrs) : Widget(attrs), text_(attrs.get("text")), - fontName(attrs.get("font", "")), + font_name(attrs.get("font", "")), colour_(attrs.get("colour", colour::WHITE)), dirty(true) { @@ -43,12 +43,12 @@ void Label::text(const string& t) void Label::render(RenderContext& rc) const { - rc.print(rc.theme().font(fontName), x(), y(), text_, colour_); + rc.print(rc.theme().font(font_name), x(), y(), text_, colour_); } -void Label::adjustForTheme(const Theme& theme) +void Label::adjust_for_theme(const Theme& theme) { - IFontPtr font = theme.font(fontName); + IFontPtr font = theme.font(font_name); if (dirty) { width(font->text_width(text_)); diff --git a/src/gui/Layout.cpp b/src/gui/Layout.cpp index 62017ea..fc2fa07 100644 --- a/src/gui/Layout.cpp +++ b/src/gui/Layout.cpp @@ -50,8 +50,8 @@ public: bool click(int x, int y); // IXMLCallback interface - void startElement(const string& localName, const AttributeSet &attrs); - void endElement(const string& localName); + void start_element(const string& local_name, const AttributeSet &attrs); + void end_element(const string& local_name); private: // Manages paths during parsing @@ -97,51 +97,51 @@ Layout::~Layout() delete (*it).second; } -void Layout::startElement(const string& localName, +void Layout::start_element(const string& local_name, const AttributeSet &attrs) { Widget* w = NULL; - if (localName == "layout") { + if (local_name == "layout") { root = new RootWidget(attrs); parse_path.push(root); return; } - else if (localName == "font") { + else if (local_name == "font") { const string name = attrs.get("name"); const string file = attrs.get("file"); - const bool dropShadow = attrs.get("dropShadow", false); + const bool drop_shadow = attrs.get("drop_shadow", false); const int size = attrs.get("size", 14); - theme.addFont(name, - gui::loadFont(file, size, FONT_NORMAL, dropShadow)); + theme.add_font(name, + gui::load_font(file, size, FONT_NORMAL, drop_shadow)); return; } - else if (localName == "window") + else if (local_name == "window") w = new Window(attrs); - else if (localName == "button") + else if (local_name == "button") w = new Button(attrs); - else if (localName == "label") + else if (local_name == "label") w = new Label(attrs); - else if (localName == "throttleMeter") + else if (local_name == "throttle_meter") w = new ThrottleMeter(attrs); - else if (localName == "toggleBar") + else if (local_name == "toggle_bar") w = new ToggleBar(attrs); - else if (localName == "toggleButton") + else if (local_name == "toggle_button") w = new ToggleButton(attrs); - else if (localName == "canvas3d") + else if (local_name == "canvas3d") w = new Canvas3D(attrs); - else if (localName == "imageButton") + else if (local_name == "image_button") w = new ImageButton(attrs); - else if (localName == "fromBottom") + else if (local_name == "from_bottom") w = new FromBottom(attrs); else - throw runtime_error("Unexpected " + localName); + throw runtime_error("Unexpected " + local_name); Widget* parent = parse_path.top(); if (ContainerWidget* c = dynamic_cast(parent)) { - c->addChild(w); + c->add_child(w); } else { throw runtime_error("Widget " + parse_path.str() @@ -153,16 +153,16 @@ void Layout::startElement(const string& localName, widgets[parse_path.str()] = w; } -void Layout::endElement(const string& localName) +void Layout::end_element(const string& local_name) { - if (localName != "font") + if (local_name != "font") parse_path.pop(); } void Layout::render() const { assert(root); - root->adjustForTheme(theme); + root->adjust_for_theme(theme); RenderContext rc(theme); root->render(rc); @@ -185,7 +185,7 @@ bool Layout::exists(const string& path) const bool Layout::click(int x, int y) { - return root->handleClick(x, y); + return root->handle_click(x, y); } string Layout::PathStack::str() const @@ -211,13 +211,13 @@ Widget* Layout::PathStack::top() const return path_comps.back(); } -ILayoutPtr gui::makeLayout(const string& file_name) +ILayoutPtr gui::make_layout(const string& file_name) { return ILayoutPtr(new Layout(file_name)); } -string gui::parentPath(const string& path) +string gui::parent_path(const string& path) { - size_t lastSlash = path.find_last_of("/"); - return path.substr(lastSlash + 1); + size_t last_slash = path.find_last_of("/"); + return path.substr(last_slash + 1); } diff --git a/src/gui/RenderContext.cpp b/src/gui/RenderContext.cpp index eb0c320..0a71afb 100644 --- a/src/gui/RenderContext.cpp +++ b/src/gui/RenderContext.cpp @@ -27,7 +27,7 @@ using namespace gui; -IWindowPtr getGameWindow(); +IWindowPtr get_game_window(); RenderContext::RenderContext(const Theme& theme) : theme_(theme), origin_x(0), origin_y(0) @@ -42,18 +42,18 @@ RenderContext::~RenderContext() assert(origin_stack.empty()); - IWindowPtr wnd = getGameWindow(); + IWindowPtr wnd = get_game_window(); glScissor(0, 0, wnd->width(), wnd->height()); } -void RenderContext::pushOrigin(const Widget* w) +void RenderContext::push_origin(const Widget* w) { origin_x += w->x() + w->border(); origin_y += w->y() + w->border(); origin_stack.push(w); } -void RenderContext::popOrigin() +void RenderContext::pop_origin() { assert(!origin_stack.empty()); @@ -130,7 +130,7 @@ void RenderContext::print(IFontPtr font, int x, int y, void RenderContext::scissor(Widget* w) { - int wh = getGameWindow()->height(); + int wh = get_game_window()->height(); const Widget* parent = origin_stack.empty() ? NULL : origin_stack.top(); int max_w, max_h; @@ -154,11 +154,11 @@ void RenderContext::scissor(Widget* w) int height = min(w->height(), max_h); if (width <= 0 || height <= 0) { - static bool haveWarned = false; + static bool have_warned = false; - if (!haveWarned) { + if (!have_warned) { warn() << "Widget " << w->name() << " is out of bounds"; - haveWarned = true; + have_warned = true; } } else diff --git a/src/gui/Theme.cpp b/src/gui/Theme.cpp index 65e7213..b01345c 100644 --- a/src/gui/Theme.cpp +++ b/src/gui/Theme.cpp @@ -25,35 +25,35 @@ using namespace gui; Theme::Theme() { - normal_font_ = gui::loadFont("fonts/DejaVuSans.ttf", + normal_font_ = gui::load_font("fonts/DejaVuSans.ttf", 17, gui::FONT_NORMAL); } -void Theme::addFont(const string& name, IFontPtr f) +void Theme::add_font(const string& name, IFontPtr f) { fonts[name] = f; } Colour Theme::background() const { - return makeColour(0.0f, 0.0f, 0.3f, 0.5f); + return make_colour(0.0f, 0.0f, 0.3f, 0.5f); } Colour Theme::border() const { - return makeColour(0.0f, 0.0f, 1.0f, 1.0f); + return make_colour(0.0f, 0.0f, 1.0f, 1.0f); } -IFontPtr Theme::font(const string& fontName) const +IFontPtr Theme::font(const string& font_name) const { - if (fontName == "") - return normalFont(); + if (font_name == "") + return normal_font(); else { - FontMap::const_iterator it = fonts.find(fontName); + FontMap::const_iterator it = fonts.find(font_name); if (it != fonts.end()) return (*it).second; else - throw runtime_error("Unknown font: " + fontName); + throw runtime_error("Unknown font: " + font_name); } } diff --git a/src/gui/ThrottleMeter.cpp b/src/gui/ThrottleMeter.cpp index 4ec2db9..5362d3e 100644 --- a/src/gui/ThrottleMeter.cpp +++ b/src/gui/ThrottleMeter.cpp @@ -30,22 +30,22 @@ const int ThrottleMeter::METER_WIDTH(100); ThrottleMeter::ThrottleMeter(const AttributeSet& attrs) : Widget(attrs), value_(0), - minValue(THROTTLE_MIN), - maxValue(THROTTLE_MAX), - fontName(attrs.get("font", "")) + min_value(THROTTLE_MIN), + max_value(THROTTLE_MAX), + font_name(attrs.get("font", "")) { } void ThrottleMeter::range(int low, int high) { - minValue = low; - maxValue = high; + min_value = low; + max_value = high; } void ThrottleMeter::render(RenderContext& rc) const { - IFontPtr font = rc.theme().font(fontName); + IFontPtr font = rc.theme().font(font_name); int ox = x(), oy = y(); rc.offset(ox, oy); @@ -61,7 +61,7 @@ void ThrottleMeter::render(RenderContext& rc) const glTranslatef(ox + static_cast(font->text_width(LABEL)), static_cast(oy + off), 0.0f); - const int unit = METER_WIDTH / (maxValue + 1); + const int unit = METER_WIDTH / (max_value + 1); // Neutral bit glColor3f(1.0f, 1.0f, 0.0f); @@ -72,39 +72,39 @@ void ThrottleMeter::render(RenderContext& rc) const glVertex2i(unit, 0); glEnd(); - int squareLen = value_ >= maxValue - ? (maxValue - 1) * unit + int square_len = value_ >= max_value + ? (max_value - 1) * unit : (value_ > 0 ? unit * (value_ - 1) : 0); glTranslatef(static_cast(unit), 0.0f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); // Forwards bit - if (squareLen > 0) { + if (square_len > 0) { glBegin(GL_QUADS); glVertex2i(0, 0); glVertex2i(0, METER_HEIGHT); - glVertex2i(squareLen, METER_HEIGHT); - glVertex2i(squareLen, 0); + glVertex2i(square_len, METER_HEIGHT); + glVertex2i(square_len, 0); glEnd(); } - const bool wantTriangle = value_ < maxValue && value_ > 0; - if (wantTriangle) { + const bool want_triangle = value_ < max_value && value_ > 0; + if (want_triangle) { // Triangle bit glBegin(GL_TRIANGLES); - glVertex2i(squareLen, 0); - glVertex2i(squareLen, METER_HEIGHT); - glVertex2i(squareLen + unit, METER_HEIGHT / 2); + glVertex2i(square_len, 0); + glVertex2i(square_len, METER_HEIGHT); + glVertex2i(square_len + unit, METER_HEIGHT / 2); glEnd(); } glPopMatrix(); } -void ThrottleMeter::adjustForTheme(const Theme& theme) +void ThrottleMeter::adjust_for_theme(const Theme& theme) { - IFontPtr font = theme.font(fontName); + IFontPtr font = theme.font(font_name); width(font->text_width("Throttle: ") + METER_WIDTH); height(max(font->height(), METER_HEIGHT)); diff --git a/src/gui/ToggleBar.cpp b/src/gui/ToggleBar.cpp index ab84027..155e2d6 100644 --- a/src/gui/ToggleBar.cpp +++ b/src/gui/ToggleBar.cpp @@ -26,41 +26,41 @@ using namespace gui; ToggleBar::ToggleBar(const AttributeSet& attrs) : ContainerWidget(attrs), nextX(0), - buttonWidth(32), buttonHeight(32) + button_width(32), button_height(32) { width(1); - height(buttonHeight); + height(button_height); } void ToggleBar::render(RenderContext& rc) const { - rc.pushOrigin(this); + rc.push_origin(this); ContainerWidget::render(rc); - rc.popOrigin(); + rc.pop_origin(); } -void ToggleBar::childAdded(Widget* w) +void ToggleBar::child_added(Widget* w) { debug() << "Added " << w->name() << " to toggle bar"; w->x(nextX); w->y(0); - w->width(buttonWidth); - w->height(buttonHeight); + w->width(button_width); + w->height(button_height); - nextX += buttonWidth; + nextX += button_width; - width(width() + buttonWidth); + width(width() + button_width); - if (countChildren() == 1) + if (count_children() == 1) boost::polymorphic_cast(w)->on(); } -bool ToggleBar::handleClick(int x, int y) +bool ToggleBar::handle_click(int x, int y) { ChildList::iterator it; for (it = begin(); it != end(); ++it) boost::polymorphic_cast(*it)->off(); - return ContainerWidget::handleClick(x, y); + return ContainerWidget::handle_click(x, y); } diff --git a/src/gui/ToggleButton.cpp b/src/gui/ToggleButton.cpp index 90b55c8..f59bee7 100644 --- a/src/gui/ToggleButton.cpp +++ b/src/gui/ToggleButton.cpp @@ -24,7 +24,7 @@ ToggleButton::ToggleButton(const AttributeSet& attrs) : Widget(attrs), enabled(false) { - texture = loadTexture(attrs.get("image")); + texture = load_texture(attrs.get("image")); } void ToggleButton::render(RenderContext& rc) const @@ -35,10 +35,10 @@ void ToggleButton::render(RenderContext& rc) const rc.border(x(), y(), width(), height(), colour::WHITE); } -bool ToggleButton::handleClick(int x, int y) +bool ToggleButton::handle_click(int x, int y) { on(); - return Widget::handleClick(x, y); + return Widget::handle_click(x, y); } void ToggleButton::on() diff --git a/src/gui/Widget.cpp b/src/gui/Widget.cpp index 9ef78cf..be28fcc 100644 --- a/src/gui/Widget.cpp +++ b/src/gui/Widget.cpp @@ -23,10 +23,10 @@ using namespace gui; -int Widget::ourUniqueId(0); +int Widget::our_unique_id(0); Widget::Widget(const AttributeSet& attrs) - : name_(attrs.get("name", uniqueName())), + : name_(attrs.get("name", unique_name())), x_(attrs.get("x", -1)), y_(attrs.get("y", -1)), width_(attrs.get("width", 0)), @@ -36,8 +36,8 @@ Widget::Widget(const AttributeSet& attrs) { // If x or y weren't specified center the widget in the screen if (x_ == -1 || y_ == -1) { - const int screenW = getGameWindow()->width(); - const int screenH = getGameWindow()->height(); + const int screenW = get_game_window()->width(); + const int screenH = get_game_window()->height(); if (x_ == -1) x_ = (screenW - width_) / 2; @@ -47,9 +47,9 @@ Widget::Widget(const AttributeSet& attrs) } } -string Widget::uniqueName() +string Widget::unique_name() { - return "widget" + boost::lexical_cast(ourUniqueId++); + return "widget" + boost::lexical_cast(our_unique_id++); } void Widget::raise(Signal sig) @@ -64,13 +64,13 @@ void Widget::connect(Signal sig, SignalHandler handler) handlers[sig] = handler; } -bool Widget::handleClick(int x, int y) +bool Widget::handle_click(int x, int y) { raise(SIG_CLICK); return true; } -void Widget::dumpLocation() const +void Widget::dump_location() const { debug() << name() << ": x=" << x() << " y=" << y() << " width=" << width() diff --git a/src/gui/Window.cpp b/src/gui/Window.cpp index 32673c9..324c74d 100644 --- a/src/gui/Window.cpp +++ b/src/gui/Window.cpp @@ -24,12 +24,12 @@ Window::Window(const AttributeSet& attrs) : ContainerWidget(attrs), title_(attrs.get("title", "")) { - dynamicWidth = !attrs.has("width"); - dynamicHeight = !attrs.has("height"); + dynamic_width = !attrs.has("width"); + dynamic_height = !attrs.has("height"); - if (dynamicWidth) + if (dynamic_width) width(0); - if (dynamicHeight) + if (dynamic_height) height(0); } @@ -40,21 +40,21 @@ void Window::render(RenderContext& rc) const rc.border(x(), y(), width(), height(), rc.theme().border()); - rc.pushOrigin(this); + rc.push_origin(this); ContainerWidget::render(rc); - rc.popOrigin(); + rc.pop_origin(); } -void Window::adjustForTheme(const Theme& theme) +void Window::adjust_for_theme(const Theme& theme) { - ContainerWidget::adjustForTheme(theme); + ContainerWidget::adjust_for_theme(theme); - if (dynamicWidth) { + if (dynamic_width) { int maxW = 0; - for (ChildList::const_iterator it = constBegin(); - it != constEnd(); ++it) { + for (ChildList::const_iterator it = const_begin(); + it != const_end(); ++it) { int w = (*it)->width(); int x = (*it)->x(); @@ -65,10 +65,10 @@ void Window::adjustForTheme(const Theme& theme) width(maxW); } - if (dynamicHeight) { + if (dynamic_height) { int maxH = 0; - for (ChildList::const_iterator it = constBegin(); - it != constEnd(); ++it) { + for (ChildList::const_iterator it = const_begin(); + it != const_end(); ++it) { int h = (*it)->height(); int y = (*it)->y(); -- 2.39.2