
- •Credits
- •Foreword
- •About the Authors
- •About the Reviewers
- •www.PacktPub.com
- •Table of Contents
- •Preface
- •Introducing SFML
- •Downloading and installation
- •A minimal example
- •A few notes on C++
- •Developing the first game
- •The Game class
- •Game loops and frames
- •Input over several frames
- •Vector algebra
- •Frame-independent movement
- •Fixed time steps
- •Other techniques related to frame rates
- •Displaying sprites on the screen
- •File paths and working directories
- •Real-time rendering
- •Adapting the code
- •Summary
- •Defining resources
- •Resources in SFML
- •Textures
- •Images
- •Fonts
- •Shaders
- •Sound buffers
- •Music
- •A typical use case
- •Graphics
- •Audio
- •Acquiring, releasing, and accessing resources
- •An automated approach
- •Finding an appropriate container
- •Loading from files
- •Accessing the textures
- •Error handling
- •Boolean return values
- •Throwing exceptions
- •Assertions
- •Generalizing the approach
- •Compatibility with sf::Music
- •A special case – sf::Shader
- •Summary
- •Entities
- •Aircraft
- •Alternative entity designs
- •Rendering the scene
- •Relative coordinates
- •SFML and transforms
- •Scene graphs
- •Scene nodes
- •Node insertion and removal
- •Making scene nodes drawable
- •Drawing entities
- •Connecting entities with resources
- •Aligning the origin
- •Scene layers
- •Updating the scene
- •One step back – absolute transforms
- •The view
- •Viewport
- •View optimizations
- •Resolution and aspect ratio
- •View scrolling
- •Zoom and rotation
- •Landscape rendering
- •SpriteNode
- •Landscape texture
- •Texture repeating
- •Composing our world
- •World initialization
- •Loading the textures
- •Building the scene
- •Update and draw
- •Integrating the Game class
- •Summary
- •Polling events
- •Window events
- •Joystick events
- •Keyboard events
- •Mouse events
- •Getting the input state in real time
- •Events and real-time input – when to use which
- •Delta movement from the mouse
- •Playing nice with your application neighborhood
- •A command-based communication system
- •Introducing commands
- •Receiver categories
- •Command execution
- •Command queues
- •Handling player input
- •Commands in a nutshell
- •Implementing the game logic
- •A general-purpose communication mechanism
- •Customizing key bindings
- •Why a player is not an entity
- •Summary
- •Defining a state
- •The state stack
- •Adding states to StateStack
- •Handling updates, input, and drawing
- •Input
- •Update
- •Draw
- •Delayed pop/push operations
- •The state context
- •Integrating the stack in the Application class
- •Navigating between states
- •Creating the game state
- •The title screen
- •Main menu
- •Pausing the game
- •The loading screen – sample
- •Progress bar
- •ParallelTask
- •Thread
- •Concurrency
- •Task implementation
- •Summary
- •The GUI hierarchy, the Java way
- •Updating the menu
- •The promised key bindings
- •Summary
- •Equipping the entities
- •Introducing hitpoints
- •Storing entity attributes in data tables
- •Displaying text
- •Creating enemies
- •Movement patterns
- •Spawning enemies
- •Adding projectiles
- •Firing bullets and missiles
- •Homing missiles
- •Picking up some goodies
- •Collision detection and response
- •Finding the collision pairs
- •Reacting to collisions
- •An outlook on optimizations
- •An interacting world
- •Cleaning everything up
- •Out of view, out of the world
- •The final update
- •Victory and defeat
- •Summary
- •Defining texture atlases
- •Adapting the game code
- •Low-level rendering
- •OpenGL and graphics cards
- •Understanding render targets
- •Texture mapping
- •Vertex arrays
- •Particle systems
- •Particles and particle types
- •Particle nodes
- •Emitter nodes
- •Affectors
- •Embedding particles in the world
- •Animated sprites
- •The Eagle has rolled!
- •Post effects and shaders
- •Fullscreen post effects
- •Shaders
- •The bloom effect
- •Summary
- •Music themes
- •Loading and playing
- •Use case – In-game themes
- •Sound effects
- •Loading, inserting, and playing
- •Removing sounds
- •Use case – GUI sounds
- •Sounds in 3D space
- •The listener
- •Attenuation factor and minimum distance
- •Positioning the listener
- •Playing spatial sounds
- •Use case – In-game sound effects
- •Summary
- •Playing multiplayer games
- •Interacting with sockets
- •Socket selectors
- •Custom protocols
- •Data transport
- •Network architectures
- •Peer-to-peer
- •Client-server architecture
- •Authoritative servers
- •Creating the structure for multiplayer
- •Working with the Server
- •Server thread
- •Server loop
- •Peers and aircraft
- •Hot Seat
- •Accepting new clients
- •Handling disconnections
- •Incoming packets
- •Studying our protocol
- •Understanding the ticks and updates
- •Synchronization issues
- •Taking a peek in the other end – the client
- •Client packets
- •Transmitting game actions via network nodes
- •The new pause state
- •Settings
- •The new Player class
- •Latency
- •Latency versus bandwidth
- •View scrolling compensation
- •Aircraft interpolation
- •Cheating prevention
- •Summary
- •Index

Diverting the Game Flow – State Stack
A member function StateStack::registerState() inserts such mappings. The template parameter T is the derived state class we want to register. A lambda expression acts as a factory for the state: It creates an object of the derived class T by passing the stack and context to its constructor. This object is wrapped into a unique pointer and returned as a base class pointer. The lambda expression is assigned to the corresponding state ID in the map:
template <typename T>
void StateStack::registerState(States::ID stateID)
{
mFactories[stateID] = [this] ()
{
return State::Ptr(new T(*this, mContext));
};
}
This approach has the advantage that the StateStack class need not know the concrete state classes, we thus keep dependencies low. For state classes that take more than two parameters, we can write an overload to pass an additional argument (which will be done in later chapters). If your compiler supports variadic templates, a single function template will handle all these cases.
The createState() method takes an ID of a state, and returns a smart pointer to a newly created object of the corresponding state class. It does so by looking up the ID in the map and invoking the stored std::function factory, which returns the std::unique_ptr to the State base class:
State::Ptr StateStack::createState(States::ID stateID)
{
auto found = mFactories.find(stateID); assert(found != mFactories.end());
return found->second();
}
Handling updates, input, and drawing
Until this point, we taught the concept of the stack and the states it holds. Now it is time to feed our StateStack and consequently our active State objects with events, update, and drawing orders.
[ 118 ]
www.it-ebooks.info

Chapter 5
Input
Every polled event is fed to the state stack. Then, internally, the stack will deliver that event to the active states:
void StateStack::handleEvent(const sf::Event& event)
{
for (auto itr = mStack.rbegin(); itr != mStack.rend(); ++itr)
{
if (!(*itr)->handleEvent(event)) return;
}
applyPendingChanges();
}
In this for loop, you can verify that we iterate the active stack from the end to the beginning, in other words, from the highest state to the lowest. And, if any of the states returns false in its handleEvent() method, the loop is immediately ended.
This gives the control to the states that may not want to let input flow to other states than itself!
Update
The updating happens under the same guidelines of event handling, both the delivery order and the stopping of update propagation to lower states, if desired.
Draw
Drawing is straightforward; the StateStack class will order every active state to render itself.
The first state to be drawn is the lowest and oldest on the stack, and only then come the others, in order. This grants that the states are transparent, and you will be able to see the underlying screens. Anyway, if you don't desire to see pixels from the lower states, you can use sf::RectangleShape to draw a colored rectangle over the whole screen, blocking the undesired graphics, as you will see later in this chapter.
[ 119 ]
www.it-ebooks.info