Skip to content

Instantly share code, notes, and snippets.

@tonykero
Created April 14, 2018 14:48
Show Gist options
  • Save tonykero/2dae639ef4b563e40d2a5e562b278f00 to your computer and use it in GitHub Desktop.
Save tonykero/2dae639ef4b563e40d2a5e562b278f00 to your computer and use it in GitHub Desktop.
SFML Doc using moxygen

group audio

Sounds, streaming (musics or custom sources), recording, spatialization.

Summary

Members Descriptions
class sf::AlResource Base class for classes that require an OpenAL context.
class sf::InputSoundFile Provide read access to sound files.
class sf::Listener The audio listener is the point in the scene from where all the sounds are heard.
class sf::Music Streamed music played from an audio file.
class sf::OutputSoundFile Provide write access to sound files.
class sf::Sound Regular sound that can be played in the audio environment.
class sf::SoundBuffer Storage for audio samples defining a sound.
class sf::SoundBufferRecorder Specialized SoundRecorder which stores the captured audio data into a sound buffer.
class sf::SoundFileFactory Manages and instantiates sound file readers and writers.
class sf::SoundFileReader Abstract base class for sound file decoding.
class sf::SoundFileWriter Abstract base class for sound file encoding.
class sf::SoundRecorder Abstract base class for capturing sound data.
class sf::SoundSource Base class defining a sound's properties.
class sf::SoundStream Abstract base class for streamed audio sources.

class sf::AlResource

Base class for classes that require an OpenAL context.

This class is for internal use only, it must be the base of every class that requires a valid OpenAL context in order to work.

Summary

Members Descriptions
protected AlResource() Default constructor.
protected ~AlResource() Destructor.

Members

protected AlResource()

Default constructor.

protected ~AlResource()

Destructor.

class sf::InputSoundFile

class sf::InputSoundFile
  : private sf::NonCopyable

Provide read access to sound files.

This class decodes audio samples from a sound file.

It is used internally by higher-level classes such as sf::SoundBuffer and sf::Music, but can also be useful if you want to process or analyze audio files without playing them, or if you want to implement your own version of sf::Music with more specific features.

Usage example:

// Open a sound file
sf::InputSoundFile file;
if (!file.openFromFile("music.ogg"))
    /* error */;

// Print the sound attributes
std::cout << "duration: " << file.getDuration().asSeconds() << std::endl;
std::cout << "channels: " << file.getChannelCount() << std::endl;
std::cout << "sample rate: " << file.getSampleRate() << std::endl;
std::cout << "sample count: " << file.getSampleCount() << std::endl;

// Read and process batches of samples until the end of file is reached
sf::Int16 samples[1024];
sf::Uint64 count;
do
{
    count = file.read(samples, 1024);

    // process, analyze, play, convert, or whatever
    // you want to do with the samples...
}
while (count > 0);

See also: sf::SoundFileReader, sf::OutputSoundFile

Summary

Members Descriptions
public InputSoundFile() Default constructor.
public ~InputSoundFile() Destructor.
public bool openFromFile(const std::string & filename) Open a sound file from the disk for reading.
public bool openFromMemory(const void * data,std::size_t sizeInBytes) Open a sound file in memory for reading.
public bool openFromStream(InputStream & stream) Open a sound file from a custom stream for reading.
public Uint64 getSampleCount() const Get the total number of audio samples in the file.
public unsigned int getChannelCount() const Get the number of channels used by the sound.
public unsigned int getSampleRate() const Get the sample rate of the sound.
public Time getDuration() const Get the total duration of the sound file.
public Time getTimeOffset() const Get the read offset of the file in time.
public Uint64 getSampleOffset() const Get the read offset of the file in samples.
public void seek(Uint64 sampleOffset) Change the current read position to the given sample offset.
public void seek(Time timeOffset) Change the current read position to the given time offset.
public Uint64 read(Int16 * samples,Uint64 maxCount) Read audio samples from the open file.

Members

Default constructor.

Destructor.

public bool openFromFile(const std::string & filename)

Open a sound file from the disk for reading.

The supported audio formats are: WAV (PCM only), OGG/Vorbis, FLAC. The supported sample sizes for FLAC and WAV are 8, 16, 24 and 32 bit.

Parameters

  • filename Path of the sound file to load

Returns

True if the file was successfully opened

public bool openFromMemory(const void * data,std::size_t sizeInBytes)

Open a sound file in memory for reading.

The supported audio formats are: WAV (PCM only), OGG/Vorbis, FLAC. The supported sample sizes for FLAC and WAV are 8, 16, 24 and 32 bit.

Parameters

  • data Pointer to the file data in memory

  • sizeInBytes Size of the data to load, in bytes

Returns

True if the file was successfully opened

public bool openFromStream(InputStream & stream)

Open a sound file from a custom stream for reading.

The supported audio formats are: WAV (PCM only), OGG/Vorbis, FLAC. The supported sample sizes for FLAC and WAV are 8, 16, 24 and 32 bit.

Parameters

  • stream Source stream to read from

Returns

True if the file was successfully opened

public Uint64 getSampleCount() const

Get the total number of audio samples in the file.

Returns

Number of samples

public unsigned int getChannelCount() const

Get the number of channels used by the sound.

Returns

Number of channels (1 = mono, 2 = stereo)

public unsigned int getSampleRate() const

Get the sample rate of the sound.

Returns

Sample rate, in samples per second

public Time getDuration() const

Get the total duration of the sound file.

This function is provided for convenience, the duration is deduced from the other sound file attributes.

Returns

Duration of the sound file

public Time getTimeOffset() const

Get the read offset of the file in time.

Returns

Time position

public Uint64 getSampleOffset() const

Get the read offset of the file in samples.

Returns

Sample position

public void seek(Uint64 sampleOffset)

Change the current read position to the given sample offset.

This function takes a sample offset to provide maximum precision. If you need to jump to a given time, use the other overload.

The sample offset takes the channels into account. If you have a time offset instead, you can easily find the corresponding sample offset with the following formula: timeInSeconds * sampleRate * channelCount If the given offset exceeds to total number of samples, this function jumps to the end of the sound file.

Parameters

  • sampleOffset Index of the sample to jump to, relative to the beginning

public void seek(Time timeOffset)

Change the current read position to the given time offset.

Using a time offset is handy but imprecise. If you need an accurate result, consider using the overload which takes a sample offset.

If the given time exceeds to total duration, this function jumps to the end of the sound file.

Parameters

  • timeOffset Time to jump to, relative to the beginning

public Uint64 read(Int16 * samples,Uint64 maxCount)

Read audio samples from the open file.

Parameters

  • samples Pointer to the sample array to fill

  • maxCount Maximum number of samples to read

Returns

Number of samples actually read (may be less than maxCount)

class sf::Listener

The audio listener is the point in the scene from where all the sounds are heard.

The audio listener defines the global properties of the audio environment, it defines where and how sounds and musics are heard.

If sf::View is the eyes of the user, then sf::Listener is his ears (by the way, they are often linked together same position, orientation, etc.).

sf::Listener is a simple interface, which allows to setup the listener in the 3D audio environment (position, direction and up vector), and to adjust the global volume.

Because the listener is unique in the scene, sf::Listener only contains static functions and doesn't have to be instantiated.

Usage example:

// Move the listener to the position (1, 0, -5)
sf::Listener::setPosition(1, 0, -5);

// Make it face the right axis (1, 0, 0)
sf::Listener::setDirection(1, 0, 0);

// Reduce the global volume
sf::Listener::setGlobalVolume(50);

Summary

Members Descriptions

Members

class sf::Music

class sf::Music
  : public sf::SoundStream

Streamed music played from an audio file.

Musics are sounds that are streamed rather than completely loaded in memory.

This is especially useful for compressed musics that usually take hundreds of MB when they are uncompressed: by streaming it instead of loading it entirely, you avoid saturating the memory and have almost no loading delay. This implies that the underlying resource (file, stream or memory buffer) must remain valid for the lifetime of the sf::Music object.

Apart from that, a sf::Music has almost the same features as the sf::SoundBuffer / sf::Sound pair: you can play/pause/stop it, request its parameters (channels, sample rate), change the way it is played (pitch, volume, 3D position, ...), etc.

As a sound stream, a music is played in its own thread in order not to block the rest of the program. This means that you can leave the music alone after calling play(), it will manage itself very well.

Usage example:

// Declare a new music
sf::Music music;

// Open it from an audio file
if (!music.openFromFile("music.ogg"))
{
    // error...
}

// Change some parameters
music.setPosition(0, 1, 10); // change its 3D position
music.setPitch(2);           // increase the pitch
music.setVolume(50);         // reduce the volume
music.setLoop(true);         // make it loop

// Play it
music.play();

See also: sf::Sound, sf::SoundStream

Summary

Members Descriptions
public Music() Default constructor.
public ~Music() Destructor.
public bool openFromFile(const std::string & filename) Open a music from an audio file.
public bool openFromMemory(const void * data,std::size_t sizeInBytes) Open a music from an audio file in memory.
public bool openFromStream(InputStream & stream) Open a music from an audio file in a custom stream.
public Time getDuration() const Get the total duration of the music.
public TimeSpan getLoopPoints() const Get the positions of the of the sound's looping sequence.
public void setLoopPoints(TimeSpan timePoints) Sets the beginning and end of the sound's looping sequence using sf::Time.
public virtual void play() Start or resume playing the audio stream.
public virtual void pause() Pause the audio stream.
public virtual void stop() Stop playing the audio stream.
public unsigned int getChannelCount() const Return the number of channels of the stream.
public unsigned int getSampleRate() const Get the stream sample rate of the stream.
public virtual Status getStatus() const Get the current status of the stream (stopped, paused, playing)
public void setPlayingOffset(Time timeOffset) Change the current playing position of the stream.
public Time getPlayingOffset() const Get the current playing position of the stream.
public void setLoop(bool loop) Set whether or not the stream should loop after reaching the end.
public bool getLoop() const Tell whether or not the stream is in loop mode.
public void setPitch(float pitch) Set the pitch of the sound.
public void setVolume(float volume) Set the volume of the sound.
public void setPosition(float x,float y,float z) Set the 3D position of the sound in the audio scene.
public void setPosition(const Vector3f & position) Set the 3D position of the sound in the audio scene.
public void setRelativeToListener(bool relative) Make the sound's position relative to the listener or absolute.
public void setMinDistance(float distance) Set the minimum distance of the sound.
public void setAttenuation(float attenuation) Set the attenuation factor of the sound.
public float getPitch() const Get the pitch of the sound.
public float getVolume() const Get the volume of the sound.
public Vector3f getPosition() const Get the 3D position of the sound in the audio scene.
public bool isRelativeToListener() const Tell whether the sound's position is relative to the listener or is absolute.
public float getMinDistance() const Get the minimum distance of the sound.
public float getAttenuation() const Get the attenuation factor of the sound.
protected unsigned int m_source OpenAL source identifier.
protected virtual bool onGetData(Chunk & data) Request a new chunk of audio samples from the stream source.
protected virtual void onSeek(Time timeOffset) Change the current playing position in the stream source.
protected virtual Int64 onLoop() Change the current playing position in the stream source to the loop offset.
protected void initialize(unsigned int channelCount,unsigned int sampleRate) Define the audio stream parameters.
typedef TimeSpan
enum Status Enumeration of the sound source states.

Members

public Music()

Default constructor.

public ~Music()

Destructor.

public bool openFromFile(const std::string & filename)

Open a music from an audio file.

This function doesn't start playing the music (call play() to do so). See the documentation of sf::InputSoundFile for the list of supported formats.

Since the music is not loaded at once but rather streamed continuously, the file must remain accessible until the sf::Music object loads a new music or is destroyed.

Parameters

  • filename Path of the music file to open

Returns

True if loading succeeded, false if it failed

See also: openFromMemory, openFromStream

public bool openFromMemory(const void * data,std::size_t sizeInBytes)

Open a music from an audio file in memory.

This function doesn't start playing the music (call play() to do so). See the documentation of sf::InputSoundFile for the list of supported formats.

Since the music is not loaded at once but rather streamed continuously, the data buffer must remain accessible until the sf::Music object loads a new music or is destroyed. That is, you can't deallocate the buffer right after calling this function.

Parameters

  • data Pointer to the file data in memory

  • sizeInBytes Size of the data to load, in bytes

Returns

True if loading succeeded, false if it failed

See also: openFromFile, openFromStream

public bool openFromStream(InputStream & stream)

Open a music from an audio file in a custom stream.

This function doesn't start playing the music (call play() to do so). See the documentation of sf::InputSoundFile for the list of supported formats.

Since the music is not loaded at once but rather streamed continuously, the stream must remain accessible until the sf::Music object loads a new music or is destroyed.

Parameters

  • stream Source stream to read from

Returns

True if loading succeeded, false if it failed

See also: openFromFile, openFromMemory

public Time getDuration() const

Get the total duration of the music.

Returns

Music duration

public TimeSpan getLoopPoints() const

Get the positions of the of the sound's looping sequence.

Returns

Loop Time position class.

Since setLoopPoints() performs some adjustments on the provided values and rounds them to internal samples, a call to getLoopPoints() is not guaranteed to return the same times passed into a previous call to setLoopPoints(). However, it is guaranteed to return times that will map to the valid internal samples of this Music if they are later passed to setLoopPoints().

See also: setLoopPoints

public void setLoopPoints(TimeSpan timePoints)

Sets the beginning and end of the sound's looping sequence using sf::Time.

Loop points allow one to specify a pair of positions such that, when the music is enabled for looping, it will seamlessly seek to the beginning whenever it encounters the end. Valid ranges for timePoints.offset and timePoints.length are [0, Dur) and (0, Dur-offset] respectively, where Dur is the value returned by getDuration(). Note that the EOF "loop point" from the end to the beginning of the stream is still honored, in case the caller seeks to a point after the end of the loop range. This function can be safely called at any point after a stream is opened, and will be applied to a playing sound without affecting the current playing offset.

Setting the loop points while the stream's status is Paused will set its status to Stopped. The playing offset will be unaffected.

Parameters

  • timePoints The definition of the loop. Can be any time points within the sound's length

See also: getLoopPoints

public virtual void play()

Start or resume playing the audio stream.

This function starts the stream if it was stopped, resumes it if it was paused, and restarts it from the beginning if it was already playing. This function uses its own thread so that it doesn't block the rest of the program while the stream is played.

See also: pause, stop

public virtual void pause()

Pause the audio stream.

This function pauses the stream if it was playing, otherwise (stream already paused or stopped) it has no effect.

See also: play, stop

public virtual void stop()

Stop playing the audio stream.

This function stops the stream if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause()).

See also: play, pause

public unsigned int getChannelCount() const

Return the number of channels of the stream.

1 channel means a mono sound, 2 means stereo, etc.

Returns

Number of channels

public unsigned int getSampleRate() const

Get the stream sample rate of the stream.

The sample rate is the number of audio samples played per second. The higher, the better the quality.

Returns

Sample rate, in number of samples per second

public virtual Status getStatus() const

Get the current status of the stream (stopped, paused, playing)

Returns

Current status

public void setPlayingOffset(Time timeOffset)

Change the current playing position of the stream.

The playing position can be changed when the stream is either paused or playing. Changing the playing position when the stream is stopped has no effect, since playing the stream would reset its position.

Parameters

  • timeOffset New playing position, from the beginning of the stream

See also: getPlayingOffset

public Time getPlayingOffset() const

Get the current playing position of the stream.

Returns

Current playing position, from the beginning of the stream

See also: setPlayingOffset

public void setLoop(bool loop)

Set whether or not the stream should loop after reaching the end.

If set, the stream will restart from beginning after reaching the end and so on, until it is stopped or setLoop(false) is called. The default looping state for streams is false.

Parameters

  • loop True to play in loop, false to play once

See also: getLoop

public bool getLoop() const

Tell whether or not the stream is in loop mode.

Returns

True if the stream is looping, false otherwise

See also: setLoop

public void setPitch(float pitch)

Set the pitch of the sound.

The pitch represents the perceived fundamental frequency of a sound; thus you can make a sound more acute or grave by changing its pitch. A side effect of changing the pitch is to modify the playing speed of the sound as well. The default value for the pitch is 1.

Parameters

  • pitch New pitch to apply to the sound

See also: getPitch

public void setVolume(float volume)

Set the volume of the sound.

The volume is a value between 0 (mute) and 100 (full volume). The default value for the volume is 100.

Parameters

  • volume Volume of the sound

See also: getVolume

public void setPosition(float x,float y,float z)

Set the 3D position of the sound in the audio scene.

Only sounds with one channel (mono sounds) can be spatialized. The default position of a sound is (0, 0, 0).

Parameters

  • x X coordinate of the position of the sound in the scene

  • y Y coordinate of the position of the sound in the scene

  • z Z coordinate of the position of the sound in the scene

See also: getPosition

public void setPosition(const Vector3f & position)

Set the 3D position of the sound in the audio scene.

Only sounds with one channel (mono sounds) can be spatialized. The default position of a sound is (0, 0, 0).

Parameters

  • position Position of the sound in the scene

See also: getPosition

public void setRelativeToListener(bool relative)

Make the sound's position relative to the listener or absolute.

Making a sound relative to the listener will ensure that it will always be played the same way regardless of the position of the listener. This can be useful for non-spatialized sounds, sounds that are produced by the listener, or sounds attached to it. The default value is false (position is absolute).

Parameters

  • relative True to set the position relative, false to set it absolute

See also: isRelativeToListener

public void setMinDistance(float distance)

Set the minimum distance of the sound.

The "minimum distance" of a sound is the maximum distance at which it is heard at its maximum volume. Further than the minimum distance, it will start to fade out according to its attenuation factor. A value of 0 ("inside the head of the listener") is an invalid value and is forbidden. The default value of the minimum distance is 1.

Parameters

  • distance New minimum distance of the sound

See also: getMinDistance, setAttenuation

public void setAttenuation(float attenuation)

Set the attenuation factor of the sound.

The attenuation is a multiplicative factor which makes the sound more or less loud according to its distance from the listener. An attenuation of 0 will produce a non-attenuated sound, i.e. its volume will always be the same whether it is heard from near or from far. On the other hand, an attenuation value such as 100 will make the sound fade out very quickly as it gets further from the listener. The default value of the attenuation is 1.

Parameters

  • attenuation New attenuation factor of the sound

See also: getAttenuation, setMinDistance

public float getPitch() const

Get the pitch of the sound.

Returns

Pitch of the sound

See also: setPitch

public float getVolume() const

Get the volume of the sound.

Returns

Volume of the sound, in the range [0, 100]

See also: setVolume

public Vector3f getPosition() const

Get the 3D position of the sound in the audio scene.

Returns

Position of the sound

See also: setPosition

public bool isRelativeToListener() const

Tell whether the sound's position is relative to the listener or is absolute.

Returns

True if the position is relative, false if it's absolute

See also: setRelativeToListener

public float getMinDistance() const

Get the minimum distance of the sound.

Returns

Minimum distance of the sound

See also: setMinDistance, getAttenuation

public float getAttenuation() const

Get the attenuation factor of the sound.

Returns

Attenuation factor of the sound

See also: setAttenuation, getMinDistance

protected unsigned int m_source

OpenAL source identifier.

protected virtual bool onGetData(Chunk & data)

Request a new chunk of audio samples from the stream source.

This function fills the chunk from the next samples to read from the audio file.

Parameters

  • data Chunk of data to fill

Returns

True to continue playback, false to stop

protected virtual void onSeek(Time timeOffset)

Change the current playing position in the stream source.

Parameters

  • timeOffset New playing position, from the beginning of the music

protected virtual Int64 onLoop()

Change the current playing position in the stream source to the loop offset.

This is called by the underlying SoundStream whenever it needs us to reset the seek position for a loop. We then determine whether we are looping on a loop point or the end-of-file, perform the seek, and return the new position.

Returns

The seek position after looping (or -1 if there's no loop)

protected void initialize(unsigned int channelCount,unsigned int sampleRate)

Define the audio stream parameters.

This function must be called by derived classes as soon as they know the audio settings of the stream to play. Any attempt to manipulate the stream (play(), ...) before calling this function will fail. It can be called multiple times if the settings of the audio stream change, but only when the stream is stopped.

Parameters

  • channelCount Number of channels of the stream

  • sampleRate Sample rate, in samples per second

typedef TimeSpan

enum Status

Values Descriptions
Stopped Sound is not playing.
Paused Sound is paused.
Playing Sound is playing.

Enumeration of the sound source states.

class sf::OutputSoundFile

class sf::OutputSoundFile
  : private sf::NonCopyable

Provide write access to sound files.

This class encodes audio samples to a sound file.

It is used internally by higher-level classes such as sf::SoundBuffer, but can also be useful if you want to create audio files from custom data sources, like generated audio samples.

Usage example:

// Create a sound file, ogg/vorbis format, 44100 Hz, stereo
sf::OutputSoundFile file;
if (!file.openFromFile("music.ogg", 44100, 2))
    /* error */;

while (...)
{
    // Read or generate audio samples from your custom source
    std::vector<sf::Int16> samples = ...;

    // Write them to the file
    file.write(samples.data(), samples.size());
}

See also: sf::SoundFileWriter, sf::InputSoundFile

Summary

Members Descriptions
public OutputSoundFile() Default constructor.
public ~OutputSoundFile() Destructor.
public bool openFromFile(const std::string & filename,unsigned int sampleRate,unsigned int channelCount) Open the sound file from the disk for writing.
public void write(const Int16 * samples,Uint64 count) Write audio samples to the file.

Members

Default constructor.

Destructor.

Closes the file if it was still open.

public bool openFromFile(const std::string & filename,unsigned int sampleRate,unsigned int channelCount)

Open the sound file from the disk for writing.

The supported audio formats are: WAV, OGG/Vorbis, FLAC.

Parameters

  • filename Path of the sound file to write

  • sampleRate Sample rate of the sound

  • channelCount Number of channels in the sound

Returns

True if the file was successfully opened

public void write(const Int16 * samples,Uint64 count)

Write audio samples to the file.

Parameters

  • samples Pointer to the sample array to write

  • count Number of samples to write

class sf::Sound

class sf::Sound
  : public sf::SoundSource

Regular sound that can be played in the audio environment.

sf::Sound is the class to use to play sounds.

It provides:

  • Control (play, pause, stop)

  • Ability to modify output parameters in real-time (pitch, volume, ...)

  • 3D spatial features (position, attenuation, ...).

sf::Sound is perfect for playing short sounds that can fit in memory and require no latency, like foot steps or gun shots. For longer sounds, like background musics or long speeches, rather see sf::Music (which is based on streaming).

In order to work, a sound must be given a buffer of audio data to play. Audio data (samples) is stored in sf::SoundBuffer, and attached to a sound with the setBuffer() function. The buffer object attached to a sound must remain alive as long as the sound uses it. Note that multiple sounds can use the same sound buffer at the same time.

Usage example:

sf::SoundBuffer buffer;
buffer.loadFromFile("sound.wav");

sf::Sound sound;
sound.setBuffer(buffer);
sound.play();

See also: sf::SoundBuffer, sf::Music

Summary

Members Descriptions
public Sound() Default constructor.
public explicit Sound(const SoundBuffer & buffer) Construct the sound with a buffer.
public Sound(const Sound & copy) Copy constructor.
public ~Sound() Destructor.
public virtual void play() Start or resume playing the sound.
public virtual void pause() Pause the sound.
public virtual void stop() stop playing the sound
public void setBuffer(const SoundBuffer & buffer) Set the source buffer containing the audio data to play.
public void setLoop(bool loop) Set whether or not the sound should loop after reaching the end.
public void setPlayingOffset(Time timeOffset) Change the current playing position of the sound.
public const SoundBuffer*getBuffer() const Get the audio buffer attached to the sound.
public bool getLoop() const Tell whether or not the sound is in loop mode.
public Time getPlayingOffset() const Get the current playing position of the sound.
public virtual Status getStatus() const Get the current status of the sound (stopped, paused, playing)
public Sound&operator=(const Sound & right) Overload of assignment operator.
public void resetBuffer() Reset the internal buffer of the sound.
public void setPitch(float pitch) Set the pitch of the sound.
public void setVolume(float volume) Set the volume of the sound.
public void setPosition(float x,float y,float z) Set the 3D position of the sound in the audio scene.
public void setPosition(const Vector3f & position) Set the 3D position of the sound in the audio scene.
public void setRelativeToListener(bool relative) Make the sound's position relative to the listener or absolute.
public void setMinDistance(float distance) Set the minimum distance of the sound.
public void setAttenuation(float attenuation) Set the attenuation factor of the sound.
public float getPitch() const Get the pitch of the sound.
public float getVolume() const Get the volume of the sound.
public Vector3f getPosition() const Get the 3D position of the sound in the audio scene.
public bool isRelativeToListener() const Tell whether the sound's position is relative to the listener or is absolute.
public float getMinDistance() const Get the minimum distance of the sound.
public float getAttenuation() const Get the attenuation factor of the sound.
protected unsigned int m_source OpenAL source identifier.
enum Status Enumeration of the sound source states.

Members

public Sound()

Default constructor.

public explicit Sound(const SoundBuffer & buffer)

Construct the sound with a buffer.

Parameters

  • buffer Sound buffer containing the audio data to play with the sound

public Sound(const Sound & copy)

Copy constructor.

Parameters

  • copy Instance to copy

public ~Sound()

Destructor.

public virtual void play()

Start or resume playing the sound.

This function starts the stream if it was stopped, resumes it if it was paused, and restarts it from beginning if it was it already playing. This function uses its own thread so that it doesn't block the rest of the program while the sound is played.

See also: pause, stop

public virtual void pause()

Pause the sound.

This function pauses the sound if it was playing, otherwise (sound already paused or stopped) it has no effect.

See also: play, stop

public virtual void stop()

stop playing the sound

This function stops the sound if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause()).

See also: play, pause

public void setBuffer(const SoundBuffer & buffer)

Set the source buffer containing the audio data to play.

It is important to note that the sound buffer is not copied, thus the sf::SoundBuffer instance must remain alive as long as it is attached to the sound.

Parameters

  • buffer Sound buffer to attach to the sound

See also: getBuffer

public void setLoop(bool loop)

Set whether or not the sound should loop after reaching the end.

If set, the sound will restart from beginning after reaching the end and so on, until it is stopped or setLoop(false) is called. The default looping state for sound is false.

Parameters

  • loop True to play in loop, false to play once

See also: getLoop

public void setPlayingOffset(Time timeOffset)

Change the current playing position of the sound.

The playing position can be changed when the sound is either paused or playing. Changing the playing position when the sound is stopped has no effect, since playing the sound will reset its position.

Parameters

  • timeOffset New playing position, from the beginning of the sound

See also: getPlayingOffset

public const SoundBuffer*getBuffer() const

Get the audio buffer attached to the sound.

Returns

Sound buffer attached to the sound (can be NULL)

public bool getLoop() const

Tell whether or not the sound is in loop mode.

Returns

True if the sound is looping, false otherwise

See also: setLoop

public Time getPlayingOffset() const

Get the current playing position of the sound.

Returns

Current playing position, from the beginning of the sound

See also: setPlayingOffset

public virtual Status getStatus() const

Get the current status of the sound (stopped, paused, playing)

Returns

Current status of the sound

public Sound&operator=(const Sound & right)

Overload of assignment operator.

Parameters

  • right Instance to assign

Returns

Reference to self

public void resetBuffer()

Reset the internal buffer of the sound.

This function is for internal use only, you don't have to use it. It is called by the sf::SoundBuffer that this sound uses, when it is destroyed in order to prevent the sound from using a dead buffer.

public void setPitch(float pitch)

Set the pitch of the sound.

The pitch represents the perceived fundamental frequency of a sound; thus you can make a sound more acute or grave by changing its pitch. A side effect of changing the pitch is to modify the playing speed of the sound as well. The default value for the pitch is 1.

Parameters

  • pitch New pitch to apply to the sound

See also: getPitch

public void setVolume(float volume)

Set the volume of the sound.

The volume is a value between 0 (mute) and 100 (full volume). The default value for the volume is 100.

Parameters

  • volume Volume of the sound

See also: getVolume

public void setPosition(float x,float y,float z)

Set the 3D position of the sound in the audio scene.

Only sounds with one channel (mono sounds) can be spatialized. The default position of a sound is (0, 0, 0).

Parameters

  • x X coordinate of the position of the sound in the scene

  • y Y coordinate of the position of the sound in the scene

  • z Z coordinate of the position of the sound in the scene

See also: getPosition

public void setPosition(const Vector3f & position)

Set the 3D position of the sound in the audio scene.

Only sounds with one channel (mono sounds) can be spatialized. The default position of a sound is (0, 0, 0).

Parameters

  • position Position of the sound in the scene

See also: getPosition

public void setRelativeToListener(bool relative)

Make the sound's position relative to the listener or absolute.

Making a sound relative to the listener will ensure that it will always be played the same way regardless of the position of the listener. This can be useful for non-spatialized sounds, sounds that are produced by the listener, or sounds attached to it. The default value is false (position is absolute).

Parameters

  • relative True to set the position relative, false to set it absolute

See also: isRelativeToListener

public void setMinDistance(float distance)

Set the minimum distance of the sound.

The "minimum distance" of a sound is the maximum distance at which it is heard at its maximum volume. Further than the minimum distance, it will start to fade out according to its attenuation factor. A value of 0 ("inside the head of the listener") is an invalid value and is forbidden. The default value of the minimum distance is 1.

Parameters

  • distance New minimum distance of the sound

See also: getMinDistance, setAttenuation

public void setAttenuation(float attenuation)

Set the attenuation factor of the sound.

The attenuation is a multiplicative factor which makes the sound more or less loud according to its distance from the listener. An attenuation of 0 will produce a non-attenuated sound, i.e. its volume will always be the same whether it is heard from near or from far. On the other hand, an attenuation value such as 100 will make the sound fade out very quickly as it gets further from the listener. The default value of the attenuation is 1.

Parameters

  • attenuation New attenuation factor of the sound

See also: getAttenuation, setMinDistance

public float getPitch() const

Get the pitch of the sound.

Returns

Pitch of the sound

See also: setPitch

public float getVolume() const

Get the volume of the sound.

Returns

Volume of the sound, in the range [0, 100]

See also: setVolume

public Vector3f getPosition() const

Get the 3D position of the sound in the audio scene.

Returns

Position of the sound

See also: setPosition

public bool isRelativeToListener() const

Tell whether the sound's position is relative to the listener or is absolute.

Returns

True if the position is relative, false if it's absolute

See also: setRelativeToListener

public float getMinDistance() const

Get the minimum distance of the sound.

Returns

Minimum distance of the sound

See also: setMinDistance, getAttenuation

public float getAttenuation() const

Get the attenuation factor of the sound.

Returns

Attenuation factor of the sound

See also: setAttenuation, getMinDistance

protected unsigned int m_source

OpenAL source identifier.

enum Status

Values Descriptions
Stopped Sound is not playing.
Paused Sound is paused.
Playing Sound is playing.

Enumeration of the sound source states.

class sf::SoundBuffer

class sf::SoundBuffer
  : private sf::AlResource

Storage for audio samples defining a sound.

A sound buffer holds the data of a sound, which is an array of audio samples.

A sample is a 16 bits signed integer that defines the amplitude of the sound at a given time. The sound is then reconstituted by playing these samples at a high rate (for example, 44100 samples per second is the standard rate used for playing CDs). In short, audio samples are like texture pixels, and a sf::SoundBuffer is similar to a sf::Texture.

A sound buffer can be loaded from a file (see loadFromFile() for the complete list of supported formats), from memory, from a custom stream (see sf::InputStream) or directly from an array of samples. It can also be saved back to a file.

Sound buffers alone are not very useful: they hold the audio data but cannot be played. To do so, you need to use the sf::Sound class, which provides functions to play/pause/stop the sound as well as changing the way it is outputted (volume, pitch, 3D position, ...). This separation allows more flexibility and better performances: indeed a sf::SoundBuffer is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Sound is a lightweight object, which can use the audio data of a sound buffer and change the way it is played without actually modifying that data. Note that it is also possible to bind several sf::Sound instances to the same sf::SoundBuffer.

It is important to note that the sf::Sound instance doesn't copy the buffer that it uses, it only keeps a reference to it. Thus, a sf::SoundBuffer must not be destructed while it is used by a sf::Sound (i.e. never write a function that uses a local sf::SoundBuffer instance for loading a sound).

Usage example:

// Declare a new sound buffer
sf::SoundBuffer buffer;

// Load it from a file
if (!buffer.loadFromFile("sound.wav"))
{
    // error...
}

// Create a sound source and bind it to the buffer
sf::Sound sound1;
sound1.setBuffer(buffer);

// Play the sound
sound1.play();

// Create another sound source bound to the same buffer
sf::Sound sound2;
sound2.setBuffer(buffer);

// Play it with a higher pitch -- the first sound remains unchanged
sound2.setPitch(2);
sound2.play();

See also: sf::Sound, sf::SoundBufferRecorder

Summary

Members Descriptions
public SoundBuffer() Default constructor.
public SoundBuffer(const SoundBuffer & copy) Copy constructor.
public ~SoundBuffer() Destructor.
public bool loadFromFile(const std::string & filename) Load the sound buffer from a file.
public bool loadFromMemory(const void * data,std::size_t sizeInBytes) Load the sound buffer from a file in memory.
public bool loadFromStream(InputStream & stream) Load the sound buffer from a custom stream.
public bool loadFromSamples(const Int16 * samples,Uint64 sampleCount,unsigned int channelCount,unsigned int sampleRate) Load the sound buffer from an array of audio samples.
public bool saveToFile(const std::string & filename) const Save the sound buffer to an audio file.
public const Int16 * getSamples() const Get the array of audio samples stored in the buffer.
public Uint64 getSampleCount() const Get the number of samples stored in the buffer.
public unsigned int getSampleRate() const Get the sample rate of the sound.
public unsigned int getChannelCount() const Get the number of channels used by the sound.
public Time getDuration() const Get the total duration of the sound.
public SoundBuffer&operator=(const SoundBuffer & right) Overload of assignment operator.

Members

public SoundBuffer()

Default constructor.

public SoundBuffer(const SoundBuffer & copy)

Copy constructor.

Parameters

  • copy Instance to copy

public ~SoundBuffer()

Destructor.

public bool loadFromFile(const std::string & filename)

Load the sound buffer from a file.

See the documentation of sf::InputSoundFile for the list of supported formats.

Parameters

  • filename Path of the sound file to load

Returns

True if loading succeeded, false if it failed

See also: loadFromMemory, loadFromStream, loadFromSamples, saveToFile

public bool loadFromMemory(const void * data,std::size_t sizeInBytes)

Load the sound buffer from a file in memory.

See the documentation of sf::InputSoundFile for the list of supported formats.

Parameters

  • data Pointer to the file data in memory

  • sizeInBytes Size of the data to load, in bytes

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromStream, loadFromSamples

public bool loadFromStream(InputStream & stream)

Load the sound buffer from a custom stream.

See the documentation of sf::InputSoundFile for the list of supported formats.

Parameters

  • stream Source stream to read from

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromMemory, loadFromSamples

public bool loadFromSamples(const Int16 * samples,Uint64 sampleCount,unsigned int channelCount,unsigned int sampleRate)

Load the sound buffer from an array of audio samples.

The assumed format of the audio samples is 16 bits signed integer (sf::Int16).

Parameters

  • samples Pointer to the array of samples in memory

  • sampleCount Number of samples in the array

  • channelCount Number of channels (1 = mono, 2 = stereo, ...)

  • sampleRate Sample rate (number of samples to play per second)

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromMemory, saveToFile

public bool saveToFile(const std::string & filename) const

Save the sound buffer to an audio file.

See the documentation of sf::OutputSoundFile for the list of supported formats.

Parameters

  • filename Path of the sound file to write

Returns

True if saving succeeded, false if it failed

See also: loadFromFile, loadFromMemory, loadFromSamples

public const Int16 * getSamples() const

Get the array of audio samples stored in the buffer.

The format of the returned samples is 16 bits signed integer (sf::Int16). The total number of samples in this array is given by the getSampleCount() function.

Returns

Read-only pointer to the array of sound samples

See also: getSampleCount

public Uint64 getSampleCount() const

Get the number of samples stored in the buffer.

The array of samples can be accessed with the getSamples() function.

Returns

Number of samples

See also: getSamples

public unsigned int getSampleRate() const

Get the sample rate of the sound.

The sample rate is the number of samples played per second. The higher, the better the quality (for example, 44100 samples/s is CD quality).

Returns

Sample rate (number of samples per second)

See also: getChannelCount, getDuration

public unsigned int getChannelCount() const

Get the number of channels used by the sound.

If the sound is mono then the number of channels will be 1, 2 for stereo, etc.

Returns

Number of channels

See also: getSampleRate, getDuration

public Time getDuration() const

Get the total duration of the sound.

Returns

Sound duration

See also: getSampleRate, getChannelCount

public SoundBuffer&operator=(const SoundBuffer & right)

Overload of assignment operator.

Parameters

  • right Instance to assign

Returns

Reference to self

class sf::SoundBufferRecorder

class sf::SoundBufferRecorder
  : public sf::SoundRecorder

Specialized SoundRecorder which stores the captured audio data into a sound buffer.

sf::SoundBufferRecorder allows to access a recorded sound through a sf::SoundBuffer, so that it can be played, saved to a file, etc.

It has the same simple interface as its base class (start(), stop()) and adds a function to retrieve the recorded sound buffer (getBuffer()).

As usual, don't forget to call the isAvailable() function before using this class (see sf::SoundRecorder for more details about this).

Usage example:

if (sf::SoundBufferRecorder::isAvailable())
{
    // Record some audio data
    sf::SoundBufferRecorder recorder;
    recorder.start();
    ...
    recorder.stop();

    // Get the buffer containing the captured audio data
    const sf::SoundBuffer& buffer = recorder.getBuffer();

    // Save it to a file (for example...)
    buffer.saveToFile("my_record.ogg");
}

See also: sf::SoundRecorder

Summary

Members Descriptions
public ~SoundBufferRecorder() destructor
public const SoundBuffer&getBuffer() const Get the sound buffer containing the captured audio data.
public bool start(unsigned int sampleRate) Start the capture.
public void stop() Stop the capture.
public unsigned int getSampleRate() const Get the sample rate.
public bool setDevice(const std::string & name) Set the audio capture device.
public const std::string & getDevice() const Get the name of the current audio capture device.
public void setChannelCount(unsigned int channelCount) Set the channel count of the audio capture device.
public unsigned int getChannelCount() const Get the number of channels used by this recorder.
protected virtual bool onStart() Start capturing audio data.
protected virtual bool onProcessSamples(const Int16 * samples,std::size_t sampleCount) Process a new chunk of recorded samples.
protected virtual void onStop() Stop capturing audio data.
protected void setProcessingInterval(Time interval) Set the processing interval.

Members

destructor

public const SoundBuffer&getBuffer() const

Get the sound buffer containing the captured audio data.

The sound buffer is valid only after the capture has ended. This function provides a read-only access to the internal sound buffer, but it can be copied if you need to make any modification to it.

Returns

Read-only access to the sound buffer

public bool start(unsigned int sampleRate)

Start the capture.

The sampleRate parameter defines the number of audio samples captured per second. The higher, the better the quality (for example, 44100 samples/sec is CD quality). This function uses its own thread so that it doesn't block the rest of the program while the capture runs. Please note that only one capture can happen at the same time. You can select which capture device will be used, by passing the name to the setDevice() method. If none was selected before, the default capture device will be used. You can get a list of the names of all available capture devices by calling getAvailableDevices().

Parameters

  • sampleRate Desired capture rate, in number of samples per second

Returns

True, if start of capture was successful

See also: stop, getAvailableDevices

public void stop()

Stop the capture.

See also: start

public unsigned int getSampleRate() const

Get the sample rate.

The sample rate defines the number of audio samples captured per second. The higher, the better the quality (for example, 44100 samples/sec is CD quality).

Returns

Sample rate, in samples per second

public bool setDevice(const std::string & name)

Set the audio capture device.

This function sets the audio capture device to the device with the given name. It can be called on the fly (i.e: while recording). If you do so while recording and opening the device fails, it stops the recording.

Parameters

  • name The name of the audio capture device

Returns

True, if it was able to set the requested device

See also: getAvailableDevices, getDefaultDevice

public const std::string & getDevice() const

Get the name of the current audio capture device.

Returns

The name of the current audio capture device

public void setChannelCount(unsigned int channelCount)

Set the channel count of the audio capture device.

This method allows you to specify the number of channels used for recording. Currently only 16-bit mono and 16-bit stereo are supported.

Parameters

  • channelCount Number of channels. Currently only mono (1) and stereo (2) are supported.

See also: getChannelCount

public unsigned int getChannelCount() const

Get the number of channels used by this recorder.

Currently only mono and stereo are supported, so the value is either 1 (for mono) or 2 (for stereo).

Returns

Number of channels

See also: setChannelCount

protected virtual bool onStart()

Start capturing audio data.

Returns

True to start the capture, or false to abort it

protected virtual bool onProcessSamples(const Int16 * samples,std::size_t sampleCount)

Process a new chunk of recorded samples.

Parameters

  • samples Pointer to the new chunk of recorded samples

  • sampleCount Number of samples pointed by samples

Returns

True to continue the capture, or false to stop it

protected virtual void onStop()

Stop capturing audio data.

protected void setProcessingInterval(Time interval)

Set the processing interval.

The processing interval controls the period between calls to the onProcessSamples function. You may want to use a small interval if you want to process the recorded data in real time, for example.

Note: this is only a hint, the actual period may vary. So don't rely on this parameter to implement precise timing.

The default processing interval is 100 ms.

Parameters

  • interval Processing interval

class sf::SoundFileFactory

Manages and instantiates sound file readers and writers.

This class is where all the sound file readers and writers are registered.

You should normally only need to use its registration and unregistration functions; readers/writers creation and manipulation are wrapped into the higher-level classes sf::InputSoundFile and sf::OutputSoundFile.

To register a new reader (writer) use the sf::SoundFileFactory::registerReader (registerWriter) static function. You don't have to call the unregisterReader (unregisterWriter) function, unless you want to unregister a format before your application ends (typically, when a plugin is unloaded).

Usage example:

sf::SoundFileFactory::registerReader<MySoundFileReader>();
sf::SoundFileFactory::registerWriter<MySoundFileWriter>();

See also: sf::InputSoundFile, sf::OutputSoundFile, sf::SoundFileReader, sf::SoundFileWriter

Summary

Members Descriptions

Members

class sf::SoundFileReader

Abstract base class for sound file decoding.

This class allows users to read audio file formats not natively supported by SFML, and thus extend the set of supported readable audio formats.

A valid sound file reader must override the open, seek and write functions, as well as providing a static check function; the latter is used by SFML to find a suitable writer for a given input file.

To register a new reader, use the sf::SoundFileFactory::registerReader template function.

Usage example:

class MySoundFileReader : public sf::SoundFileReader
{
public:

    static bool check(sf::InputStream& stream)
    {
        // typically, read the first few header bytes and check fields that identify the format
        // return true if the reader can handle the format
    }

    virtual bool open(sf::InputStream& stream, Info& info)
    {
        // read the sound file header and fill the sound attributes
        // (channel count, sample count and sample rate)
        // return true on success
    }

    virtual void seek(sf::Uint64 sampleOffset)
    {
        // advance to the sampleOffset-th sample from the beginning of the sound
    }

    virtual sf::Uint64 read(sf::Int16* samples, sf::Uint64 maxCount)
    {
        // read up to 'maxCount' samples into the 'samples' array,
        // convert them (for example from normalized float) if they are not stored
        // as 16-bits signed integers in the file
        // return the actual number of samples read
    }
};

sf::SoundFileFactory::registerReader<MySoundFileReader>();

See also: sf::InputSoundFile, sf::SoundFileFactory, sf::SoundFileWriter

Summary

Members Descriptions
public inline virtual ~SoundFileReader() Virtual destructor.
public bool open(InputStream & stream,Info & info) Open a sound file for reading.
public void seek(Uint64 sampleOffset) Change the current read position to the given sample offset.
public Uint64 read(Int16 * samples,Uint64 maxCount) Read audio samples from the open file.

Members

public inline virtual ~SoundFileReader()

Virtual destructor.

public bool open(InputStream & stream,Info & info)

Open a sound file for reading.

The provided stream reference is valid as long as the SoundFileReader is alive, so it is safe to use/store it during the whole lifetime of the reader.

Parameters

  • stream Source stream to read from

  • info Structure to fill with the properties of the loaded sound

Returns

True if the file was successfully opened

public void seek(Uint64 sampleOffset)

Change the current read position to the given sample offset.

The sample offset takes the channels into account. If you have a time offset instead, you can easily find the corresponding sample offset with the following formula: timeInSeconds * sampleRate * channelCount If the given offset exceeds to total number of samples, this function must jump to the end of the file.

Parameters

  • sampleOffset Index of the sample to jump to, relative to the beginning

public Uint64 read(Int16 * samples,Uint64 maxCount)

Read audio samples from the open file.

Parameters

  • samples Pointer to the sample array to fill

  • maxCount Maximum number of samples to read

Returns

Number of samples actually read (may be less than maxCount)

class sf::SoundFileWriter

Abstract base class for sound file encoding.

This class allows users to write audio file formats not natively supported by SFML, and thus extend the set of supported writable audio formats.

A valid sound file writer must override the open and write functions, as well as providing a static check function; the latter is used by SFML to find a suitable writer for a given filename.

To register a new writer, use the sf::SoundFileFactory::registerWriter template function.

Usage example:

class MySoundFileWriter : public sf::SoundFileWriter
{
public:

    static bool check(const std::string& filename)
    {
        // typically, check the extension
        // return true if the writer can handle the format
    }

    virtual bool open(const std::string& filename, unsigned int sampleRate, unsigned int channelCount)
    {
        // open the file 'filename' for writing,
        // write the given sample rate and channel count to the file header
        // return true on success
    }

    virtual void write(const sf::Int16* samples, sf::Uint64 count)
    {
        // write 'count' samples stored at address 'samples',
        // convert them (for example to normalized float) if the format requires it
    }
};

sf::SoundFileFactory::registerWriter<MySoundFileWriter>();

See also: sf::OutputSoundFile, sf::SoundFileFactory, sf::SoundFileReader

Summary

Members Descriptions
public inline virtual ~SoundFileWriter() Virtual destructor.
public bool open(const std::string & filename,unsigned int sampleRate,unsigned int channelCount) Open a sound file for writing.
public void write(const Int16 * samples,Uint64 count) Write audio samples to the open file.

Members

public inline virtual ~SoundFileWriter()

Virtual destructor.

public bool open(const std::string & filename,unsigned int sampleRate,unsigned int channelCount)

Open a sound file for writing.

Parameters

  • filename Path of the file to open

  • sampleRate Sample rate of the sound

  • channelCount Number of channels of the sound

Returns

True if the file was successfully opened

public void write(const Int16 * samples,Uint64 count)

Write audio samples to the open file.

Parameters

  • samples Pointer to the sample array to write

  • count Number of samples to write

class sf::SoundRecorder

class sf::SoundRecorder
  : private sf::AlResource

Abstract base class for capturing sound data.

sf::SoundBuffer provides a simple interface to access the audio recording capabilities of the computer (the microphone).

As an abstract base class, it only cares about capturing sound samples, the task of making something useful with them is left to the derived class. Note that SFML provides a built-in specialization for saving the captured data to a sound buffer (see sf::SoundBufferRecorder).

A derived class has only one virtual function to override:

  • onProcessSamples provides the new chunks of audio samples while the capture happens

Moreover, two additional virtual functions can be overridden as well if necessary:

  • onStart is called before the capture happens, to perform custom initializations

  • onStop is called after the capture ends, to perform custom cleanup

A derived class can also control the frequency of the onProcessSamples calls, with the setProcessingInterval protected function. The default interval is chosen so that recording thread doesn't consume too much CPU, but it can be changed to a smaller value if you need to process the recorded data in real time, for example.

The audio capture feature may not be supported or activated on every platform, thus it is recommended to check its availability with the isAvailable() function. If it returns false, then any attempt to use an audio recorder will fail.

If you have multiple sound input devices connected to your computer (for example: microphone, external soundcard, webcam mic, ...) you can get a list of all available devices through the getAvailableDevices() function. You can then select a device by calling setDevice() with the appropriate device. Otherwise the default capturing device will be used.

By default the recording is in 16-bit mono. Using the setChannelCount method you can change the number of channels used by the audio capture device to record. Note that you have to decide whether you want to record in mono or stereo before starting the recording.

It is important to note that the audio capture happens in a separate thread, so that it doesn't block the rest of the program. In particular, the onProcessSamples virtual function (but not onStart and not onStop) will be called from this separate thread. It is important to keep this in mind, because you may have to take care of synchronization issues if you share data between threads. Another thing to bear in mind is that you must call stop() in the destructor of your derived class, so that the recording thread finishes before your object is destroyed.

Usage example:

class CustomRecorder : public sf::SoundRecorder
{
    ~CustomRecorder()
    {
        // Make sure to stop the recording thread
        stop();
    }

    virtual bool onStart() // optional
    {
        // Initialize whatever has to be done before the capture starts
        ...

        // Return true to start playing
        return true;
    }

    virtual bool onProcessSamples(const Int16* samples, std::size_t sampleCount)
    {
        // Do something with the new chunk of samples (store them, send them, ...)
        ...

        // Return true to continue playing
        return true;
    }

    virtual void onStop() // optional
    {
        // Clean up whatever has to be done after the capture ends
        ...
    }
}

// Usage
if (CustomRecorder::isAvailable())
{
    CustomRecorder recorder;

    if (!recorder.start())
        return -1;

    ...
    recorder.stop();
}

See also: sf::SoundBufferRecorder

Summary

Members Descriptions
public virtual ~SoundRecorder() destructor
public bool start(unsigned int sampleRate) Start the capture.
public void stop() Stop the capture.
public unsigned int getSampleRate() const Get the sample rate.
public bool setDevice(const std::string & name) Set the audio capture device.
public const std::string & getDevice() const Get the name of the current audio capture device.
public void setChannelCount(unsigned int channelCount) Set the channel count of the audio capture device.
public unsigned int getChannelCount() const Get the number of channels used by this recorder.
protected SoundRecorder() Default constructor.
protected void setProcessingInterval(Time interval) Set the processing interval.
protected virtual bool onStart() Start capturing audio data.
protected bool onProcessSamples(const Int16 * samples,std::size_t sampleCount) Process a new chunk of recorded samples.
protected virtual void onStop() Stop capturing audio data.

Members

public virtual ~SoundRecorder()

destructor

public bool start(unsigned int sampleRate)

Start the capture.

The sampleRate parameter defines the number of audio samples captured per second. The higher, the better the quality (for example, 44100 samples/sec is CD quality). This function uses its own thread so that it doesn't block the rest of the program while the capture runs. Please note that only one capture can happen at the same time. You can select which capture device will be used, by passing the name to the setDevice() method. If none was selected before, the default capture device will be used. You can get a list of the names of all available capture devices by calling getAvailableDevices().

Parameters

  • sampleRate Desired capture rate, in number of samples per second

Returns

True, if start of capture was successful

See also: stop, getAvailableDevices

public void stop()

Stop the capture.

See also: start

public unsigned int getSampleRate() const

Get the sample rate.

The sample rate defines the number of audio samples captured per second. The higher, the better the quality (for example, 44100 samples/sec is CD quality).

Returns

Sample rate, in samples per second

public bool setDevice(const std::string & name)

Set the audio capture device.

This function sets the audio capture device to the device with the given name. It can be called on the fly (i.e: while recording). If you do so while recording and opening the device fails, it stops the recording.

Parameters

  • name The name of the audio capture device

Returns

True, if it was able to set the requested device

See also: getAvailableDevices, getDefaultDevice

public const std::string & getDevice() const

Get the name of the current audio capture device.

Returns

The name of the current audio capture device

public void setChannelCount(unsigned int channelCount)

Set the channel count of the audio capture device.

This method allows you to specify the number of channels used for recording. Currently only 16-bit mono and 16-bit stereo are supported.

Parameters

  • channelCount Number of channels. Currently only mono (1) and stereo (2) are supported.

See also: getChannelCount

public unsigned int getChannelCount() const

Get the number of channels used by this recorder.

Currently only mono and stereo are supported, so the value is either 1 (for mono) or 2 (for stereo).

Returns

Number of channels

See also: setChannelCount

protected SoundRecorder()

Default constructor.

This constructor is only meant to be called by derived classes.

protected void setProcessingInterval(Time interval)

Set the processing interval.

The processing interval controls the period between calls to the onProcessSamples function. You may want to use a small interval if you want to process the recorded data in real time, for example.

Note: this is only a hint, the actual period may vary. So don't rely on this parameter to implement precise timing.

The default processing interval is 100 ms.

Parameters

  • interval Processing interval

protected virtual bool onStart()

Start capturing audio data.

This virtual function may be overridden by a derived class if something has to be done every time a new capture starts. If not, this function can be ignored; the default implementation does nothing.

Returns

True to start the capture, or false to abort it

protected bool onProcessSamples(const Int16 * samples,std::size_t sampleCount)

Process a new chunk of recorded samples.

This virtual function is called every time a new chunk of recorded data is available. The derived class can then do whatever it wants with it (storing it, playing it, sending it over the network, etc.).

Parameters

  • samples Pointer to the new chunk of recorded samples

  • sampleCount Number of samples pointed by samples

Returns

True to continue the capture, or false to stop it

protected virtual void onStop()

Stop capturing audio data.

This virtual function may be overridden by a derived class if something has to be done every time the capture ends. If not, this function can be ignored; the default implementation does nothing.

class sf::SoundSource

class sf::SoundSource
  : private sf::AlResource

Base class defining a sound's properties.

sf::SoundSource is not meant to be used directly, it only serves as a common base for all audio objects that can live in the audio environment.

It defines several properties for the sound: pitch, volume, position, attenuation, etc. All of them can be changed at any time with no impact on performances.

See also: sf::Sound, sf::SoundStream

Summary

Members Descriptions
public SoundSource(const SoundSource & copy) Copy constructor.
public virtual ~SoundSource() Destructor.
public void setPitch(float pitch) Set the pitch of the sound.
public void setVolume(float volume) Set the volume of the sound.
public void setPosition(float x,float y,float z) Set the 3D position of the sound in the audio scene.
public void setPosition(const Vector3f & position) Set the 3D position of the sound in the audio scene.
public void setRelativeToListener(bool relative) Make the sound's position relative to the listener or absolute.
public void setMinDistance(float distance) Set the minimum distance of the sound.
public void setAttenuation(float attenuation) Set the attenuation factor of the sound.
public float getPitch() const Get the pitch of the sound.
public float getVolume() const Get the volume of the sound.
public Vector3f getPosition() const Get the 3D position of the sound in the audio scene.
public bool isRelativeToListener() const Tell whether the sound's position is relative to the listener or is absolute.
public float getMinDistance() const Get the minimum distance of the sound.
public float getAttenuation() const Get the attenuation factor of the sound.
public SoundSource&operator=(const SoundSource & right) Overload of assignment operator.
public void play() Start or resume playing the sound source.
public void pause() Pause the sound source.
public void stop() Stop playing the sound source.
public virtual Status getStatus() const Get the current status of the sound (stopped, paused, playing)
protected unsigned int m_source OpenAL source identifier.
protected SoundSource() Default constructor.
enum Status Enumeration of the sound source states.

Members

public SoundSource(const SoundSource & copy)

Copy constructor.

Parameters

  • copy Instance to copy

public virtual ~SoundSource()

Destructor.

public void setPitch(float pitch)

Set the pitch of the sound.

The pitch represents the perceived fundamental frequency of a sound; thus you can make a sound more acute or grave by changing its pitch. A side effect of changing the pitch is to modify the playing speed of the sound as well. The default value for the pitch is 1.

Parameters

  • pitch New pitch to apply to the sound

See also: getPitch

public void setVolume(float volume)

Set the volume of the sound.

The volume is a value between 0 (mute) and 100 (full volume). The default value for the volume is 100.

Parameters

  • volume Volume of the sound

See also: getVolume

public void setPosition(float x,float y,float z)

Set the 3D position of the sound in the audio scene.

Only sounds with one channel (mono sounds) can be spatialized. The default position of a sound is (0, 0, 0).

Parameters

  • x X coordinate of the position of the sound in the scene

  • y Y coordinate of the position of the sound in the scene

  • z Z coordinate of the position of the sound in the scene

See also: getPosition

public void setPosition(const Vector3f & position)

Set the 3D position of the sound in the audio scene.

Only sounds with one channel (mono sounds) can be spatialized. The default position of a sound is (0, 0, 0).

Parameters

  • position Position of the sound in the scene

See also: getPosition

public void setRelativeToListener(bool relative)

Make the sound's position relative to the listener or absolute.

Making a sound relative to the listener will ensure that it will always be played the same way regardless of the position of the listener. This can be useful for non-spatialized sounds, sounds that are produced by the listener, or sounds attached to it. The default value is false (position is absolute).

Parameters

  • relative True to set the position relative, false to set it absolute

See also: isRelativeToListener

public void setMinDistance(float distance)

Set the minimum distance of the sound.

The "minimum distance" of a sound is the maximum distance at which it is heard at its maximum volume. Further than the minimum distance, it will start to fade out according to its attenuation factor. A value of 0 ("inside the head of the listener") is an invalid value and is forbidden. The default value of the minimum distance is 1.

Parameters

  • distance New minimum distance of the sound

See also: getMinDistance, setAttenuation

public void setAttenuation(float attenuation)

Set the attenuation factor of the sound.

The attenuation is a multiplicative factor which makes the sound more or less loud according to its distance from the listener. An attenuation of 0 will produce a non-attenuated sound, i.e. its volume will always be the same whether it is heard from near or from far. On the other hand, an attenuation value such as 100 will make the sound fade out very quickly as it gets further from the listener. The default value of the attenuation is 1.

Parameters

  • attenuation New attenuation factor of the sound

See also: getAttenuation, setMinDistance

public float getPitch() const

Get the pitch of the sound.

Returns

Pitch of the sound

See also: setPitch

public float getVolume() const

Get the volume of the sound.

Returns

Volume of the sound, in the range [0, 100]

See also: setVolume

public Vector3f getPosition() const

Get the 3D position of the sound in the audio scene.

Returns

Position of the sound

See also: setPosition

public bool isRelativeToListener() const

Tell whether the sound's position is relative to the listener or is absolute.

Returns

True if the position is relative, false if it's absolute

See also: setRelativeToListener

public float getMinDistance() const

Get the minimum distance of the sound.

Returns

Minimum distance of the sound

See also: setMinDistance, getAttenuation

public float getAttenuation() const

Get the attenuation factor of the sound.

Returns

Attenuation factor of the sound

See also: setAttenuation, getMinDistance

public SoundSource&operator=(const SoundSource & right)

Overload of assignment operator.

Parameters

  • right Instance to assign

Returns

Reference to self

public void play()

Start or resume playing the sound source.

This function starts the source if it was stopped, resumes it if it was paused, and restarts it from the beginning if it was already playing.

See also: pause, stop

public void pause()

Pause the sound source.

This function pauses the source if it was playing, otherwise (source already paused or stopped) it has no effect.

See also: play, stop

public void stop()

Stop playing the sound source.

This function stops the source if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause()).

See also: play, pause

public virtual Status getStatus() const

Get the current status of the sound (stopped, paused, playing)

Returns

Current status of the sound

protected unsigned int m_source

OpenAL source identifier.

protected SoundSource()

Default constructor.

This constructor is meant to be called by derived classes only.

enum Status

Values Descriptions
Stopped Sound is not playing.
Paused Sound is paused.
Playing Sound is playing.

Enumeration of the sound source states.

class sf::SoundStream

class sf::SoundStream
  : public sf::SoundSource

Abstract base class for streamed audio sources.

Unlike audio buffers (see sf::SoundBuffer), audio streams are never completely loaded in memory.

Instead, the audio data is acquired continuously while the stream is playing. This behavior allows to play a sound with no loading delay, and keeps the memory consumption very low.

Sound sources that need to be streamed are usually big files (compressed audio musics that would eat hundreds of MB in memory) or files that would take a lot of time to be received (sounds played over the network).

sf::SoundStream is a base class that doesn't care about the stream source, which is left to the derived class. SFML provides a built-in specialization for big files (see sf::Music). No network stream source is provided, but you can write your own by combining this class with the network module.

A derived class has to override two virtual functions:

  • onGetData fills a new chunk of audio data to be played

  • onSeek changes the current playing position in the source

It is important to note that each SoundStream is played in its own separate thread, so that the streaming loop doesn't block the rest of the program. In particular, the OnGetData and OnSeek virtual functions may sometimes be called from this separate thread. It is important to keep this in mind, because you may have to take care of synchronization issues if you share data between threads.

Usage example:

class CustomStream : public sf::SoundStream
{
public:

    bool open(const std::string& location)
    {
        // Open the source and get audio settings
        ...
        unsigned int channelCount = ...;
        unsigned int sampleRate = ...;

        // Initialize the stream -- important!
        initialize(channelCount, sampleRate);
    }

private:

    virtual bool onGetData(Chunk& data)
    {
        // Fill the chunk with audio data from the stream source
        // (note: must not be empty if you want to continue playing)
        data.samples = ...;
        data.sampleCount = ...;

        // Return true to continue playing
        return true;
    }

    virtual void onSeek(Uint32 timeOffset)
    {
        // Change the current position in the stream source
        ...
    }
}

// Usage
CustomStream stream;
stream.open("path/to/stream");
stream.play();

See also: sf::Music

Summary

Members Descriptions
public virtual ~SoundStream() Destructor.
public virtual void play() Start or resume playing the audio stream.
public virtual void pause() Pause the audio stream.
public virtual void stop() Stop playing the audio stream.
public unsigned int getChannelCount() const Return the number of channels of the stream.
public unsigned int getSampleRate() const Get the stream sample rate of the stream.
public virtual Status getStatus() const Get the current status of the stream (stopped, paused, playing)
public void setPlayingOffset(Time timeOffset) Change the current playing position of the stream.
public Time getPlayingOffset() const Get the current playing position of the stream.
public void setLoop(bool loop) Set whether or not the stream should loop after reaching the end.
public bool getLoop() const Tell whether or not the stream is in loop mode.
public void setPitch(float pitch) Set the pitch of the sound.
public void setVolume(float volume) Set the volume of the sound.
public void setPosition(float x,float y,float z) Set the 3D position of the sound in the audio scene.
public void setPosition(const Vector3f & position) Set the 3D position of the sound in the audio scene.
public void setRelativeToListener(bool relative) Make the sound's position relative to the listener or absolute.
public void setMinDistance(float distance) Set the minimum distance of the sound.
public void setAttenuation(float attenuation) Set the attenuation factor of the sound.
public float getPitch() const Get the pitch of the sound.
public float getVolume() const Get the volume of the sound.
public Vector3f getPosition() const Get the 3D position of the sound in the audio scene.
public bool isRelativeToListener() const Tell whether the sound's position is relative to the listener or is absolute.
public float getMinDistance() const Get the minimum distance of the sound.
public float getAttenuation() const Get the attenuation factor of the sound.
protected unsigned int m_source OpenAL source identifier.
protected SoundStream() Default constructor.
protected void initialize(unsigned int channelCount,unsigned int sampleRate) Define the audio stream parameters.
protected bool onGetData(Chunk & data) Request a new chunk of audio samples from the stream source.
protected void onSeek(Time timeOffset) Change the current playing position in the stream source.
protected virtual Int64 onLoop() Change the current playing position in the stream source to the beginning of the loop.
enum Status Enumeration of the sound source states.

Members

public virtual ~SoundStream()

Destructor.

public virtual void play()

Start or resume playing the audio stream.

This function starts the stream if it was stopped, resumes it if it was paused, and restarts it from the beginning if it was already playing. This function uses its own thread so that it doesn't block the rest of the program while the stream is played.

See also: pause, stop

public virtual void pause()

Pause the audio stream.

This function pauses the stream if it was playing, otherwise (stream already paused or stopped) it has no effect.

See also: play, stop

public virtual void stop()

Stop playing the audio stream.

This function stops the stream if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause()).

See also: play, pause

public unsigned int getChannelCount() const

Return the number of channels of the stream.

1 channel means a mono sound, 2 means stereo, etc.

Returns

Number of channels

public unsigned int getSampleRate() const

Get the stream sample rate of the stream.

The sample rate is the number of audio samples played per second. The higher, the better the quality.

Returns

Sample rate, in number of samples per second

public virtual Status getStatus() const

Get the current status of the stream (stopped, paused, playing)

Returns

Current status

public void setPlayingOffset(Time timeOffset)

Change the current playing position of the stream.

The playing position can be changed when the stream is either paused or playing. Changing the playing position when the stream is stopped has no effect, since playing the stream would reset its position.

Parameters

  • timeOffset New playing position, from the beginning of the stream

See also: getPlayingOffset

public Time getPlayingOffset() const

Get the current playing position of the stream.

Returns

Current playing position, from the beginning of the stream

See also: setPlayingOffset

public void setLoop(bool loop)

Set whether or not the stream should loop after reaching the end.

If set, the stream will restart from beginning after reaching the end and so on, until it is stopped or setLoop(false) is called. The default looping state for streams is false.

Parameters

  • loop True to play in loop, false to play once

See also: getLoop

public bool getLoop() const

Tell whether or not the stream is in loop mode.

Returns

True if the stream is looping, false otherwise

See also: setLoop

public void setPitch(float pitch)

Set the pitch of the sound.

The pitch represents the perceived fundamental frequency of a sound; thus you can make a sound more acute or grave by changing its pitch. A side effect of changing the pitch is to modify the playing speed of the sound as well. The default value for the pitch is 1.

Parameters

  • pitch New pitch to apply to the sound

See also: getPitch

public void setVolume(float volume)

Set the volume of the sound.

The volume is a value between 0 (mute) and 100 (full volume). The default value for the volume is 100.

Parameters

  • volume Volume of the sound

See also: getVolume

public void setPosition(float x,float y,float z)

Set the 3D position of the sound in the audio scene.

Only sounds with one channel (mono sounds) can be spatialized. The default position of a sound is (0, 0, 0).

Parameters

  • x X coordinate of the position of the sound in the scene

  • y Y coordinate of the position of the sound in the scene

  • z Z coordinate of the position of the sound in the scene

See also: getPosition

public void setPosition(const Vector3f & position)

Set the 3D position of the sound in the audio scene.

Only sounds with one channel (mono sounds) can be spatialized. The default position of a sound is (0, 0, 0).

Parameters

  • position Position of the sound in the scene

See also: getPosition

public void setRelativeToListener(bool relative)

Make the sound's position relative to the listener or absolute.

Making a sound relative to the listener will ensure that it will always be played the same way regardless of the position of the listener. This can be useful for non-spatialized sounds, sounds that are produced by the listener, or sounds attached to it. The default value is false (position is absolute).

Parameters

  • relative True to set the position relative, false to set it absolute

See also: isRelativeToListener

public void setMinDistance(float distance)

Set the minimum distance of the sound.

The "minimum distance" of a sound is the maximum distance at which it is heard at its maximum volume. Further than the minimum distance, it will start to fade out according to its attenuation factor. A value of 0 ("inside the head of the listener") is an invalid value and is forbidden. The default value of the minimum distance is 1.

Parameters

  • distance New minimum distance of the sound

See also: getMinDistance, setAttenuation

public void setAttenuation(float attenuation)

Set the attenuation factor of the sound.

The attenuation is a multiplicative factor which makes the sound more or less loud according to its distance from the listener. An attenuation of 0 will produce a non-attenuated sound, i.e. its volume will always be the same whether it is heard from near or from far. On the other hand, an attenuation value such as 100 will make the sound fade out very quickly as it gets further from the listener. The default value of the attenuation is 1.

Parameters

  • attenuation New attenuation factor of the sound

See also: getAttenuation, setMinDistance

public float getPitch() const

Get the pitch of the sound.

Returns

Pitch of the sound

See also: setPitch

public float getVolume() const

Get the volume of the sound.

Returns

Volume of the sound, in the range [0, 100]

See also: setVolume

public Vector3f getPosition() const

Get the 3D position of the sound in the audio scene.

Returns

Position of the sound

See also: setPosition

public bool isRelativeToListener() const

Tell whether the sound's position is relative to the listener or is absolute.

Returns

True if the position is relative, false if it's absolute

See also: setRelativeToListener

public float getMinDistance() const

Get the minimum distance of the sound.

Returns

Minimum distance of the sound

See also: setMinDistance, getAttenuation

public float getAttenuation() const

Get the attenuation factor of the sound.

Returns

Attenuation factor of the sound

See also: setAttenuation, getMinDistance

protected unsigned int m_source

OpenAL source identifier.

protected SoundStream()

Default constructor.

This constructor is only meant to be called by derived classes.

protected void initialize(unsigned int channelCount,unsigned int sampleRate)

Define the audio stream parameters.

This function must be called by derived classes as soon as they know the audio settings of the stream to play. Any attempt to manipulate the stream (play(), ...) before calling this function will fail. It can be called multiple times if the settings of the audio stream change, but only when the stream is stopped.

Parameters

  • channelCount Number of channels of the stream

  • sampleRate Sample rate, in samples per second

protected bool onGetData(Chunk & data)

Request a new chunk of audio samples from the stream source.

This function must be overridden by derived classes to provide the audio samples to play. It is called continuously by the streaming loop, in a separate thread. The source can choose to stop the streaming loop at any time, by returning false to the caller. If you return true (i.e. continue streaming) it is important that the returned array of samples is not empty; this would stop the stream due to an internal limitation.

Parameters

  • data Chunk of data to fill

Returns

True to continue playback, false to stop

protected void onSeek(Time timeOffset)

Change the current playing position in the stream source.

This function must be overridden by derived classes to allow random seeking into the stream source.

Parameters

  • timeOffset New playing position, relative to the beginning of the stream

protected virtual Int64 onLoop()

Change the current playing position in the stream source to the beginning of the loop.

This function can be overridden by derived classes to allow implementation of custom loop points. Otherwise, it just calls onSeek(Time::Zero) and returns 0.

Returns

The seek position after looping (or -1 if there's no loop)

enum Status

Values Descriptions
Stopped Sound is not playing.
Paused Sound is paused.
Playing Sound is playing.

Enumeration of the sound source states.

group graphics

2D graphics module: sprites, text, shapes, ...

Summary

Members Descriptions
enum PrimitiveType Types of primitives that a sf::VertexArray can render.
class sf::BlendMode Blending modes for drawing.
class sf::CircleShape Specialized shape representing a circle.
class sf::Color Utility class for manipulating RGBA colors.
class sf::ConvexShape Specialized shape representing a convex polygon.
class sf::Drawable Abstract base class for objects that can be drawn to a render target.
class sf::Font Class for loading and manipulating character fonts.
class sf::Glyph Structure describing a glyph.
class sf::Image Class for loading, manipulating and saving images.
class sf::Rect Utility class for manipulating 2D axis aligned rectangles.
class sf::RectangleShape Specialized shape representing a rectangle.
class sf::RenderStates Define the states used for drawing to a RenderTarget.
class sf::RenderTarget Base class for all render targets (window, texture, ...)
class sf::RenderTexture Target for off-screen 2D rendering into a texture.
class sf::RenderWindow Window that can serve as a target for 2D drawing.
class sf::Shader Shader class (vertex, geometry and fragment)
class sf::Shape Base class for textured shapes with outline.
class sf::Sprite Drawable representation of a texture, with its own transformations, color, etc.
class sf::Text Graphical text that can be drawn to a render target.
class sf::Texture Image living on the graphics card that can be used for drawing.
class sf::Transform Define a 3x3 transform matrix.
class sf::Transformable Decomposed transform defined by a position, a rotation and a scale.
class sf::Vertex Define a point with color and texture coordinates.
class sf::VertexArray Define a set of one or more 2D primitives.
class sf::VertexBuffer Vertex buffer storage for one or more 2D primitives.
class sf::View 2D camera that defines what region is shown on screen

Members

Values Descriptions
Points List of individual points.
Lines List of individual lines.
LineStrip List of connected lines, a point uses the previous point to form a line.
Triangles List of individual triangles.
TriangleStrip List of connected triangles, a point uses the two previous points to form a triangle.
TriangleFan List of connected triangles, a point uses the common center and the previous point to form a triangle.
Quads List of individual quads (deprecated, don't work with OpenGL ES)
LinesStrip > Deprecated: Use LineStrip instead
TrianglesStrip > Deprecated: Use TriangleStrip instead
TrianglesFan > Deprecated: Use TriangleFan instead

Types of primitives that a sf::VertexArray can render.

Points and lines have no area, therefore their thickness will always be 1 pixel, regardless the current transform and view.

class sf::BlendMode

Blending modes for drawing.

sf::BlendMode is a class that represents a blend mode.

A blend mode determines how the colors of an object you draw are mixed with the colors that are already in the buffer.

The class is composed of 6 components, each of which has its own public member variable:

The source factor specifies how the pixel you are drawing contributes to the final color. The destination factor specifies how the pixel already drawn in the buffer contributes to the final color.

The color channels RGB (red, green, blue; simply referred to as color) and A (alpha; the transparency) can be treated separately. This separation can be useful for specific blend modes, but most often you won't need it and will simply treat the color as a single unit.

The blend factors and equations correspond to their OpenGL equivalents. In general, the color of the resulting pixel is calculated according to the following formula (src is the color of the source pixel, dst the color of the destination pixel, the other variables correspond to the public members, with the equations being + or - operators):

dst.rgb = colorSrcFactor * src.rgb (colorEquation) colorDstFactor * dst.rgb
dst.a   = alphaSrcFactor * src.a   (alphaEquation) alphaDstFactor * dst.a

All factors and colors are represented as floating point numbers between 0 and 1. Where necessary, the result is clamped to fit in that range.

The most common blending modes are defined as constants in the sf namespace:

sf::BlendMode alphaBlending          = sf::BlendAlpha;
sf::BlendMode additiveBlending       = sf::BlendAdd;
sf::BlendMode multiplicativeBlending = sf::BlendMultiply;
sf::BlendMode noBlending             = sf::BlendNone;

In SFML, a blend mode can be specified every time you draw a sf::Drawable object to a render target. It is part of the sf::RenderStates compound that is passed to the member function sf::RenderTarget::draw().

See also: sf::RenderStates, sf::RenderTarget

Summary

Members Descriptions
public Factor colorSrcFactor Source blending factor for the color channels.
public Factor colorDstFactor Destination blending factor for the color channels.
public Equation colorEquation Blending equation for the color channels.
public Factor alphaSrcFactor Source blending factor for the alpha channel.
public Factor alphaDstFactor Destination blending factor for the alpha channel.
public Equation alphaEquation Blending equation for the alpha channel.
public BlendMode() Default constructor.
public BlendMode(Factor sourceFactor,Factor destinationFactor,Equation blendEquation) Construct the blend mode given the factors and equation.
public BlendMode(Factor colorSourceFactor,Factor colorDestinationFactor,Equation colorBlendEquation,Factor alphaSourceFactor,Factor alphaDestinationFactor,Equation alphaBlendEquation) Construct the blend mode given the factors and equation.
enum Factor Enumeration of the blending factors.
enum Equation Enumeration of the blending equations.

Members

Source blending factor for the color channels.

Destination blending factor for the color channels.

Blending equation for the color channels.

Source blending factor for the alpha channel.

Destination blending factor for the alpha channel.

Blending equation for the alpha channel.

public BlendMode()

Default constructor.

Constructs a blending mode that does alpha blending.

public BlendMode(Factor sourceFactor,Factor destinationFactor,Equation blendEquation)

Construct the blend mode given the factors and equation.

This constructor uses the same factors and equation for both color and alpha components. It also defaults to the Add equation.

Parameters

  • sourceFactor Specifies how to compute the source factor for the color and alpha channels.

  • destinationFactor Specifies how to compute the destination factor for the color and alpha channels.

  • blendEquation Specifies how to combine the source and destination colors and alpha.

public BlendMode(Factor colorSourceFactor,Factor colorDestinationFactor,Equation colorBlendEquation,Factor alphaSourceFactor,Factor alphaDestinationFactor,Equation alphaBlendEquation)

Construct the blend mode given the factors and equation.

Parameters

  • colorSourceFactor Specifies how to compute the source factor for the color channels.

  • colorDestinationFactor Specifies how to compute the destination factor for the color channels.

  • colorBlendEquation Specifies how to combine the source and destination colors.

  • alphaSourceFactor Specifies how to compute the source factor.

  • alphaDestinationFactor Specifies how to compute the destination factor.

  • alphaBlendEquation Specifies how to combine the source and destination alphas.

enum Factor

Values Descriptions
Zero (0, 0, 0, 0)
One (1, 1, 1, 1)
SrcColor (src.r, src.g, src.b, src.a)
OneMinusSrcColor (1, 1, 1, 1) - (src.r, src.g, src.b, src.a)
DstColor (dst.r, dst.g, dst.b, dst.a)
OneMinusDstColor (1, 1, 1, 1) - (dst.r, dst.g, dst.b, dst.a)
SrcAlpha (src.a, src.a, src.a, src.a)
OneMinusSrcAlpha (1, 1, 1, 1) - (src.a, src.a, src.a, src.a)
DstAlpha (dst.a, dst.a, dst.a, dst.a)
OneMinusDstAlpha (1, 1, 1, 1) - (dst.a, dst.a, dst.a, dst.a)

Enumeration of the blending factors.

The factors are mapped directly to their OpenGL equivalents, specified by glBlendFunc() or glBlendFuncSeparate().

Values Descriptions
Add Pixel = Src * SrcFactor + Dst * DstFactor.
Subtract Pixel = Src * SrcFactor - Dst * DstFactor.
ReverseSubtract Pixel = Dst * DstFactor - Src * SrcFactor.

Enumeration of the blending equations.

The equations are mapped directly to their OpenGL equivalents, specified by glBlendEquation() or glBlendEquationSeparate().

class sf::CircleShape

class sf::CircleShape
  : public sf::Shape

Specialized shape representing a circle.

This class inherits all the functions of sf::Transformable (position, rotation, scale, bounds, ...) as well as the functions of sf::Shape (outline, color, texture, ...).

Usage example:

sf::CircleShape circle;
circle.setRadius(150);
circle.setOutlineColor(sf::Color::Red);
circle.setOutlineThickness(5);
circle.setPosition(10, 20);
...
window.draw(circle);

Since the graphics card can't draw perfect circles, we have to fake them with multiple triangles connected to each other. The "points count" property of sf::CircleShape defines how many of these triangles to use, and therefore defines the quality of the circle.

The number of points can also be used for another purpose; with small numbers you can create any regular polygon shape: equilateral triangle, square, pentagon, hexagon, ...

See also: sf::Shape, sf::RectangleShape, sf::ConvexShape

Summary

Members Descriptions
public explicit CircleShape(float radius,std::size_t pointCount) Default constructor.
public void setRadius(float radius) Set the radius of the circle.
public float getRadius() const Get the radius of the circle.
public void setPointCount(std::size_t count) Set the number of points of the circle.
public virtual std::size_t getPointCount() const Get the number of points of the circle.
public virtual Vector2f getPoint(std::size_t index) const Get a point of the circle.
public void setTexture(const Texture * texture,bool resetRect) Change the source texture of the shape.
public void setTextureRect(const IntRect & rect) Set the sub-rectangle of the texture that the shape will display.
public void setFillColor(const Color & color) Set the fill color of the shape.
public void setOutlineColor(const Color & color) Set the outline color of the shape.
public void setOutlineThickness(float thickness) Set the thickness of the shape's outline.
public const Texture*getTexture() const Get the source texture of the shape.
public const IntRect&getTextureRect() const Get the sub-rectangle of the texture displayed by the shape.
public const Color&getFillColor() const Get the fill color of the shape.
public const Color&getOutlineColor() const Get the outline color of the shape.
public float getOutlineThickness() const Get the outline thickness of the shape.
public FloatRect getLocalBounds() const Get the local bounding rectangle of the entity.
public FloatRect getGlobalBounds() const Get the global (non-minimal) bounding rectangle of the entity.
public void setPosition(float x,float y) set the position of the object
public void setPosition(const Vector2f & position) set the position of the object
public void setRotation(float angle) set the orientation of the object
public void setScale(float factorX,float factorY) set the scale factors of the object
public void setScale(const Vector2f & factors) set the scale factors of the object
public void setOrigin(float x,float y) set the local origin of the object
public void setOrigin(const Vector2f & origin) set the local origin of the object
public const Vector2f&getPosition() const get the position of the object
public float getRotation() const get the orientation of the object
public const Vector2f&getScale() const get the current scale of the object
public const Vector2f&getOrigin() const get the local origin of the object
public void move(float offsetX,float offsetY) Move the object by a given offset.
public void move(const Vector2f & offset) Move the object by a given offset.
public void rotate(float angle) Rotate the object.
public void scale(float factorX,float factorY) Scale the object.
public void scale(const Vector2f & factor) Scale the object.
public const Transform&getTransform() const get the combined transform of the object
public const Transform&getInverseTransform() const get the inverse of the combined transform of the object
protected void update() Recompute the internal geometry of the shape.

Members

public explicit CircleShape(float radius,std::size_t pointCount)

Default constructor.

Parameters

  • radius Radius of the circle

  • pointCount Number of points composing the circle

public void setRadius(float radius)

Set the radius of the circle.

Parameters

  • radius New radius of the circle

See also: getRadius

public float getRadius() const

Get the radius of the circle.

Returns

Radius of the circle

See also: setRadius

public void setPointCount(std::size_t count)

Set the number of points of the circle.

Parameters

  • count New number of points of the circle

See also: getPointCount

public virtual std::size_t getPointCount() const

Get the number of points of the circle.

Returns

Number of points of the circle

See also: setPointCount

public virtual Vector2f getPoint(std::size_t index) const

Get a point of the circle.

The returned point is in local coordinates, that is, the shape's transforms (position, rotation, scale) are not taken into account. The result is undefined if index is out of the valid range.

Parameters

Returns

index-th point of the shape

public void setTexture(const Texture * texture,bool resetRect)

Change the source texture of the shape.

The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behavior is undefined. texture can be NULL to disable texturing. If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.

Parameters

  • texture New texture

  • resetRect Should the texture rect be reset to the size of the new texture?

See also: getTexture, setTextureRect

public void setTextureRect(const IntRect & rect)

Set the sub-rectangle of the texture that the shape will display.

The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.

Parameters

  • rect Rectangle defining the region of the texture to display

See also: getTextureRect, setTexture

public void setFillColor(const Color & color)

Set the fill color of the shape.

This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use sf::Color::Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.

Parameters

  • color New color of the shape

See also: getFillColor, setOutlineColor

public void setOutlineColor(const Color & color)

Set the outline color of the shape.

By default, the shape's outline color is opaque white.

Parameters

  • color New outline color of the shape

See also: getOutlineColor, setFillColor

public void setOutlineThickness(float thickness)

Set the thickness of the shape's outline.

Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.

Parameters

  • thickness New outline thickness

See also: getOutlineThickness

public const Texture*getTexture() const

Get the source texture of the shape.

If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.

Returns

Pointer to the shape's texture

See also: setTexture

public const IntRect&getTextureRect() const

Get the sub-rectangle of the texture displayed by the shape.

Returns

Texture rectangle of the shape

See also: setTextureRect

public const Color&getFillColor() const

Get the fill color of the shape.

Returns

Fill color of the shape

See also: setFillColor

public const Color&getOutlineColor() const

Get the outline color of the shape.

Returns

Outline color of the shape

See also: setOutlineColor

public float getOutlineThickness() const

Get the outline thickness of the shape.

Returns

Outline thickness of the shape

See also: setOutlineThickness

public FloatRect getLocalBounds() const

Get the local bounding rectangle of the entity.

The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.

Returns

Local bounding rectangle of the entity

public FloatRect getGlobalBounds() const

Get the global (non-minimal) bounding rectangle of the entity.

The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the shape in the global 2D world's coordinate system.

This function does not necessarily return the minimal bounding rectangle. It merely ensures that the returned rectangle covers all the vertices (but possibly more). This allows for a fast approximation of the bounds as a first check; you may want to use more precise checks on top of that.

Returns

Global bounding rectangle of the entity

public void setPosition(float x,float y)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new position

  • y Y coordinate of the new position

See also: move, getPosition

public void setPosition(const Vector2f & position)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • position New position

See also: move, getPosition

public void setRotation(float angle)

set the orientation of the object

This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.

Parameters

  • angle New rotation, in degrees

See also: rotate, getRotation

public void setScale(float factorX,float factorY)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factorX New horizontal scale factor

  • factorY New vertical scale factor

See also: scale, getScale

public void setScale(const Vector2f & factors)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factors New scale factors

See also: scale, getScale

public void setOrigin(float x,float y)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new origin

  • y Y coordinate of the new origin

See also: getOrigin

public void setOrigin(const Vector2f & origin)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • origin New origin

See also: getOrigin

public const Vector2f&getPosition() const

get the position of the object

Returns

Current position

See also: setPosition

public float getRotation() const

get the orientation of the object

The rotation is always in the range [0, 360].

Returns

Current rotation, in degrees

See also: setRotation

public const Vector2f&getScale() const

get the current scale of the object

Returns

Current scale factors

See also: setScale

public const Vector2f&getOrigin() const

get the local origin of the object

Returns

Current origin

See also: setOrigin

public void move(float offsetX,float offsetY)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f pos = object.getPosition();
object.setPosition(pos.x + offsetX, pos.y + offsetY);

Parameters

  • offsetX X offset

  • offsetY Y offset

See also: setPosition

public void move(const Vector2f & offset)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

object.setPosition(object.getPosition() + offset);

Parameters

  • offset Offset

See also: setPosition

public void rotate(float angle)

Rotate the object.

This function adds to the current rotation of the object, unlike setRotation which overwrites it. Thus, it is equivalent to the following code:

object.setRotation(object.getRotation() + angle);

Parameters

  • angle Angle of rotation, in degrees

public void scale(float factorX,float factorY)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factorX, scale.y * factorY);

Parameters

  • factorX Horizontal scale factor

  • factorY Vertical scale factor

See also: setScale

public void scale(const Vector2f & factor)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factor.x, scale.y * factor.y);

Parameters

  • factor Scale factors

See also: setScale

public const Transform&getTransform() const

get the combined transform of the object

Returns

Transform combining the position/rotation/scale/origin of the object

See also: getInverseTransform

public const Transform&getInverseTransform() const

get the inverse of the combined transform of the object

Returns

Inverse of the combined transformations applied to the object

See also: getTransform

protected void update()

Recompute the internal geometry of the shape.

This function must be called by the derived class everytime the shape's points change (i.e. the result of either getPointCount or getPoint is different).

class sf::Color

Utility class for manipulating RGBA colors.

sf::Color is a simple color class composed of 4 components:

  • Red

  • Green

  • Blue

  • Alpha (opacity)

Each component is a public member, an unsigned integer in the range [0, 255]. Thus, colors can be constructed and manipulated very easily:

sf::Color color(255, 0, 0); // red
color.r = 0;                // make it black
color.b = 128;              // make it dark blue

The fourth component of colors, named "alpha", represents the opacity of the color. A color with an alpha value of 255 will be fully opaque, while an alpha value of 0 will make a color fully transparent, whatever the value of the other components is.

The most common colors are already defined as static variables:

sf::Color black       = sf::Color::Black;
sf::Color white       = sf::Color::White;
sf::Color red         = sf::Color::Red;
sf::Color green       = sf::Color::Green;
sf::Color blue        = sf::Color::Blue;
sf::Color yellow      = sf::Color::Yellow;
sf::Color magenta     = sf::Color::Magenta;
sf::Color cyan        = sf::Color::Cyan;
sf::Color transparent = sf::Color::Transparent;

Colors can also be added and modulated (multiplied) using the overloaded operators + and *.

Summary

Members Descriptions
public Uint8 r Red component.
public Uint8 g Green component.
public Uint8 b Blue component.
public Uint8 a Alpha (opacity) component.
public Color() Default constructor.
public Color(Uint8 red,Uint8 green,Uint8 blue,Uint8 alpha) Construct the color from its 4 RGBA components.
public explicit Color(Uint32 color) Construct the color from 32-bit unsigned integer.
public Uint32 toInteger() const Retrieve the color as a 32-bit unsigned integer.

Members

public Uint8 r

Red component.

public Uint8 g

Green component.

public Uint8 b

Blue component.

public Uint8 a

Alpha (opacity) component.

public Color()

Default constructor.

Constructs an opaque black color. It is equivalent to sf::Color(0, 0, 0, 255).

public Color(Uint8 red,Uint8 green,Uint8 blue,Uint8 alpha)

Construct the color from its 4 RGBA components.

Parameters

  • red Red component (in the range [0, 255])

  • green Green component (in the range [0, 255])

  • blue Blue component (in the range [0, 255])

  • alpha Alpha (opacity) component (in the range [0, 255])

public explicit Color(Uint32 color)

Construct the color from 32-bit unsigned integer.

Parameters

  • color Number containing the RGBA components (in that order)

public Uint32 toInteger() const

Retrieve the color as a 32-bit unsigned integer.

Returns

Color represented as a 32-bit unsigned integer

class sf::ConvexShape

class sf::ConvexShape
  : public sf::Shape

Specialized shape representing a convex polygon.

This class inherits all the functions of sf::Transformable (position, rotation, scale, bounds, ...) as well as the functions of sf::Shape (outline, color, texture, ...).

It is important to keep in mind that a convex shape must always be... convex, otherwise it may not be drawn correctly. Moreover, the points must be defined in order; using a random order would result in an incorrect shape.

Usage example:

sf::ConvexShape polygon;
polygon.setPointCount(3);
polygon.setPoint(0, sf::Vector2f(0, 0));
polygon.setPoint(1, sf::Vector2f(0, 10));
polygon.setPoint(2, sf::Vector2f(25, 5));
polygon.setOutlineColor(sf::Color::Red);
polygon.setOutlineThickness(5);
polygon.setPosition(10, 20);
...
window.draw(polygon);

See also: sf::Shape, sf::RectangleShape, sf::CircleShape

Summary

Members Descriptions
public explicit ConvexShape(std::size_t pointCount) Default constructor.
public void setPointCount(std::size_t count) Set the number of points of the polygon.
public virtual std::size_t getPointCount() const Get the number of points of the polygon.
public void setPoint(std::size_t index,const Vector2f & point) Set the position of a point.
public virtual Vector2f getPoint(std::size_t index) const Get the position of a point.
public void setTexture(const Texture * texture,bool resetRect) Change the source texture of the shape.
public void setTextureRect(const IntRect & rect) Set the sub-rectangle of the texture that the shape will display.
public void setFillColor(const Color & color) Set the fill color of the shape.
public void setOutlineColor(const Color & color) Set the outline color of the shape.
public void setOutlineThickness(float thickness) Set the thickness of the shape's outline.
public const Texture*getTexture() const Get the source texture of the shape.
public const IntRect&getTextureRect() const Get the sub-rectangle of the texture displayed by the shape.
public const Color&getFillColor() const Get the fill color of the shape.
public const Color&getOutlineColor() const Get the outline color of the shape.
public float getOutlineThickness() const Get the outline thickness of the shape.
public FloatRect getLocalBounds() const Get the local bounding rectangle of the entity.
public FloatRect getGlobalBounds() const Get the global (non-minimal) bounding rectangle of the entity.
public void setPosition(float x,float y) set the position of the object
public void setPosition(const Vector2f & position) set the position of the object
public void setRotation(float angle) set the orientation of the object
public void setScale(float factorX,float factorY) set the scale factors of the object
public void setScale(const Vector2f & factors) set the scale factors of the object
public void setOrigin(float x,float y) set the local origin of the object
public void setOrigin(const Vector2f & origin) set the local origin of the object
public const Vector2f&getPosition() const get the position of the object
public float getRotation() const get the orientation of the object
public const Vector2f&getScale() const get the current scale of the object
public const Vector2f&getOrigin() const get the local origin of the object
public void move(float offsetX,float offsetY) Move the object by a given offset.
public void move(const Vector2f & offset) Move the object by a given offset.
public void rotate(float angle) Rotate the object.
public void scale(float factorX,float factorY) Scale the object.
public void scale(const Vector2f & factor) Scale the object.
public const Transform&getTransform() const get the combined transform of the object
public const Transform&getInverseTransform() const get the inverse of the combined transform of the object
protected void update() Recompute the internal geometry of the shape.

Members

public explicit ConvexShape(std::size_t pointCount)

Default constructor.

Parameters

  • pointCount Number of points of the polygon

public void setPointCount(std::size_t count)

Set the number of points of the polygon.

count must be greater than 2 to define a valid shape.

Parameters

  • count New number of points of the polygon

See also: getPointCount

public virtual std::size_t getPointCount() const

Get the number of points of the polygon.

Returns

Number of points of the polygon

See also: setPointCount

public void setPoint(std::size_t index,const Vector2f & point)

Set the position of a point.

Don't forget that the polygon must remain convex, and the points need to stay ordered! setPointCount must be called first in order to set the total number of points. The result is undefined if index is out of the valid range.

Parameters

  • index Index of the point to change, in range [0 .. getPointCount() - 1]

  • point New position of the point

See also: getPoint

public virtual Vector2f getPoint(std::size_t index) const

Get the position of a point.

The returned point is in local coordinates, that is, the shape's transforms (position, rotation, scale) are not taken into account. The result is undefined if index is out of the valid range.

Parameters

Returns

Position of the index-th point of the polygon

See also: setPoint

public void setTexture(const Texture * texture,bool resetRect)

Change the source texture of the shape.

The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behavior is undefined. texture can be NULL to disable texturing. If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.

Parameters

  • texture New texture

  • resetRect Should the texture rect be reset to the size of the new texture?

See also: getTexture, setTextureRect

public void setTextureRect(const IntRect & rect)

Set the sub-rectangle of the texture that the shape will display.

The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.

Parameters

  • rect Rectangle defining the region of the texture to display

See also: getTextureRect, setTexture

public void setFillColor(const Color & color)

Set the fill color of the shape.

This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use sf::Color::Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.

Parameters

  • color New color of the shape

See also: getFillColor, setOutlineColor

public void setOutlineColor(const Color & color)

Set the outline color of the shape.

By default, the shape's outline color is opaque white.

Parameters

  • color New outline color of the shape

See also: getOutlineColor, setFillColor

public void setOutlineThickness(float thickness)

Set the thickness of the shape's outline.

Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.

Parameters

  • thickness New outline thickness

See also: getOutlineThickness

public const Texture*getTexture() const

Get the source texture of the shape.

If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.

Returns

Pointer to the shape's texture

See also: setTexture

public const IntRect&getTextureRect() const

Get the sub-rectangle of the texture displayed by the shape.

Returns

Texture rectangle of the shape

See also: setTextureRect

public const Color&getFillColor() const

Get the fill color of the shape.

Returns

Fill color of the shape

See also: setFillColor

public const Color&getOutlineColor() const

Get the outline color of the shape.

Returns

Outline color of the shape

See also: setOutlineColor

public float getOutlineThickness() const

Get the outline thickness of the shape.

Returns

Outline thickness of the shape

See also: setOutlineThickness

public FloatRect getLocalBounds() const

Get the local bounding rectangle of the entity.

The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.

Returns

Local bounding rectangle of the entity

public FloatRect getGlobalBounds() const

Get the global (non-minimal) bounding rectangle of the entity.

The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the shape in the global 2D world's coordinate system.

This function does not necessarily return the minimal bounding rectangle. It merely ensures that the returned rectangle covers all the vertices (but possibly more). This allows for a fast approximation of the bounds as a first check; you may want to use more precise checks on top of that.

Returns

Global bounding rectangle of the entity

public void setPosition(float x,float y)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new position

  • y Y coordinate of the new position

See also: move, getPosition

public void setPosition(const Vector2f & position)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • position New position

See also: move, getPosition

public void setRotation(float angle)

set the orientation of the object

This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.

Parameters

  • angle New rotation, in degrees

See also: rotate, getRotation

public void setScale(float factorX,float factorY)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factorX New horizontal scale factor

  • factorY New vertical scale factor

See also: scale, getScale

public void setScale(const Vector2f & factors)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factors New scale factors

See also: scale, getScale

public void setOrigin(float x,float y)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new origin

  • y Y coordinate of the new origin

See also: getOrigin

public void setOrigin(const Vector2f & origin)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • origin New origin

See also: getOrigin

public const Vector2f&getPosition() const

get the position of the object

Returns

Current position

See also: setPosition

public float getRotation() const

get the orientation of the object

The rotation is always in the range [0, 360].

Returns

Current rotation, in degrees

See also: setRotation

public const Vector2f&getScale() const

get the current scale of the object

Returns

Current scale factors

See also: setScale

public const Vector2f&getOrigin() const

get the local origin of the object

Returns

Current origin

See also: setOrigin

public void move(float offsetX,float offsetY)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f pos = object.getPosition();
object.setPosition(pos.x + offsetX, pos.y + offsetY);

Parameters

  • offsetX X offset

  • offsetY Y offset

See also: setPosition

public void move(const Vector2f & offset)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

object.setPosition(object.getPosition() + offset);

Parameters

  • offset Offset

See also: setPosition

public void rotate(float angle)

Rotate the object.

This function adds to the current rotation of the object, unlike setRotation which overwrites it. Thus, it is equivalent to the following code:

object.setRotation(object.getRotation() + angle);

Parameters

  • angle Angle of rotation, in degrees

public void scale(float factorX,float factorY)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factorX, scale.y * factorY);

Parameters

  • factorX Horizontal scale factor

  • factorY Vertical scale factor

See also: setScale

public void scale(const Vector2f & factor)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factor.x, scale.y * factor.y);

Parameters

  • factor Scale factors

See also: setScale

public const Transform&getTransform() const

get the combined transform of the object

Returns

Transform combining the position/rotation/scale/origin of the object

See also: getInverseTransform

public const Transform&getInverseTransform() const

get the inverse of the combined transform of the object

Returns

Inverse of the combined transformations applied to the object

See also: getTransform

protected void update()

Recompute the internal geometry of the shape.

This function must be called by the derived class everytime the shape's points change (i.e. the result of either getPointCount or getPoint is different).

class sf::Drawable

Abstract base class for objects that can be drawn to a render target.

sf::Drawable is a very simple base class that allows objects of derived classes to be drawn to a sf::RenderTarget.

All you have to do in your derived class is to override the draw virtual function.

Note that inheriting from sf::Drawable is not mandatory, but it allows this nice syntax "window.draw(object)" rather than "object.draw(window)", which is more consistent with other SFML classes.

Example:

class MyDrawable : public sf::Drawable
{
public:

   ...

private:

    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
        // You can draw other high-level objects
        target.draw(m_sprite, states);

        // ... or use the low-level API
        states.texture = &m_texture;
        target.draw(m_vertices, states);

        // ... or draw with OpenGL directly
        glBegin(GL_QUADS);
        ...
        glEnd();
    }

    sf::Sprite m_sprite;
    sf::Texture m_texture;
    sf::VertexArray m_vertices;
};

See also: sf::RenderTarget

Summary

Members Descriptions
public inline virtual ~Drawable() Virtual destructor.
protected void draw(RenderTarget & target,RenderStates states) const Draw the object to a render target.

Members

public inline virtual ~Drawable()

Virtual destructor.

protected void draw(RenderTarget & target,RenderStates states) const

Draw the object to a render target.

This is a pure virtual function that has to be implemented by the derived class to define how the drawable should be drawn.

Parameters

  • target Render target to draw to

  • states Current render states

class sf::Font

Class for loading and manipulating character fonts.

Fonts can be loaded from a file, from memory or from a custom stream, and supports the most common types of fonts.

See the loadFromFile function for the complete list of supported formats.

Once it is loaded, a sf::Font instance provides three types of information about the font:

  • Global metrics, such as the line spacing

  • Per-glyph metrics, such as bounding box or kerning

  • Pixel representation of glyphs

Fonts alone are not very useful: they hold the font data but cannot make anything useful of it. To do so you need to use the sf::Text class, which is able to properly output text with several options such as character size, style, color, position, rotation, etc. This separation allows more flexibility and better performances: indeed a sf::Font is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Text is a lightweight object which can combine the glyphs data and metrics of a sf::Font to display any text on a render target. Note that it is also possible to bind several sf::Text instances to the same sf::Font.

It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text).

Usage example:

// Declare a new font
sf::Font font;

// Load it from a file
if (!font.loadFromFile("arial.ttf"))
{
    // error...
}

// Create a text which uses our font
sf::Text text1;
text1.setFont(font);
text1.setCharacterSize(30);
text1.setStyle(sf::Text::Regular);

// Create another text using the same font, but with different parameters
sf::Text text2;
text2.setFont(font);
text2.setCharacterSize(50);
text2.setStyle(sf::Text::Italic);

Apart from loading font files, and passing them to instances of sf::Text, you should normally not have to deal directly with this class. However, it may be useful to access the font metrics or rasterized glyphs for advanced usage.

Note that if the font is a bitmap font, it is not scalable, thus not all requested sizes will be available to use. This needs to be taken into consideration when using sf::Text. If you need to display text of a certain size, make sure the corresponding bitmap font that supports that size is used.

See also: sf::Text

Summary

Members Descriptions
public Font() Default constructor.
public Font(const Font & copy) Copy constructor.
public ~Font() Destructor.
public bool loadFromFile(const std::string & filename) Load the font from a file.
public bool loadFromMemory(const void * data,std::size_t sizeInBytes) Load the font from a file in memory.
public bool loadFromStream(InputStream & stream) Load the font from a custom stream.
public const Info&getInfo() const Get the font information.
public const Glyph&getGlyph(Uint32 codePoint,unsigned int characterSize,bool bold,float outlineThickness) const Retrieve a glyph of the font.
public float getKerning(Uint32 first,Uint32 second,unsigned int characterSize) const Get the kerning offset of two glyphs.
public float getLineSpacing(unsigned int characterSize) const Get the line spacing.
public float getUnderlinePosition(unsigned int characterSize) const Get the position of the underline.
public float getUnderlineThickness(unsigned int characterSize) const Get the thickness of the underline.
public const Texture&getTexture(unsigned int characterSize) const Retrieve the texture containing the loaded glyphs of a certain size.
public Font&operator=(const Font & right) Overload of assignment operator.

Members

public Font()

Default constructor.

This constructor defines an empty font

public Font(const Font & copy)

Copy constructor.

Parameters

  • copy Instance to copy

public ~Font()

Destructor.

Cleans up all the internal resources used by the font

public bool loadFromFile(const std::string & filename)

Load the font from a file.

The supported font formats are: TrueType, Type 1, CFF, OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42. Note that this function knows nothing about the standard fonts installed on the user's system, thus you can't load them directly.

SFML cannot preload all the font data in this function, so the file has to remain accessible until the sf::Font object loads a new font or is destroyed.

Parameters

  • filename Path of the font file to load

Returns

True if loading succeeded, false if it failed

See also: loadFromMemory, loadFromStream

public bool loadFromMemory(const void * data,std::size_t sizeInBytes)

Load the font from a file in memory.

The supported font formats are: TrueType, Type 1, CFF, OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42.

SFML cannot preload all the font data in this function, so the buffer pointed by data has to remain valid until the sf::Font object loads a new font or is destroyed.

Parameters

  • data Pointer to the file data in memory

  • sizeInBytes Size of the data to load, in bytes

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromStream

public bool loadFromStream(InputStream & stream)

Load the font from a custom stream.

The supported font formats are: TrueType, Type 1, CFF, OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42. Warning: SFML cannot preload all the font data in this function, so the contents of stream have to remain valid as long as the font is used.

SFML cannot preload all the font data in this function, so the stream has to remain accessible until the sf::Font object loads a new font or is destroyed.

Parameters

  • stream Source stream to read from

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromMemory

public const Info&getInfo() const

Get the font information.

Returns

A structure that holds the font information

public const Glyph&getGlyph(Uint32 codePoint,unsigned int characterSize,bool bold,float outlineThickness) const

Retrieve a glyph of the font.

If the font is a bitmap font, not all character sizes might be available. If the glyph is not available at the requested size, an empty glyph is returned.

Be aware that using a negative value for the outline thickness will cause distorted rendering.

Parameters

  • codePoint Unicode code point of the character to get

  • characterSize Reference character size

  • bold Retrieve the bold version or the regular one?

  • outlineThickness Thickness of outline (when != 0 the glyph will not be filled)

Returns

The glyph corresponding to codePoint and characterSize

public float getKerning(Uint32 first,Uint32 second,unsigned int characterSize) const

Get the kerning offset of two glyphs.

The kerning is an extra offset (negative) to apply between two glyphs when rendering them, to make the pair look more "natural". For example, the pair "AV" have a special kerning to make them closer than other characters. Most of the glyphs pairs have a kerning offset of zero, though.

Parameters

  • first Unicode code point of the first character

  • second Unicode code point of the second character

  • characterSize Reference character size

Returns

Kerning value for first and second, in pixels

public float getLineSpacing(unsigned int characterSize) const

Get the line spacing.

Line spacing is the vertical offset to apply between two consecutive lines of text.

Parameters

  • characterSize Reference character size

Returns

Line spacing, in pixels

public float getUnderlinePosition(unsigned int characterSize) const

Get the position of the underline.

Underline position is the vertical offset to apply between the baseline and the underline.

Parameters

  • characterSize Reference character size

Returns

Underline position, in pixels

See also: getUnderlineThickness

public float getUnderlineThickness(unsigned int characterSize) const

Get the thickness of the underline.

Underline thickness is the vertical size of the underline.

Parameters

  • characterSize Reference character size

Returns

Underline thickness, in pixels

See also: getUnderlinePosition

public const Texture&getTexture(unsigned int characterSize) const

Retrieve the texture containing the loaded glyphs of a certain size.

The contents of the returned texture changes as more glyphs are requested, thus it is not very relevant. It is mainly used internally by sf::Text.

Parameters

  • characterSize Reference character size

Returns

Texture containing the glyphs of the requested size

public Font&operator=(const Font & right)

Overload of assignment operator.

Parameters

  • right Instance to assign

Returns

Reference to self

class sf::Glyph

Structure describing a glyph.

A glyph is the visual representation of a character.

The sf::Glyph structure provides the information needed to handle the glyph:

  • its coordinates in the font's texture

  • its bounding rectangle

  • the offset to apply to get the starting position of the next glyph

See also: sf::Font

Summary

Members Descriptions
public float advance Offset to move horizontally to the next character.
public FloatRect bounds Bounding rectangle of the glyph, in coordinates relative to the baseline.
public IntRect textureRect Texture coordinates of the glyph inside the font's texture.
public inline Glyph() Default constructor.

Members

public float advance

Offset to move horizontally to the next character.

Bounding rectangle of the glyph, in coordinates relative to the baseline.

Texture coordinates of the glyph inside the font's texture.

public inline Glyph()

Default constructor.

class sf::Image

Class for loading, manipulating and saving images.

sf::Image is an abstraction to manipulate images as bidimensional arrays of pixels.

The class provides functions to load, read, write and save pixels, as well as many other useful functions.

sf::Image can handle a unique internal representation of pixels, which is RGBA 32 bits. This means that a pixel must be composed of 8 bits red, green, blue and alpha channels just like a sf::Color. All the functions that return an array of pixels follow this rule, and all parameters that you pass to sf::Image functions (such as loadFromMemory) must use this representation as well.

A sf::Image can be copied, but it is a heavy resource and if possible you should always use [const] references to pass or return them to avoid useless copies.

Usage example:

// Load an image file from a file
sf::Image background;
if (!background.loadFromFile("background.jpg"))
    return -1;

// Create a 20x20 image filled with black color
sf::Image image;
image.create(20, 20, sf::Color::Black);

// Copy image1 on image2 at position (10, 10)
image.copy(background, 10, 10);

// Make the top-left pixel transparent
sf::Color color = image.getPixel(0, 0);
color.a = 0;
image.setPixel(0, 0, color);

// Save the image to a file
if (!image.saveToFile("result.png"))
    return -1;

See also: sf::Texture

Summary

Members Descriptions
public Image() Default constructor.
public ~Image() Destructor.
public void create(unsigned int width,unsigned int height,const Color & color) Create the image and fill it with a unique color.
public void create(unsigned int width,unsigned int height,const Uint8 * pixels) Create the image from an array of pixels.
public bool loadFromFile(const std::string & filename) Load the image from a file on disk.
public bool loadFromMemory(const void * data,std::size_t size) Load the image from a file in memory.
public bool loadFromStream(InputStream & stream) Load the image from a custom stream.
public bool saveToFile(const std::string & filename) const Save the image to a file on disk.
public Vector2u getSize() const Return the size (width and height) of the image.
public void createMaskFromColor(const Color & color,Uint8 alpha) Create a transparency mask from a specified color-key.
public void copy(const Image& source,unsigned int destX,unsigned int destY,constIntRect & sourceRect,bool applyAlpha) Copy pixels from another image onto this one.
public void setPixel(unsigned int x,unsigned int y,const Color & color) Change the color of a pixel.
public Color getPixel(unsigned int x,unsigned int y) const Get the color of a pixel.
public const Uint8 * getPixelsPtr() const Get a read-only pointer to the array of pixels.
public void flipHorizontally() Flip the image horizontally (left <-> right)
public void flipVertically() Flip the image vertically (top <-> bottom)

Members

public Image()

Default constructor.

Creates an empty image.

public ~Image()

Destructor.

public void create(unsigned int width,unsigned int height,const Color & color)

Create the image and fill it with a unique color.

Parameters

  • width Width of the image

  • height Height of the image

  • color Fill color

public void create(unsigned int width,unsigned int height,const Uint8 * pixels)

Create the image from an array of pixels.

The pixel array is assumed to contain 32-bits RGBA pixels, and have the given width and height. If not, this is an undefined behavior. If pixels is null, an empty image is created.

Parameters

  • width Width of the image

  • height Height of the image

  • pixels Array of pixels to copy to the image

public bool loadFromFile(const std::string & filename)

Load the image from a file on disk.

The supported image formats are bmp, png, tga, jpg, gif, psd, hdr and pic. Some format options are not supported, like progressive jpeg. If this function fails, the image is left unchanged.

Parameters

  • filename Path of the image file to load

Returns

True if loading was successful

See also: loadFromMemory, loadFromStream, saveToFile

public bool loadFromMemory(const void * data,std::size_t size)

Load the image from a file in memory.

The supported image formats are bmp, png, tga, jpg, gif, psd, hdr and pic. Some format options are not supported, like progressive jpeg. If this function fails, the image is left unchanged.

Parameters

  • data Pointer to the file data in memory

  • size Size of the data to load, in bytes

Returns

True if loading was successful

See also: loadFromFile, loadFromStream

public bool loadFromStream(InputStream & stream)

Load the image from a custom stream.

The supported image formats are bmp, png, tga, jpg, gif, psd, hdr and pic. Some format options are not supported, like progressive jpeg. If this function fails, the image is left unchanged.

Parameters

  • stream Source stream to read from

Returns

True if loading was successful

See also: loadFromFile, loadFromMemory

public bool saveToFile(const std::string & filename) const

Save the image to a file on disk.

The format of the image is automatically deduced from the extension. The supported image formats are bmp, png, tga and jpg. The destination file is overwritten if it already exists. This function fails if the image is empty.

Parameters

  • filename Path of the file to save

Returns

True if saving was successful

See also: create, loadFromFile, loadFromMemory

public Vector2u getSize() const

Return the size (width and height) of the image.

Returns

Size of the image, in pixels

public void createMaskFromColor(const Color & color,Uint8 alpha)

Create a transparency mask from a specified color-key.

This function sets the alpha value of every pixel matching the given color to alpha (0 by default), so that they become transparent.

Parameters

  • color Color to make transparent

  • alpha Alpha value to assign to transparent pixels

public void copy(const Image& source,unsigned int destX,unsigned int destY,constIntRect & sourceRect,bool applyAlpha)

Copy pixels from another image onto this one.

This function does a slow pixel copy and should not be used intensively. It can be used to prepare a complex static image from several others, but if you need this kind of feature in real-time you'd better use sf::RenderTexture.

If sourceRect is empty, the whole image is copied. If applyAlpha is set to true, the transparency of source pixels is applied. If it is false, the pixels are copied unchanged with their alpha value.

Parameters

  • source Source image to copy

  • destX X coordinate of the destination position

  • destY Y coordinate of the destination position

  • sourceRect Sub-rectangle of the source image to copy

  • applyAlpha Should the copy take into account the source transparency?

public void setPixel(unsigned int x,unsigned int y,const Color & color)

Change the color of a pixel.

This function doesn't check the validity of the pixel coordinates, using out-of-range values will result in an undefined behavior.

Parameters

  • x X coordinate of pixel to change

  • y Y coordinate of pixel to change

  • color New color of the pixel

See also: getPixel

public Color getPixel(unsigned int x,unsigned int y) const

Get the color of a pixel.

This function doesn't check the validity of the pixel coordinates, using out-of-range values will result in an undefined behavior.

Parameters

  • x X coordinate of pixel to get

  • y Y coordinate of pixel to get

Returns

Color of the pixel at coordinates (x, y)

See also: setPixel

public const Uint8 * getPixelsPtr() const

Get a read-only pointer to the array of pixels.

The returned value points to an array of RGBA pixels made of 8 bits integers components. The size of the array is width * height * 4 (getSize().x * getSize().y * 4). Warning: the returned pointer may become invalid if you modify the image, so you should never store it for too long. If the image is empty, a null pointer is returned.

Returns

Read-only pointer to the array of pixels

public void flipHorizontally()

Flip the image horizontally (left <-> right)

public void flipVertically()

Flip the image vertically (top <-> bottom)

class sf::Rect

Utility class for manipulating 2D axis aligned rectangles.

A rectangle is defined by its top-left corner and its size.

It is a very simple class defined for convenience, so its member variables (left, top, width and height) are public and can be accessed directly, just like the vector classes (Vector2 and Vector3).

To keep things simple, sf::Rect doesn't define functions to emulate the properties that are not directly members (such as right, bottom, center, etc.), it rather only provides intersection functions.

sf::Rect uses the usual rules for its boundaries:

  • The left and top edges are included in the rectangle's area

  • The right (left + width) and bottom (top + height) edges are excluded from the rectangle's area

This means that sf::IntRect(0, 0, 1, 1) and sf::IntRect(1, 1, 1, 1) don't intersect.

sf::Rect is a template and may be used with any numeric type, but for simplicity the instantiations used by SFML are typedef'd:

  • sf::Rect is sf::IntRect

  • sf::Rect is sf::FloatRect

So that you don't have to care about the template syntax.

Usage example:

// Define a rectangle, located at (0, 0) with a size of 20x5
sf::IntRect r1(0, 0, 20, 5);

// Define another rectangle, located at (4, 2) with a size of 18x10
sf::Vector2i position(4, 2);
sf::Vector2i size(18, 10);
sf::IntRect r2(position, size);

// Test intersections with the point (3, 1)
bool b1 = r1.contains(3, 1); // true
bool b2 = r2.contains(3, 1); // false

// Test the intersection between r1 and r2
sf::IntRect result;
bool b3 = r1.intersects(r2, result); // true
// result == (4, 2, 16, 3)

Summary

Members Descriptions
public T left Left coordinate of the rectangle.
public T top Top coordinate of the rectangle.
public T width Width of the rectangle.
public T height Height of the rectangle.
public Rect() Default constructor.
public Rect(T rectLeft,T rectTop,T rectWidth,T rectHeight) Construct the rectangle from its coordinates.
public Rect(const Vector2< T > & position,const Vector2< T > & size) Construct the rectangle from position and size.
public template<>
explicitRect(const Rect< U > & rectangle)
Construct the rectangle from another type of rectangle.
public bool contains(T x,T y) const Check if a point is inside the rectangle's area.
public bool contains(const Vector2< T > & point) const Check if a point is inside the rectangle's area.
public bool intersects(const Rect< T > & rectangle) const Check the intersection between two rectangles.
public bool intersects(const Rect< T > & rectangle,Rect< T > & intersection) const Check the intersection between two rectangles.

Members

public T left

Left coordinate of the rectangle.

public T top

Top coordinate of the rectangle.

public T width

Width of the rectangle.

public T height

Height of the rectangle.

public Rect()

Default constructor.

Creates an empty rectangle (it is equivalent to calling Rect(0, 0, 0, 0)).

public Rect(T rectLeft,T rectTop,T rectWidth,T rectHeight)

Construct the rectangle from its coordinates.

Be careful, the last two parameters are the width and height, not the right and bottom coordinates!

Parameters

  • rectLeft Left coordinate of the rectangle

  • rectTop Top coordinate of the rectangle

  • rectWidth Width of the rectangle

  • rectHeight Height of the rectangle

public Rect(const Vector2< T > & position,const Vector2< T > & size)

Construct the rectangle from position and size.

Be careful, the last parameter is the size, not the bottom-right corner!

Parameters

  • position Position of the top-left corner of the rectangle

  • size Size of the rectangle

public template<>
explicitRect(const Rect< U > & rectangle)

Construct the rectangle from another type of rectangle.

This constructor doesn't replace the copy constructor, it's called only when U != T. A call to this constructor will fail to compile if U is not convertible to T.

Parameters

  • rectangle Rectangle to convert

public bool contains(T x,T y) const

Check if a point is inside the rectangle's area.

This check is non-inclusive. If the point lies on the edge of the rectangle, this function will return false.

Parameters

  • x X coordinate of the point to test

  • y Y coordinate of the point to test

Returns

True if the point is inside, false otherwise

See also: intersects

public bool contains(const Vector2< T > & point) const

Check if a point is inside the rectangle's area.

This check is non-inclusive. If the point lies on the edge of the rectangle, this function will return false.

Parameters

  • point Point to test

Returns

True if the point is inside, false otherwise

See also: intersects

public bool intersects(const Rect< T > & rectangle) const

Check the intersection between two rectangles.

Parameters

  • rectangle Rectangle to test

Returns

True if rectangles overlap, false otherwise

See also: contains

public bool intersects(const Rect< T > & rectangle,Rect< T > & intersection) const

Check the intersection between two rectangles.

This overload returns the overlapped rectangle in the intersection parameter.

Parameters

  • rectangle Rectangle to test

  • intersection Rectangle to be filled with the intersection

Returns

True if rectangles overlap, false otherwise

See also: contains

class sf::RectangleShape

class sf::RectangleShape
  : public sf::Shape

Specialized shape representing a rectangle.

This class inherits all the functions of sf::Transformable (position, rotation, scale, bounds, ...) as well as the functions of sf::Shape (outline, color, texture, ...).

Usage example:

sf::RectangleShape rectangle;
rectangle.setSize(sf::Vector2f(100, 50));
rectangle.setOutlineColor(sf::Color::Red);
rectangle.setOutlineThickness(5);
rectangle.setPosition(10, 20);
...
window.draw(rectangle);

See also: sf::Shape, sf::CircleShape, sf::ConvexShape

Summary

Members Descriptions
public explicit RectangleShape(const Vector2f & size) Default constructor.
public void setSize(const Vector2f & size) Set the size of the rectangle.
public const Vector2f&getSize() const Get the size of the rectangle.
public virtual std::size_t getPointCount() const Get the number of points defining the shape.
public virtual Vector2f getPoint(std::size_t index) const Get a point of the rectangle.
public void setTexture(const Texture * texture,bool resetRect) Change the source texture of the shape.
public void setTextureRect(const IntRect & rect) Set the sub-rectangle of the texture that the shape will display.
public void setFillColor(const Color & color) Set the fill color of the shape.
public void setOutlineColor(const Color & color) Set the outline color of the shape.
public void setOutlineThickness(float thickness) Set the thickness of the shape's outline.
public const Texture*getTexture() const Get the source texture of the shape.
public const IntRect&getTextureRect() const Get the sub-rectangle of the texture displayed by the shape.
public const Color&getFillColor() const Get the fill color of the shape.
public const Color&getOutlineColor() const Get the outline color of the shape.
public float getOutlineThickness() const Get the outline thickness of the shape.
public FloatRect getLocalBounds() const Get the local bounding rectangle of the entity.
public FloatRect getGlobalBounds() const Get the global (non-minimal) bounding rectangle of the entity.
public void setPosition(float x,float y) set the position of the object
public void setPosition(const Vector2f & position) set the position of the object
public void setRotation(float angle) set the orientation of the object
public void setScale(float factorX,float factorY) set the scale factors of the object
public void setScale(const Vector2f & factors) set the scale factors of the object
public void setOrigin(float x,float y) set the local origin of the object
public void setOrigin(const Vector2f & origin) set the local origin of the object
public const Vector2f&getPosition() const get the position of the object
public float getRotation() const get the orientation of the object
public const Vector2f&getScale() const get the current scale of the object
public const Vector2f&getOrigin() const get the local origin of the object
public void move(float offsetX,float offsetY) Move the object by a given offset.
public void move(const Vector2f & offset) Move the object by a given offset.
public void rotate(float angle) Rotate the object.
public void scale(float factorX,float factorY) Scale the object.
public void scale(const Vector2f & factor) Scale the object.
public const Transform&getTransform() const get the combined transform of the object
public const Transform&getInverseTransform() const get the inverse of the combined transform of the object
protected void update() Recompute the internal geometry of the shape.

Members

public explicit RectangleShape(const Vector2f & size)

Default constructor.

Parameters

  • size Size of the rectangle

public void setSize(const Vector2f & size)

Set the size of the rectangle.

Parameters

  • size New size of the rectangle

See also: getSize

public const Vector2f&getSize() const

Get the size of the rectangle.

Returns

Size of the rectangle

See also: setSize

public virtual std::size_t getPointCount() const

Get the number of points defining the shape.

Returns

Number of points of the shape. For rectangle shapes, this number is always 4.

public virtual Vector2f getPoint(std::size_t index) const

Get a point of the rectangle.

The returned point is in local coordinates, that is, the shape's transforms (position, rotation, scale) are not taken into account. The result is undefined if index is out of the valid range.

Parameters

  • index Index of the point to get, in range [0 .. 3]

Returns

index-th point of the shape

public void setTexture(const Texture * texture,bool resetRect)

Change the source texture of the shape.

The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behavior is undefined. texture can be NULL to disable texturing. If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.

Parameters

  • texture New texture

  • resetRect Should the texture rect be reset to the size of the new texture?

See also: getTexture, setTextureRect

public void setTextureRect(const IntRect & rect)

Set the sub-rectangle of the texture that the shape will display.

The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.

Parameters

  • rect Rectangle defining the region of the texture to display

See also: getTextureRect, setTexture

public void setFillColor(const Color & color)

Set the fill color of the shape.

This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use sf::Color::Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.

Parameters

  • color New color of the shape

See also: getFillColor, setOutlineColor

public void setOutlineColor(const Color & color)

Set the outline color of the shape.

By default, the shape's outline color is opaque white.

Parameters

  • color New outline color of the shape

See also: getOutlineColor, setFillColor

public void setOutlineThickness(float thickness)

Set the thickness of the shape's outline.

Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.

Parameters

  • thickness New outline thickness

See also: getOutlineThickness

public const Texture*getTexture() const

Get the source texture of the shape.

If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.

Returns

Pointer to the shape's texture

See also: setTexture

public const IntRect&getTextureRect() const

Get the sub-rectangle of the texture displayed by the shape.

Returns

Texture rectangle of the shape

See also: setTextureRect

public const Color&getFillColor() const

Get the fill color of the shape.

Returns

Fill color of the shape

See also: setFillColor

public const Color&getOutlineColor() const

Get the outline color of the shape.

Returns

Outline color of the shape

See also: setOutlineColor

public float getOutlineThickness() const

Get the outline thickness of the shape.

Returns

Outline thickness of the shape

See also: setOutlineThickness

public FloatRect getLocalBounds() const

Get the local bounding rectangle of the entity.

The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.

Returns

Local bounding rectangle of the entity

public FloatRect getGlobalBounds() const

Get the global (non-minimal) bounding rectangle of the entity.

The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the shape in the global 2D world's coordinate system.

This function does not necessarily return the minimal bounding rectangle. It merely ensures that the returned rectangle covers all the vertices (but possibly more). This allows for a fast approximation of the bounds as a first check; you may want to use more precise checks on top of that.

Returns

Global bounding rectangle of the entity

public void setPosition(float x,float y)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new position

  • y Y coordinate of the new position

See also: move, getPosition

public void setPosition(const Vector2f & position)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • position New position

See also: move, getPosition

public void setRotation(float angle)

set the orientation of the object

This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.

Parameters

  • angle New rotation, in degrees

See also: rotate, getRotation

public void setScale(float factorX,float factorY)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factorX New horizontal scale factor

  • factorY New vertical scale factor

See also: scale, getScale

public void setScale(const Vector2f & factors)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factors New scale factors

See also: scale, getScale

public void setOrigin(float x,float y)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new origin

  • y Y coordinate of the new origin

See also: getOrigin

public void setOrigin(const Vector2f & origin)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • origin New origin

See also: getOrigin

public const Vector2f&getPosition() const

get the position of the object

Returns

Current position

See also: setPosition

public float getRotation() const

get the orientation of the object

The rotation is always in the range [0, 360].

Returns

Current rotation, in degrees

See also: setRotation

public const Vector2f&getScale() const

get the current scale of the object

Returns

Current scale factors

See also: setScale

public const Vector2f&getOrigin() const

get the local origin of the object

Returns

Current origin

See also: setOrigin

public void move(float offsetX,float offsetY)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f pos = object.getPosition();
object.setPosition(pos.x + offsetX, pos.y + offsetY);

Parameters

  • offsetX X offset

  • offsetY Y offset

See also: setPosition

public void move(const Vector2f & offset)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

object.setPosition(object.getPosition() + offset);

Parameters

  • offset Offset

See also: setPosition

public void rotate(float angle)

Rotate the object.

This function adds to the current rotation of the object, unlike setRotation which overwrites it. Thus, it is equivalent to the following code:

object.setRotation(object.getRotation() + angle);

Parameters

  • angle Angle of rotation, in degrees

public void scale(float factorX,float factorY)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factorX, scale.y * factorY);

Parameters

  • factorX Horizontal scale factor

  • factorY Vertical scale factor

See also: setScale

public void scale(const Vector2f & factor)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factor.x, scale.y * factor.y);

Parameters

  • factor Scale factors

See also: setScale

public const Transform&getTransform() const

get the combined transform of the object

Returns

Transform combining the position/rotation/scale/origin of the object

See also: getInverseTransform

public const Transform&getInverseTransform() const

get the inverse of the combined transform of the object

Returns

Inverse of the combined transformations applied to the object

See also: getTransform

protected void update()

Recompute the internal geometry of the shape.

This function must be called by the derived class everytime the shape's points change (i.e. the result of either getPointCount or getPoint is different).

class sf::RenderStates

Define the states used for drawing to a RenderTarget.

There are four global states that can be applied to the drawn objects:

  • the blend mode: how pixels of the object are blended with the background

  • the transform: how the object is positioned/rotated/scaled

  • the texture: what image is mapped to the object

  • the shader: what custom effect is applied to the object

High-level objects such as sprites or text force some of these states when they are drawn. For example, a sprite will set its own texture, so that you don't have to care about it when drawing the sprite.

The transform is a special case: sprites, texts and shapes (and it's a good idea to do it with your own drawable classes too) combine their transform with the one that is passed in the RenderStates structure. So that you can use a "global" transform on top of each object's transform.

Most objects, especially high-level drawables, can be drawn directly without defining render states explicitly the default set of states is ok in most cases.

window.draw(sprite);

If you want to use a single specific render state, for example a shader, you can pass it directly to the Draw function: sf::RenderStates has an implicit one-argument constructor for each state.

window.draw(sprite, shader);

When you're inside the Draw function of a drawable object (inherited from sf::Drawable), you can either pass the render states unmodified, or change some of them. For example, a transformable object will combine the current transform with its own transform. A sprite will set its texture. Etc.

See also: sf::RenderTarget, sf::Drawable

Summary

Members Descriptions
public BlendMode blendMode Blending mode.
public Transform transform Transform.
public const Texture*texture Texture.
public const Shader*shader Shader.
public RenderStates() Default constructor.
public RenderStates(const BlendMode & theBlendMode) Construct a default set of render states with a custom blend mode.
public RenderStates(const Transform & theTransform) Construct a default set of render states with a custom transform.
public RenderStates(const Texture * theTexture) Construct a default set of render states with a custom texture.
public RenderStates(const Shader * theShader) Construct a default set of render states with a custom shader.
public RenderStates(const BlendMode& theBlendMode,constTransform& theTransform,constTexture* theTexture,constShader * theShader) Construct a set of render states with all its attributes.

Members

Blending mode.

Transform.

public const Texture*texture

Texture.

public const Shader*shader

Shader.

public RenderStates()

Default constructor.

Constructing a default set of render states is equivalent to using sf::RenderStates::Default. The default set defines:

  • the BlendAlpha blend mode

  • the identity transform

  • a null texture

  • a null shader

public RenderStates(const BlendMode & theBlendMode)

Construct a default set of render states with a custom blend mode.

Parameters

  • theBlendMode Blend mode to use

public RenderStates(const Transform & theTransform)

Construct a default set of render states with a custom transform.

Parameters

public RenderStates(const Texture * theTexture)

Construct a default set of render states with a custom texture.

Parameters

public RenderStates(const Shader * theShader)

Construct a default set of render states with a custom shader.

Parameters

public RenderStates(const BlendMode& theBlendMode,constTransform& theTransform,constTexture* theTexture,constShader * theShader)

Construct a set of render states with all its attributes.

Parameters

  • theBlendMode Blend mode to use

  • theTransform Transform to use

  • theTexture Texture to use

  • theShader Shader to use

class sf::RenderTarget

class sf::RenderTarget
  : private sf::NonCopyable

Base class for all render targets (window, texture, ...)

sf::RenderTarget defines the common behavior of all the 2D render targets usable in the graphics module.

It makes it possible to draw 2D entities like sprites, shapes, text without using any OpenGL command directly.

A sf::RenderTarget is also able to use views (sf::View), which are a kind of 2D cameras. With views you can globally scroll, rotate or zoom everything that is drawn, without having to transform every single entity. See the documentation of sf::View for more details and sample pieces of code about this class.

On top of that, render targets are still able to render direct OpenGL stuff. It is even possible to mix together OpenGL calls and regular SFML drawing commands. When doing so, make sure that OpenGL states are not messed up by calling the pushGLStates/popGLStates functions.

See also: sf::RenderWindow, sf::RenderTexture, sf::View

Summary

Members Descriptions
public virtual ~RenderTarget() Destructor.
public void clear(const Color & color) Clear the entire target with a single color.
public void setView(const View & view) Change the current active view.
public const View&getView() const Get the view currently in use in the render target.
public const View&getDefaultView() const Get the default view of the render target.
public IntRect getViewport(const View & view) const Get the viewport of a view, applied to this render target.
public Vector2f mapPixelToCoords(const Vector2i & point) const Convert a point from target coordinates to world coordinates, using the current view.
public Vector2f mapPixelToCoords(const Vector2i& point,constView & view) const Convert a point from target coordinates to world coordinates.
public Vector2i mapCoordsToPixel(const Vector2f & point) const Convert a point from world coordinates to target coordinates, using the current view.
public Vector2i mapCoordsToPixel(const Vector2f& point,constView & view) const Convert a point from world coordinates to target coordinates.
public void draw(const Drawable& drawable,constRenderStates & states) Draw a drawable object to the render target.
public void draw(const Vertex * vertices,std::size_t vertexCount,PrimitiveTypetype,constRenderStates & states) Draw primitives defined by an array of vertices.
public void draw(const VertexBuffer& vertexBuffer,constRenderStates & states) Draw primitives defined by a vertex buffer.
public void draw(const VertexBuffer& vertexBuffer,std::size_t firstVertex,std::size_t vertexCount,constRenderStates & states) Draw primitives defined by a vertex buffer.
public Vector2u getSize() const Return the size of the rendering region of the target.
public bool setActive(bool active) Activate or deactivate the render target for rendering.
public void pushGLStates() Save the current OpenGL render states and matrices.
public void popGLStates() Restore the previously saved OpenGL render states and matrices.
public void resetGLStates() Reset the internal OpenGL states so that the target is ready for drawing.
protected RenderTarget() Default constructor.
protected void initialize() Performs the common initialization step after creation.

Members

public virtual ~RenderTarget()

Destructor.

public void clear(const Color & color)

Clear the entire target with a single color.

This function is usually called once every frame, to clear the previous contents of the target.

Parameters

  • color Fill color to use to clear the render target

public void setView(const View & view)

Change the current active view.

The view is like a 2D camera, it controls which part of the 2D scene is visible, and how it is viewed in the render target. The new view will affect everything that is drawn, until another view is set. The render target keeps its own copy of the view object, so it is not necessary to keep the original one alive after calling this function. To restore the original view of the target, you can pass the result of getDefaultView() to this function.

Parameters

  • view New view to use

See also: getView, getDefaultView

public const View&getView() const

Get the view currently in use in the render target.

Returns

The view object that is currently used

See also: setView, getDefaultView

public const View&getDefaultView() const

Get the default view of the render target.

The default view has the initial size of the render target, and never changes after the target has been created.

Returns

The default view of the render target

See also: setView, getView

public IntRect getViewport(const View & view) const

Get the viewport of a view, applied to this render target.

The viewport is defined in the view as a ratio, this function simply applies this ratio to the current dimensions of the render target to calculate the pixels rectangle that the viewport actually covers in the target.

Parameters

  • view The view for which we want to compute the viewport

Returns

Viewport rectangle, expressed in pixels

public Vector2f mapPixelToCoords(const Vector2i & point) const

Convert a point from target coordinates to world coordinates, using the current view.

This function is an overload of the mapPixelToCoords function that implicitly uses the current view. It is equivalent to:

target.mapPixelToCoords(point, target.getView());

Parameters

  • point Pixel to convert

Returns

The converted point, in "world" coordinates

See also: mapCoordsToPixel

public Vector2f mapPixelToCoords(const Vector2i& point,constView & view) const

Convert a point from target coordinates to world coordinates.

This function finds the 2D position that matches the given pixel of the render target. In other words, it does the inverse of what the graphics card does, to find the initial position of a rendered pixel.

Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (10, 50) in your render target may map to the point (150, 75) in your 2D world if the view is translated by (140, 25).

For render-windows, this function is typically used to find which point (or object) is located below the mouse cursor.

This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.

Parameters

  • point Pixel to convert

  • view The view to use for converting the point

Returns

The converted point, in "world" units

See also: mapCoordsToPixel

public Vector2i mapCoordsToPixel(const Vector2f & point) const

Convert a point from world coordinates to target coordinates, using the current view.

This function is an overload of the mapCoordsToPixel function that implicitly uses the current view. It is equivalent to:

target.mapCoordsToPixel(point, target.getView());

Parameters

  • point Point to convert

Returns

The converted point, in target coordinates (pixels)

See also: mapPixelToCoords

public Vector2i mapCoordsToPixel(const Vector2f& point,constView & view) const

Convert a point from world coordinates to target coordinates.

This function finds the pixel of the render target that matches the given 2D point. In other words, it goes through the same process as the graphics card, to compute the final position of a rendered point.

Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (150, 75) in your 2D world may map to the pixel (10, 50) of your render target if the view is translated by (140, 25).

This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.

Parameters

  • point Point to convert

  • view The view to use for converting the point

Returns

The converted point, in target coordinates (pixels)

See also: mapPixelToCoords

public void draw(const Drawable& drawable,constRenderStates & states)

Draw a drawable object to the render target.

Parameters

  • drawable Object to draw

  • states Render states to use for drawing

public void draw(const Vertex * vertices,std::size_t vertexCount,PrimitiveTypetype,constRenderStates & states)

Draw primitives defined by an array of vertices.

Parameters

  • vertices Pointer to the vertices

  • vertexCount Number of vertices in the array

  • type Type of primitives to draw

  • states Render states to use for drawing

public void draw(const VertexBuffer& vertexBuffer,constRenderStates & states)

Draw primitives defined by a vertex buffer.

Parameters

  • vertexBuffer Vertex buffer

  • states Render states to use for drawing

public void draw(const VertexBuffer& vertexBuffer,std::size_t firstVertex,std::size_t vertexCount,constRenderStates & states)

Draw primitives defined by a vertex buffer.

Parameters

  • vertexBuffer Vertex buffer

  • firstVertex Index of the first vertex to render

  • vertexCount Number of vertices to render

  • states Render states to use for drawing

public Vector2u getSize() const

Return the size of the rendering region of the target.

Returns

Size in pixels

public bool setActive(bool active)

Activate or deactivate the render target for rendering.

This function makes the render target's context current for future OpenGL rendering operations (so you shouldn't care about it if you're not doing direct OpenGL stuff). A render target's context is active only on the current thread, if you want to make it active on another thread you have to deactivate it on the previous thread first if it was active. Only one context can be current in a thread, so if you want to draw OpenGL geometry to another render target don't forget to activate it again. Activating a render target will automatically deactivate the previously active context (if any).

Parameters

  • active True to activate, false to deactivate

Returns

True if operation was successful, false otherwise

public void pushGLStates()

Save the current OpenGL render states and matrices.

This function can be used when you mix SFML drawing and direct OpenGL rendering. Combined with popGLStates, it ensures that:

  • SFML's internal states are not messed up by your OpenGL code

  • your OpenGL states are not modified by a call to a SFML function

More specifically, it must be used around code that calls Draw functions. Example:

// OpenGL code here...
window.pushGLStates();
window.draw(...);
window.draw(...);
window.popGLStates();
// OpenGL code here...

Note that this function is quite expensive: it saves all the possible OpenGL states and matrices, even the ones you don't care about. Therefore it should be used wisely. It is provided for convenience, but the best results will be achieved if you handle OpenGL states yourself (because you know which states have really changed, and need to be saved and restored). Take a look at the resetGLStates function if you do so.

See also: popGLStates

public void popGLStates()

Restore the previously saved OpenGL render states and matrices.

See the description of pushGLStates to get a detailed description of these functions.

See also: pushGLStates

public void resetGLStates()

Reset the internal OpenGL states so that the target is ready for drawing.

This function can be used when you mix SFML drawing and direct OpenGL rendering, if you choose not to use pushGLStates/popGLStates. It makes sure that all OpenGL states needed by SFML are set, so that subsequent draw() calls will work as expected.

Example:

// OpenGL code here...
glPushAttrib(...);
window.resetGLStates();
window.draw(...);
window.draw(...);
glPopAttrib(...);
// OpenGL code here...

protected RenderTarget()

Default constructor.

protected void initialize()

Performs the common initialization step after creation.

The derived classes must call this function after the target is created and ready for drawing.

class sf::RenderTexture

class sf::RenderTexture
  : public sf::RenderTarget

Target for off-screen 2D rendering into a texture.

sf::RenderTexture is the little brother of sf::RenderWindow.

It implements the same 2D drawing and OpenGL-related functions (see their base class sf::RenderTarget for more details), the difference is that the result is stored in an off-screen texture rather than being show in a window.

Rendering to a texture can be useful in a variety of situations:

  • precomputing a complex static texture (like a level's background from multiple tiles)

  • applying post-effects to the whole scene with shaders

  • creating a sprite from a 3D object rendered with OpenGL

  • etc.

Usage example:

// Create a new render-window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");

// Create a new render-texture
sf::RenderTexture texture;
if (!texture.create(500, 500))
    return -1;

// The main loop
while (window.isOpen())
{
   // Event processing
   // ...

   // Clear the whole texture with red color
   texture.clear(sf::Color::Red);

   // Draw stuff to the texture
   texture.draw(sprite);  // sprite is a sf::Sprite
   texture.draw(shape);   // shape is a sf::Shape
   texture.draw(text);    // text is a sf::Text

   // We're done drawing to the texture
   texture.display();

   // Now we start rendering to the window, clear it first
   window.clear();

   // Draw the texture
   sf::Sprite sprite(texture.getTexture());
   window.draw(sprite);

   // End the current frame and display its contents on screen
   window.display();
}

Like sf::RenderWindow, sf::RenderTexture is still able to render direct OpenGL stuff. It is even possible to mix together OpenGL calls and regular SFML drawing commands. If you need a depth buffer for 3D rendering, don't forget to request it when calling RenderTexture::create.

See also: sf::RenderTarget, sf::RenderWindow, sf::View, sf::Texture

Summary

Members Descriptions
public RenderTexture() Default constructor.
public virtual ~RenderTexture() Destructor.
public bool create(unsigned int width,unsigned int height,bool depthBuffer) Create the render-texture.
public bool create(unsigned int width,unsigned int height,const ContextSettings & settings) Create the render-texture.
public void setSmooth(bool smooth) Enable or disable texture smoothing.
public bool isSmooth() const Tell whether the smooth filtering is enabled or not.
public void setRepeated(bool repeated) Enable or disable texture repeating.
public bool isRepeated() const Tell whether the texture is repeated or not.
public bool generateMipmap() Generate a mipmap using the current texture data.
public virtual bool setActive(bool active) Activate or deactivate the render-texture for rendering.
public void display() Update the contents of the target texture.
public virtual Vector2u getSize() const Return the size of the rendering region of the texture.
public const Texture&getTexture() const Get a read-only reference to the target texture.
public void clear(const Color & color) Clear the entire target with a single color.
public void setView(const View & view) Change the current active view.
public const View&getView() const Get the view currently in use in the render target.
public const View&getDefaultView() const Get the default view of the render target.
public IntRect getViewport(const View & view) const Get the viewport of a view, applied to this render target.
public Vector2f mapPixelToCoords(const Vector2i & point) const Convert a point from target coordinates to world coordinates, using the current view.
public Vector2f mapPixelToCoords(const Vector2i& point,constView & view) const Convert a point from target coordinates to world coordinates.
public Vector2i mapCoordsToPixel(const Vector2f & point) const Convert a point from world coordinates to target coordinates, using the current view.
public Vector2i mapCoordsToPixel(const Vector2f& point,constView & view) const Convert a point from world coordinates to target coordinates.
public void draw(const Drawable& drawable,constRenderStates & states) Draw a drawable object to the render target.
public void draw(const Vertex * vertices,std::size_t vertexCount,PrimitiveTypetype,constRenderStates & states) Draw primitives defined by an array of vertices.
public void draw(const VertexBuffer& vertexBuffer,constRenderStates & states) Draw primitives defined by a vertex buffer.
public void draw(const VertexBuffer& vertexBuffer,std::size_t firstVertex,std::size_t vertexCount,constRenderStates & states) Draw primitives defined by a vertex buffer.
public void pushGLStates() Save the current OpenGL render states and matrices.
public void popGLStates() Restore the previously saved OpenGL render states and matrices.
public void resetGLStates() Reset the internal OpenGL states so that the target is ready for drawing.
protected void initialize() Performs the common initialization step after creation.

Members

public RenderTexture()

Default constructor.

Constructs an empty, invalid render-texture. You must call create to have a valid render-texture.

See also: create

public virtual ~RenderTexture()

Destructor.

public bool create(unsigned int width,unsigned int height,bool depthBuffer)

Create the render-texture.

Before calling this function, the render-texture is in an invalid state, thus it is mandatory to call it before doing anything with the render-texture. The last parameter, depthBuffer, is useful if you want to use the render-texture for 3D OpenGL rendering that requires a depth buffer. Otherwise it is unnecessary, and you should leave this parameter to false (which is its default value).

Parameters

  • width Width of the render-texture

  • height Height of the render-texture

  • depthBuffer Do you want this render-texture to have a depth buffer?

Returns

True if creation has been successful

Deprecated: Use create(unsigned int, unsigned int, const ContextSettings&) instead.

public bool create(unsigned int width,unsigned int height,const ContextSettings & settings)

Create the render-texture.

Before calling this function, the render-texture is in an invalid state, thus it is mandatory to call it before doing anything with the render-texture. The last parameter, settings, is useful if you want to enable multi-sampling or use the render-texture for OpenGL rendering that requires a depth or stencil buffer. Otherwise it is unnecessary, and you should leave this parameter at its default value.

Parameters

  • width Width of the render-texture

  • height Height of the render-texture

  • settings Additional settings for the underlying OpenGL texture and context

Returns

True if creation has been successful

public void setSmooth(bool smooth)

Enable or disable texture smoothing.

This function is similar to Texture::setSmooth. This parameter is disabled by default.

Parameters

  • smooth True to enable smoothing, false to disable it

See also: isSmooth

public bool isSmooth() const

Tell whether the smooth filtering is enabled or not.

Returns

True if texture smoothing is enabled

See also: setSmooth

public void setRepeated(bool repeated)

Enable or disable texture repeating.

This function is similar to Texture::setRepeated. This parameter is disabled by default.

Parameters

  • repeated True to enable repeating, false to disable it

See also: isRepeated

public bool isRepeated() const

Tell whether the texture is repeated or not.

Returns

True if texture is repeated

See also: setRepeated

public bool generateMipmap()

Generate a mipmap using the current texture data.

This function is similar to Texture::generateMipmap and operates on the texture used as the target for drawing. Be aware that any draw operation may modify the base level image data. For this reason, calling this function only makes sense after all drawing is completed and display has been called. Not calling display after subsequent drawing will lead to undefined behavior if a mipmap had been previously generated.

Returns

True if mipmap generation was successful, false if unsuccessful

public virtual bool setActive(bool active)

Activate or deactivate the render-texture for rendering.

This function makes the render-texture's context current for future OpenGL rendering operations (so you shouldn't care about it if you're not doing direct OpenGL stuff). Only one context can be current in a thread, so if you want to draw OpenGL geometry to another render target (like a RenderWindow) don't forget to activate it again.

Parameters

  • active True to activate, false to deactivate

Returns

True if operation was successful, false otherwise

public void display()

Update the contents of the target texture.

This function updates the target texture with what has been drawn so far. Like for windows, calling this function is mandatory at the end of rendering. Not calling it may leave the texture in an undefined state.

public virtual Vector2u getSize() const

Return the size of the rendering region of the texture.

The returned value is the size that you passed to the create function.

Returns

Size in pixels

public const Texture&getTexture() const

Get a read-only reference to the target texture.

After drawing to the render-texture and calling Display, you can retrieve the updated texture using this function, and draw it using a sprite (for example). The internal sf::Texture of a render-texture is always the same instance, so that it is possible to call this function once and keep a reference to the texture even after it is modified.

Returns

Const reference to the texture

public void clear(const Color & color)

Clear the entire target with a single color.

This function is usually called once every frame, to clear the previous contents of the target.

Parameters

  • color Fill color to use to clear the render target

public void setView(const View & view)

Change the current active view.

The view is like a 2D camera, it controls which part of the 2D scene is visible, and how it is viewed in the render target. The new view will affect everything that is drawn, until another view is set. The render target keeps its own copy of the view object, so it is not necessary to keep the original one alive after calling this function. To restore the original view of the target, you can pass the result of getDefaultView() to this function.

Parameters

  • view New view to use

See also: getView, getDefaultView

public const View&getView() const

Get the view currently in use in the render target.

Returns

The view object that is currently used

See also: setView, getDefaultView

public const View&getDefaultView() const

Get the default view of the render target.

The default view has the initial size of the render target, and never changes after the target has been created.

Returns

The default view of the render target

See also: setView, getView

public IntRect getViewport(const View & view) const

Get the viewport of a view, applied to this render target.

The viewport is defined in the view as a ratio, this function simply applies this ratio to the current dimensions of the render target to calculate the pixels rectangle that the viewport actually covers in the target.

Parameters

  • view The view for which we want to compute the viewport

Returns

Viewport rectangle, expressed in pixels

public Vector2f mapPixelToCoords(const Vector2i & point) const

Convert a point from target coordinates to world coordinates, using the current view.

This function is an overload of the mapPixelToCoords function that implicitly uses the current view. It is equivalent to:

target.mapPixelToCoords(point, target.getView());

Parameters

  • point Pixel to convert

Returns

The converted point, in "world" coordinates

See also: mapCoordsToPixel

public Vector2f mapPixelToCoords(const Vector2i& point,constView & view) const

Convert a point from target coordinates to world coordinates.

This function finds the 2D position that matches the given pixel of the render target. In other words, it does the inverse of what the graphics card does, to find the initial position of a rendered pixel.

Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (10, 50) in your render target may map to the point (150, 75) in your 2D world if the view is translated by (140, 25).

For render-windows, this function is typically used to find which point (or object) is located below the mouse cursor.

This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.

Parameters

  • point Pixel to convert

  • view The view to use for converting the point

Returns

The converted point, in "world" units

See also: mapCoordsToPixel

public Vector2i mapCoordsToPixel(const Vector2f & point) const

Convert a point from world coordinates to target coordinates, using the current view.

This function is an overload of the mapCoordsToPixel function that implicitly uses the current view. It is equivalent to:

target.mapCoordsToPixel(point, target.getView());

Parameters

  • point Point to convert

Returns

The converted point, in target coordinates (pixels)

See also: mapPixelToCoords

public Vector2i mapCoordsToPixel(const Vector2f& point,constView & view) const

Convert a point from world coordinates to target coordinates.

This function finds the pixel of the render target that matches the given 2D point. In other words, it goes through the same process as the graphics card, to compute the final position of a rendered point.

Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (150, 75) in your 2D world may map to the pixel (10, 50) of your render target if the view is translated by (140, 25).

This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.

Parameters

  • point Point to convert

  • view The view to use for converting the point

Returns

The converted point, in target coordinates (pixels)

See also: mapPixelToCoords

public void draw(const Drawable& drawable,constRenderStates & states)

Draw a drawable object to the render target.

Parameters

  • drawable Object to draw

  • states Render states to use for drawing

public void draw(const Vertex * vertices,std::size_t vertexCount,PrimitiveTypetype,constRenderStates & states)

Draw primitives defined by an array of vertices.

Parameters

  • vertices Pointer to the vertices

  • vertexCount Number of vertices in the array

  • type Type of primitives to draw

  • states Render states to use for drawing

public void draw(const VertexBuffer& vertexBuffer,constRenderStates & states)

Draw primitives defined by a vertex buffer.

Parameters

  • vertexBuffer Vertex buffer

  • states Render states to use for drawing

public void draw(const VertexBuffer& vertexBuffer,std::size_t firstVertex,std::size_t vertexCount,constRenderStates & states)

Draw primitives defined by a vertex buffer.

Parameters

  • vertexBuffer Vertex buffer

  • firstVertex Index of the first vertex to render

  • vertexCount Number of vertices to render

  • states Render states to use for drawing

public void pushGLStates()

Save the current OpenGL render states and matrices.

This function can be used when you mix SFML drawing and direct OpenGL rendering. Combined with popGLStates, it ensures that:

  • SFML's internal states are not messed up by your OpenGL code

  • your OpenGL states are not modified by a call to a SFML function

More specifically, it must be used around code that calls Draw functions. Example:

// OpenGL code here...
window.pushGLStates();
window.draw(...);
window.draw(...);
window.popGLStates();
// OpenGL code here...

Note that this function is quite expensive: it saves all the possible OpenGL states and matrices, even the ones you don't care about. Therefore it should be used wisely. It is provided for convenience, but the best results will be achieved if you handle OpenGL states yourself (because you know which states have really changed, and need to be saved and restored). Take a look at the resetGLStates function if you do so.

See also: popGLStates

public void popGLStates()

Restore the previously saved OpenGL render states and matrices.

See the description of pushGLStates to get a detailed description of these functions.

See also: pushGLStates

public void resetGLStates()

Reset the internal OpenGL states so that the target is ready for drawing.

This function can be used when you mix SFML drawing and direct OpenGL rendering, if you choose not to use pushGLStates/popGLStates. It makes sure that all OpenGL states needed by SFML are set, so that subsequent draw() calls will work as expected.

Example:

// OpenGL code here...
glPushAttrib(...);
window.resetGLStates();
window.draw(...);
window.draw(...);
glPopAttrib(...);
// OpenGL code here...

protected void initialize()

Performs the common initialization step after creation.

The derived classes must call this function after the target is created and ready for drawing.

class sf::RenderWindow

class sf::RenderWindow
  : public sf::Window
  : public sf::RenderTarget

Window that can serve as a target for 2D drawing.

sf::RenderWindow is the main class of the Graphics module.

It defines an OS window that can be painted using the other classes of the graphics module.

sf::RenderWindow is derived from sf::Window, thus it inherits all its features: events, window management, OpenGL rendering, etc. See the documentation of sf::Window for a more complete description of all these features, as well as code examples.

On top of that, sf::RenderWindow adds more features related to 2D drawing with the graphics module (see its base class sf::RenderTarget for more details). Here is a typical rendering and event loop with a sf::RenderWindow:

// Declare and create a new render-window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");

// Limit the framerate to 60 frames per second (this step is optional)
window.setFramerateLimit(60);

// The main loop - ends as soon as the window is closed
while (window.isOpen())
{
   // Event processing
   sf::Event event;
   while (window.pollEvent(event))
   {
       // Request for closing the window
       if (event.type == sf::Event::Closed)
           window.close();
   }

   // Clear the whole window before rendering a new frame
   window.clear();

   // Draw some graphical entities
   window.draw(sprite);
   window.draw(circle);
   window.draw(text);

   // End the current frame and display its contents on screen
   window.display();
}

Like sf::Window, sf::RenderWindow is still able to render direct OpenGL stuff. It is even possible to mix together OpenGL calls and regular SFML drawing commands.

// Create the render window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML OpenGL");

// Create a sprite and a text to display
sf::Sprite sprite;
sf::Text text;
...

// Perform OpenGL initializations
glMatrixMode(GL_PROJECTION);
...

// Start the rendering loop
while (window.isOpen())
{
    // Process events
    ...

    // Draw a background sprite
    window.pushGLStates();
    window.draw(sprite);
    window.popGLStates();

    // Draw a 3D object using OpenGL
    glBegin(GL_QUADS);
        glVertex3f(...);
        ...
    glEnd();

    // Draw text on top of the 3D object
    window.pushGLStates();
    window.draw(text);
    window.popGLStates();

    // Finally, display the rendered frame on screen
    window.display();
}

See also: sf::Window, sf::RenderTarget, sf::RenderTexture, sf::View

Summary

Members Descriptions
public RenderWindow() Default constructor.
public RenderWindow(VideoModemode,constString& title,Uint32 style,constContextSettings & settings) Construct a new window.
public explicit RenderWindow(WindowHandlehandle,constContextSettings & settings) Construct the window from an existing control.
public virtual ~RenderWindow() Destructor.
public virtual Vector2u getSize() const Get the size of the rendering region of the window.
public virtual bool setActive(bool active) Activate or deactivate the window as the current target for OpenGL rendering.
public Image capture() const Copy the current contents of the window to an image.
public void create(VideoModemode,constString& title,Uint32 style,constContextSettings & settings) Create (or recreate) the window.
public void create(WindowHandlehandle,constContextSettings & settings) Create (or recreate) the window from an existing control.
public void close() Close the window and destroy all the attached resources.
public bool isOpen() const Tell whether or not the window is open.
public const ContextSettings&getSettings() const Get the settings of the OpenGL context of the window.
public bool pollEvent(Event & event) Pop the event on top of the event queue, if any, and return it.
public bool waitEvent(Event & event) Wait for an event and return it.
public Vector2i getPosition() const Get the position of the window.
public void setPosition(const Vector2i & position) Change the position of the window on screen.
public void setSize(const Vector2u & size) Change the size of the rendering region of the window.
public void setTitle(const String & title) Change the title of the window.
public void setIcon(unsigned int width,unsigned int height,const Uint8 * pixels) Change the window's icon.
public void setVisible(bool visible) Show or hide the window.
public void setVerticalSyncEnabled(bool enabled) Enable or disable vertical synchronization.
public void setMouseCursorVisible(bool visible) Show or hide the mouse cursor.
public void setMouseCursorGrabbed(bool grabbed) Grab or release the mouse cursor.
public void setMouseCursor(const Cursor & cursor) Set the displayed cursor to a native system cursor.
public void setKeyRepeatEnabled(bool enabled) Enable or disable automatic key-repeat.
public void setFramerateLimit(unsigned int limit) Limit the framerate to a maximum fixed frequency.
public void setJoystickThreshold(float threshold) Change the joystick threshold.
public bool setActive(bool active) const Activate or deactivate the window as the current target for OpenGL rendering.
public void requestFocus() Request the current window to be made the active foreground window.
public bool hasFocus() const Check whether the window has the input focus.
public void display() Display on screen what has been rendered to the window so far.
public WindowHandle getSystemHandle() const Get the OS-specific handle of the window.
public void clear(const Color & color) Clear the entire target with a single color.
public void setView(const View & view) Change the current active view.
public const View&getView() const Get the view currently in use in the render target.
public const View&getDefaultView() const Get the default view of the render target.
public IntRect getViewport(const View & view) const Get the viewport of a view, applied to this render target.
public Vector2f mapPixelToCoords(const Vector2i & point) const Convert a point from target coordinates to world coordinates, using the current view.
public Vector2f mapPixelToCoords(const Vector2i& point,constView & view) const Convert a point from target coordinates to world coordinates.
public Vector2i mapCoordsToPixel(const Vector2f & point) const Convert a point from world coordinates to target coordinates, using the current view.
public Vector2i mapCoordsToPixel(const Vector2f& point,constView & view) const Convert a point from world coordinates to target coordinates.
public void draw(const Drawable& drawable,constRenderStates & states) Draw a drawable object to the render target.
public void draw(const Vertex * vertices,std::size_t vertexCount,PrimitiveTypetype,constRenderStates & states) Draw primitives defined by an array of vertices.
public void draw(const VertexBuffer& vertexBuffer,constRenderStates & states) Draw primitives defined by a vertex buffer.
public void draw(const VertexBuffer& vertexBuffer,std::size_t firstVertex,std::size_t vertexCount,constRenderStates & states) Draw primitives defined by a vertex buffer.
public void pushGLStates() Save the current OpenGL render states and matrices.
public void popGLStates() Restore the previously saved OpenGL render states and matrices.
public void resetGLStates() Reset the internal OpenGL states so that the target is ready for drawing.
protected virtual void onCreate() Function called after the window has been created.
protected virtual void onResize() Function called after the window has been resized.
protected void initialize() Performs the common initialization step after creation.

Members

public RenderWindow()

Default constructor.

This constructor doesn't actually create the window, use the other constructors or call create() to do so.

public RenderWindow(VideoModemode,constString& title,Uint32 style,constContextSettings & settings)

Construct a new window.

This constructor creates the window with the size and pixel depth defined in mode. An optional style can be passed to customize the look and behavior of the window (borders, title bar, resizable, closable, ...).

The fourth parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc. You shouldn't care about these parameters for a regular usage of the graphics module.

Parameters

  • mode Video mode to use (defines the width, height and depth of the rendering area of the window)

  • title Title of the window

  • style Window style, a bitwise OR combination of sf::Style enumerators

  • settings Additional settings for the underlying OpenGL context

public explicit RenderWindow(WindowHandlehandle,constContextSettings & settings)

Construct the window from an existing control.

Use this constructor if you want to create an SFML rendering area into an already existing control.

The second parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc. You shouldn't care about these parameters for a regular usage of the graphics module.

Parameters

  • handle Platform-specific handle of the control (HWND on Windows, Window on Linux/FreeBSD, NSWindow on OS X)

  • settings Additional settings for the underlying OpenGL context

public virtual ~RenderWindow()

Destructor.

Closes the window and frees all the resources attached to it.

public virtual Vector2u getSize() const

Get the size of the rendering region of the window.

The size doesn't include the titlebar and borders of the window.

Returns

Size in pixels

public virtual bool setActive(bool active)

Activate or deactivate the window as the current target for OpenGL rendering.

A window is active only on the current thread, if you want to make it active on another thread you have to deactivate it on the previous thread first if it was active. Only one window can be active on a thread at a time, thus the window previously active (if any) automatically gets deactivated. This is not to be confused with requestFocus().

Parameters

  • active True to activate, false to deactivate

Returns

True if operation was successful, false otherwise

public Image capture() const

Copy the current contents of the window to an image.

Deprecated: Use a sf::Texture and its sf::Texture::update(const Window&) function and copy its contents into an sf::Image instead.

sf::Vector2u windowSize = window.getSize();
sf::Texture texture;
texture.create(windowSize.x, windowSize.y);
texture.update(window);
sf::Image screenshot = texture.copyToImage();

This is a slow operation, whose main purpose is to make screenshots of the application. If you want to update an image with the contents of the window and then use it for drawing, you should rather use a sf::Texture and its update(Window&) function. You can also draw things directly to a texture with the sf::RenderTexture class.

Returns

Image containing the captured contents

public void create(VideoModemode,constString& title,Uint32 style,constContextSettings & settings)

Create (or recreate) the window.

If the window was already created, it closes it first. If style contains Style::Fullscreen, then mode must be a valid video mode.

The fourth parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.

Parameters

  • mode Video mode to use (defines the width, height and depth of the rendering area of the window)

  • title Title of the window

  • style Window style, a bitwise OR combination of sf::Style enumerators

  • settings Additional settings for the underlying OpenGL context

public void create(WindowHandlehandle,constContextSettings & settings)

Create (or recreate) the window from an existing control.

Use this function if you want to create an OpenGL rendering area into an already existing control. If the window was already created, it closes it first.

The second parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.

Parameters

  • handle Platform-specific handle of the control

  • settings Additional settings for the underlying OpenGL context

public void close()

Close the window and destroy all the attached resources.

After calling this function, the sf::Window instance remains valid and you can call create() to recreate the window. All other functions such as pollEvent() or display() will still work (i.e. you don't have to test isOpen() every time), and will have no effect on closed windows.

public bool isOpen() const

Tell whether or not the window is open.

This function returns whether or not the window exists. Note that a hidden window (setVisible(false)) is open (therefore this function would return true).

Returns

True if the window is open, false if it has been closed

public const ContextSettings&getSettings() const

Get the settings of the OpenGL context of the window.

Note that these settings may be different from what was passed to the constructor or the create() function, if one or more settings were not supported. In this case, SFML chose the closest match.

Returns

Structure containing the OpenGL context settings

public bool pollEvent(Event & event)

Pop the event on top of the event queue, if any, and return it.

This function is not blocking: if there's no pending event then it will return false and leave event unmodified. Note that more than one event may be present in the event queue, thus you should always call this function in a loop to make sure that you process every pending event.

sf::Event event;
while (window.pollEvent(event))
{
   // process event...
}

Parameters

  • event Event to be returned

Returns

True if an event was returned, or false if the event queue was empty

See also: waitEvent

public bool waitEvent(Event & event)

Wait for an event and return it.

This function is blocking: if there's no pending event then it will wait until an event is received. After this function returns (and no error occurred), the event object is always valid and filled properly. This function is typically used when you have a thread that is dedicated to events handling: you want to make this thread sleep as long as no new event is received.

sf::Event event;
if (window.waitEvent(event))
{
   // process event...
}

Parameters

  • event Event to be returned

Returns

False if any error occurred

See also: pollEvent

public Vector2i getPosition() const

Get the position of the window.

Returns

Position of the window, in pixels

See also: setPosition

public void setPosition(const Vector2i & position)

Change the position of the window on screen.

This function only works for top-level windows (i.e. it will be ignored for windows created from the handle of a child window/control).

Parameters

  • position New position, in pixels

See also: getPosition

public void setSize(const Vector2u & size)

Change the size of the rendering region of the window.

Parameters

  • size New size, in pixels

See also: getSize

public void setTitle(const String & title)

Change the title of the window.

Parameters

  • title New title

See also: setIcon

public void setIcon(unsigned int width,unsigned int height,const Uint8 * pixels)

Change the window's icon.

pixels must be an array of width x height pixels in 32-bits RGBA format.

The OS default icon is used by default.

Parameters

  • width Icon's width, in pixels

  • height Icon's height, in pixels

  • pixels Pointer to the array of pixels in memory. The pixels are copied, so you need not keep the source alive after calling this function.

See also: setTitle

public void setVisible(bool visible)

Show or hide the window.

The window is shown by default.

Parameters

  • visible True to show the window, false to hide it

public void setVerticalSyncEnabled(bool enabled)

Enable or disable vertical synchronization.

Activating vertical synchronization will limit the number of frames displayed to the refresh rate of the monitor. This can avoid some visual artifacts, and limit the framerate to a good value (but not constant across different computers).

Vertical synchronization is disabled by default.

Parameters

  • enabled True to enable v-sync, false to deactivate it

public void setMouseCursorVisible(bool visible)

Show or hide the mouse cursor.

The mouse cursor is visible by default.

Parameters

  • visible True to show the mouse cursor, false to hide it

public void setMouseCursorGrabbed(bool grabbed)

Grab or release the mouse cursor.

If set, grabs the mouse cursor inside this window's client area so it may no longer be moved outside its bounds. Note that grabbing is only active while the window has focus.

Parameters

  • grabbed True to enable, false to disable

public void setMouseCursor(const Cursor & cursor)

Set the displayed cursor to a native system cursor.

Upon window creation, the arrow cursor is used by default.

The cursor must not be destroyed while in use by the window.

Features related to Cursor are not supported on iOS and Android.

Parameters

  • cursor Native system cursor type to display

See also: sf::Cursor::loadFromSystem

See also: sf::Cursor::loadFromPixels

public void setKeyRepeatEnabled(bool enabled)

Enable or disable automatic key-repeat.

If key repeat is enabled, you will receive repeated KeyPressed events while keeping a key pressed. If it is disabled, you will only get a single event when the key is pressed.

Key repeat is enabled by default.

Parameters

  • enabled True to enable, false to disable

public void setFramerateLimit(unsigned int limit)

Limit the framerate to a maximum fixed frequency.

If a limit is set, the window will use a small delay after each call to display() to ensure that the current frame lasted long enough to match the framerate limit. SFML will try to match the given limit as much as it can, but since it internally uses sf::sleep, whose precision depends on the underlying OS, the results may be a little unprecise as well (for example, you can get 65 FPS when requesting 60).

Parameters

  • limit Framerate limit, in frames per seconds (use 0 to disable limit)

public void setJoystickThreshold(float threshold)

Change the joystick threshold.

The joystick threshold is the value below which no JoystickMoved event will be generated.

The threshold value is 0.1 by default.

Parameters

  • threshold New threshold, in the range [0, 100]

public bool setActive(bool active) const

Activate or deactivate the window as the current target for OpenGL rendering.

A window is active only on the current thread, if you want to make it active on another thread you have to deactivate it on the previous thread first if it was active. Only one window can be active on a thread at a time, thus the window previously active (if any) automatically gets deactivated. This is not to be confused with requestFocus().

Parameters

  • active True to activate, false to deactivate

Returns

True if operation was successful, false otherwise

public void requestFocus()

Request the current window to be made the active foreground window.

At any given time, only one window may have the input focus to receive input events such as keystrokes or mouse events. If a window requests focus, it only hints to the operating system, that it would like to be focused. The operating system is free to deny the request. This is not to be confused with setActive().

See also: hasFocus

public bool hasFocus() const

Check whether the window has the input focus.

At any given time, only one window may have the input focus to receive input events such as keystrokes or most mouse events.

Returns

True if window has focus, false otherwise

See also: requestFocus

public void display()

Display on screen what has been rendered to the window so far.

This function is typically called after all OpenGL rendering has been done for the current frame, in order to show it on screen.

Get the OS-specific handle of the window.

The type of the returned handle is sf::WindowHandle, which is a typedef to the handle type defined by the OS. You shouldn't need to use this function, unless you have very specific stuff to implement that SFML doesn't support, or implement a temporary workaround until a bug is fixed.

Returns

System handle of the window

public void clear(const Color & color)

Clear the entire target with a single color.

This function is usually called once every frame, to clear the previous contents of the target.

Parameters

  • color Fill color to use to clear the render target

public void setView(const View & view)

Change the current active view.

The view is like a 2D camera, it controls which part of the 2D scene is visible, and how it is viewed in the render target. The new view will affect everything that is drawn, until another view is set. The render target keeps its own copy of the view object, so it is not necessary to keep the original one alive after calling this function. To restore the original view of the target, you can pass the result of getDefaultView() to this function.

Parameters

  • view New view to use

See also: getView, getDefaultView

public const View&getView() const

Get the view currently in use in the render target.

Returns

The view object that is currently used

See also: setView, getDefaultView

public const View&getDefaultView() const

Get the default view of the render target.

The default view has the initial size of the render target, and never changes after the target has been created.

Returns

The default view of the render target

See also: setView, getView

public IntRect getViewport(const View & view) const

Get the viewport of a view, applied to this render target.

The viewport is defined in the view as a ratio, this function simply applies this ratio to the current dimensions of the render target to calculate the pixels rectangle that the viewport actually covers in the target.

Parameters

  • view The view for which we want to compute the viewport

Returns

Viewport rectangle, expressed in pixels

public Vector2f mapPixelToCoords(const Vector2i & point) const

Convert a point from target coordinates to world coordinates, using the current view.

This function is an overload of the mapPixelToCoords function that implicitly uses the current view. It is equivalent to:

target.mapPixelToCoords(point, target.getView());

Parameters

  • point Pixel to convert

Returns

The converted point, in "world" coordinates

See also: mapCoordsToPixel

public Vector2f mapPixelToCoords(const Vector2i& point,constView & view) const

Convert a point from target coordinates to world coordinates.

This function finds the 2D position that matches the given pixel of the render target. In other words, it does the inverse of what the graphics card does, to find the initial position of a rendered pixel.

Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (10, 50) in your render target may map to the point (150, 75) in your 2D world if the view is translated by (140, 25).

For render-windows, this function is typically used to find which point (or object) is located below the mouse cursor.

This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.

Parameters

  • point Pixel to convert

  • view The view to use for converting the point

Returns

The converted point, in "world" units

See also: mapCoordsToPixel

public Vector2i mapCoordsToPixel(const Vector2f & point) const

Convert a point from world coordinates to target coordinates, using the current view.

This function is an overload of the mapCoordsToPixel function that implicitly uses the current view. It is equivalent to:

target.mapCoordsToPixel(point, target.getView());

Parameters

  • point Point to convert

Returns

The converted point, in target coordinates (pixels)

See also: mapPixelToCoords

public Vector2i mapCoordsToPixel(const Vector2f& point,constView & view) const

Convert a point from world coordinates to target coordinates.

This function finds the pixel of the render target that matches the given 2D point. In other words, it goes through the same process as the graphics card, to compute the final position of a rendered point.

Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (150, 75) in your 2D world may map to the pixel (10, 50) of your render target if the view is translated by (140, 25).

This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.

Parameters

  • point Point to convert

  • view The view to use for converting the point

Returns

The converted point, in target coordinates (pixels)

See also: mapPixelToCoords

public void draw(const Drawable& drawable,constRenderStates & states)

Draw a drawable object to the render target.

Parameters

  • drawable Object to draw

  • states Render states to use for drawing

public void draw(const Vertex * vertices,std::size_t vertexCount,PrimitiveTypetype,constRenderStates & states)

Draw primitives defined by an array of vertices.

Parameters

  • vertices Pointer to the vertices

  • vertexCount Number of vertices in the array

  • type Type of primitives to draw

  • states Render states to use for drawing

public void draw(const VertexBuffer& vertexBuffer,constRenderStates & states)

Draw primitives defined by a vertex buffer.

Parameters

  • vertexBuffer Vertex buffer

  • states Render states to use for drawing

public void draw(const VertexBuffer& vertexBuffer,std::size_t firstVertex,std::size_t vertexCount,constRenderStates & states)

Draw primitives defined by a vertex buffer.

Parameters

  • vertexBuffer Vertex buffer

  • firstVertex Index of the first vertex to render

  • vertexCount Number of vertices to render

  • states Render states to use for drawing

public void pushGLStates()

Save the current OpenGL render states and matrices.

This function can be used when you mix SFML drawing and direct OpenGL rendering. Combined with popGLStates, it ensures that:

  • SFML's internal states are not messed up by your OpenGL code

  • your OpenGL states are not modified by a call to a SFML function

More specifically, it must be used around code that calls Draw functions. Example:

// OpenGL code here...
window.pushGLStates();
window.draw(...);
window.draw(...);
window.popGLStates();
// OpenGL code here...

Note that this function is quite expensive: it saves all the possible OpenGL states and matrices, even the ones you don't care about. Therefore it should be used wisely. It is provided for convenience, but the best results will be achieved if you handle OpenGL states yourself (because you know which states have really changed, and need to be saved and restored). Take a look at the resetGLStates function if you do so.

See also: popGLStates

public void popGLStates()

Restore the previously saved OpenGL render states and matrices.

See the description of pushGLStates to get a detailed description of these functions.

See also: pushGLStates

public void resetGLStates()

Reset the internal OpenGL states so that the target is ready for drawing.

This function can be used when you mix SFML drawing and direct OpenGL rendering, if you choose not to use pushGLStates/popGLStates. It makes sure that all OpenGL states needed by SFML are set, so that subsequent draw() calls will work as expected.

Example:

// OpenGL code here...
glPushAttrib(...);
window.resetGLStates();
window.draw(...);
window.draw(...);
glPopAttrib(...);
// OpenGL code here...

protected virtual void onCreate()

Function called after the window has been created.

This function is called so that derived classes can perform their own specific initialization as soon as the window is created.

protected virtual void onResize()

Function called after the window has been resized.

This function is called so that derived classes can perform custom actions when the size of the window changes.

protected void initialize()

Performs the common initialization step after creation.

The derived classes must call this function after the target is created and ready for drawing.

class sf::Shader

class sf::Shader
  : private sf::GlResource
  : private sf::NonCopyable

Shader class (vertex, geometry and fragment)

Shaders are programs written using a specific language, executed directly by the graphics card and allowing to apply real-time operations to the rendered entities.

There are three kinds of shaders:

  • Vertex shaders, that process vertices

  • Geometry shaders, that process primitives

  • Fragment (pixel) shaders, that process pixels

A sf::Shader can be composed of either a vertex shader alone, a geometry shader alone, a fragment shader alone, or any combination of them. (see the variants of the load functions).

Shaders are written in GLSL, which is a C-like language dedicated to OpenGL shaders. You'll probably need to learn its basics before writing your own shaders for SFML.

Like any C/C++ program, a GLSL shader has its own variables called uniforms that you can set from your C++ application. sf::Shader handles different types of uniforms:

  • scalars: float, int, bool

  • vectors (2, 3 or 4 components)

  • matrices (3x3 or 4x4)

  • samplers (textures)

Some SFML-specific types can be converted:

Every uniform variable in a shader can be set through one of the setUniform() or setUniformArray() overloads. For example, if you have a shader with the following uniforms:

uniform float offset;
uniform vec3 point;
uniform vec4 color;
uniform mat4 matrix;
uniform sampler2D overlay;
uniform sampler2D current;

You can set their values from C++ code as follows, using the types defined in the sf::Glsl namespace:

shader.setUniform("offset", 2.f);
shader.setUniform("point", sf::Vector3f(0.5f, 0.8f, 0.3f));
shader.setUniform("color", sf::Glsl::Vec4(color));          // color is a sf::Color
shader.setUniform("matrix", sf::Glsl::Mat4(transform));     // transform is a sf::Transform
shader.setUniform("overlay", texture);                      // texture is a sf::Texture
shader.setUniform("current", sf::Shader::CurrentTexture);

The old setParameter() overloads are deprecated and will be removed in a future version. You should use their setUniform() equivalents instead.

The special Shader::CurrentTexture argument maps the given sampler2D uniform to the current texture of the object being drawn (which cannot be known in advance).

To apply a shader to a drawable, you must pass it as an additional parameter to the Window::draw() draw() function:

window.draw(sprite, &shader);

... which is in fact just a shortcut for this:

sf::RenderStates states;
states.shader = &shader;
window.draw(sprite, states);

In the code above we pass a pointer to the shader, because it may be null (which means "no shader").

Shaders can be used on any drawable, but some combinations are not interesting. For example, using a vertex shader on a sf::Sprite is limited because there are only 4 vertices, the sprite would have to be subdivided in order to apply wave effects. Another bad example is a fragment shader with sf::Text: the texture of the text is not the actual text that you see on screen, it is a big texture containing all the characters of the font in an arbitrary order; thus, texture lookups on pixels other than the current one may not give you the expected result.

Shaders can also be used to apply global post-effects to the current contents of the target (like the old sf::PostFx class in SFML 1). This can be done in two different ways:

  • draw everything to a sf::RenderTexture, then draw it to the main target using the shader

  • draw everything directly to the main target, then use sf::Texture::update(Window&) to copy its contents to a texture and draw it to the main target using the shader

The first technique is more optimized because it doesn't involve retrieving the target's pixels to system memory, but the second one doesn't impact the rendering process and can be easily inserted anywhere without impacting all the code.

Like sf::Texture that can be used as a raw OpenGL texture, sf::Shader can also be used directly as a raw shader for custom OpenGL geometry.

sf::Shader::bind(&shader);
... render OpenGL geometry ...
sf::Shader::bind(NULL);

See also: sf::Glsl

Summary

Members Descriptions
public Shader() Default constructor.
public ~Shader() Destructor.
public bool loadFromFile(const std::string & filename,Type type) Load the vertex, geometry or fragment shader from a file.
public bool loadFromFile(const std::string & vertexShaderFilename,const std::string & fragmentShaderFilename) Load both the vertex and fragment shaders from files.
public bool loadFromFile(const std::string & vertexShaderFilename,const std::string & geometryShaderFilename,const std::string & fragmentShaderFilename) Load the vertex, geometry and fragment shaders from files.
public bool loadFromMemory(const std::string & shader,Type type) Load the vertex, geometry or fragment shader from a source code in memory.
public bool loadFromMemory(const std::string & vertexShader,const std::string & fragmentShader) Load both the vertex and fragment shaders from source codes in memory.
public bool loadFromMemory(const std::string & vertexShader,const std::string & geometryShader,const std::string & fragmentShader) Load the vertex, geometry and fragment shaders from source codes in memory.
public bool loadFromStream(InputStream & stream,Type type) Load the vertex, geometry or fragment shader from a custom stream.
public bool loadFromStream(InputStream & vertexShaderStream,InputStream & fragmentShaderStream) Load both the vertex and fragment shaders from custom streams.
public bool loadFromStream(InputStream & vertexShaderStream,InputStream & geometryShaderStream,InputStream & fragmentShaderStream) Load the vertex, geometry and fragment shaders from custom streams.
public void setUniform(const std::string & name,float x) Specify value for float uniform.
public void setUniform(const std::string & name,const Glsl::Vec2 & vector) Specify value for vec2 uniform.
public void setUniform(const std::string & name,const Glsl::Vec3 & vector) Specify value for vec3 uniform.
public void setUniform(const std::string & name,const Glsl::Vec4 & vector) Specify value for vec4 uniform.
public void setUniform(const std::string & name,int x) Specify value for int uniform.
public void setUniform(const std::string & name,const Glsl::Ivec2 & vector) Specify value for ivec2 uniform.
public void setUniform(const std::string & name,const Glsl::Ivec3 & vector) Specify value for ivec3 uniform.
public void setUniform(const std::string & name,const Glsl::Ivec4 & vector) Specify value for ivec4 uniform.
public void setUniform(const std::string & name,bool x) Specify value for bool uniform.
public void setUniform(const std::string & name,const Glsl::Bvec2 & vector) Specify value for bvec2 uniform.
public void setUniform(const std::string & name,const Glsl::Bvec3 & vector) Specify value for bvec3 uniform.
public void setUniform(const std::string & name,const Glsl::Bvec4 & vector) Specify value for bvec4 uniform.
public void setUniform(const std::string & name,const Glsl::Mat3 & matrix) Specify value for mat3 matrix.
public void setUniform(const std::string & name,const Glsl::Mat4 & matrix) Specify value for mat4 matrix.
public void setUniform(const std::string & name,const Texture & texture) Specify a texture as sampler2D uniform.
public void setUniform(const std::string & name,CurrentTextureType) Specify current texture as sampler2D uniform.
public void setUniformArray(const std::string & name,const float * scalarArray,std::size_t length) Specify values for float[] array uniform.
public void setUniformArray(const std::string & name,const Glsl::Vec2 * vectorArray,std::size_t length) Specify values for vec2[] array uniform.
public void setUniformArray(const std::string & name,const Glsl::Vec3 * vectorArray,std::size_t length) Specify values for vec3[] array uniform.
public void setUniformArray(const std::string & name,const Glsl::Vec4 * vectorArray,std::size_t length) Specify values for vec4[] array uniform.
public void setUniformArray(const std::string & name,const Glsl::Mat3 * matrixArray,std::size_t length) Specify values for mat3[] array uniform.
public void setUniformArray(const std::string & name,const Glsl::Mat4 * matrixArray,std::size_t length) Specify values for mat4[] array uniform.
public void setParameter(const std::string & name,float x) Change a float parameter of the shader.
public void setParameter(const std::string & name,float x,float y) Change a 2-components vector parameter of the shader.
public void setParameter(const std::string & name,float x,float y,float z) Change a 3-components vector parameter of the shader.
public void setParameter(const std::string & name,float x,float y,float z,float w) Change a 4-components vector parameter of the shader.
public void setParameter(const std::string & name,const Vector2f & vector) Change a 2-components vector parameter of the shader.
public void setParameter(const std::string & name,const Vector3f & vector) Change a 3-components vector parameter of the shader.
public void setParameter(const std::string & name,const Color & color) Change a color parameter of the shader.
public void setParameter(const std::string & name,const Transform & transform) Change a matrix parameter of the shader.
public void setParameter(const std::string & name,const Texture & texture) Change a texture parameter of the shader.
public void setParameter(const std::string & name,CurrentTextureType) Change a texture parameter of the shader.
public unsigned int getNativeHandle() const Get the underlying OpenGL handle of the shader.
enum Type Types of shaders.

Members

public Shader()

Default constructor.

This constructor creates an invalid shader.

public ~Shader()

Destructor.

public bool loadFromFile(const std::string & filename,Type type)

Load the vertex, geometry or fragment shader from a file.

This function loads a single shader, vertex, geometry or fragment, identified by the second argument. The source must be a text file containing a valid shader in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • filename Path of the vertex, geometry or fragment shader file to load

  • type Type of shader (vertex, geometry or fragment)

Returns

True if loading succeeded, false if it failed

See also: loadFromMemory, loadFromStream

public bool loadFromFile(const std::string & vertexShaderFilename,const std::string & fragmentShaderFilename)

Load both the vertex and fragment shaders from files.

This function loads both the vertex and the fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The sources must be text files containing valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • vertexShaderFilename Path of the vertex shader file to load

  • fragmentShaderFilename Path of the fragment shader file to load

Returns

True if loading succeeded, false if it failed

See also: loadFromMemory, loadFromStream

public bool loadFromFile(const std::string & vertexShaderFilename,const std::string & geometryShaderFilename,const std::string & fragmentShaderFilename)

Load the vertex, geometry and fragment shaders from files.

This function loads the vertex, geometry and fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The sources must be text files containing valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • vertexShaderFilename Path of the vertex shader file to load

  • geometryShaderFilename Path of the geometry shader file to load

  • fragmentShaderFilename Path of the fragment shader file to load

Returns

True if loading succeeded, false if it failed

See also: loadFromMemory, loadFromStream

public bool loadFromMemory(const std::string & shader,Type type)

Load the vertex, geometry or fragment shader from a source code in memory.

This function loads a single shader, vertex, geometry or fragment, identified by the second argument. The source code must be a valid shader in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • shader String containing the source code of the shader

  • type Type of shader (vertex, geometry or fragment)

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromStream

public bool loadFromMemory(const std::string & vertexShader,const std::string & fragmentShader)

Load both the vertex and fragment shaders from source codes in memory.

This function loads both the vertex and the fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The sources must be valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • vertexShader String containing the source code of the vertex shader

  • fragmentShader String containing the source code of the fragment shader

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromStream

public bool loadFromMemory(const std::string & vertexShader,const std::string & geometryShader,const std::string & fragmentShader)

Load the vertex, geometry and fragment shaders from source codes in memory.

This function loads the vertex, geometry and fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The sources must be valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • vertexShader String containing the source code of the vertex shader

  • geometryShader String containing the source code of the geometry shader

  • fragmentShader String containing the source code of the fragment shader

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromStream

public bool loadFromStream(InputStream & stream,Type type)

Load the vertex, geometry or fragment shader from a custom stream.

This function loads a single shader, vertex, geometry or fragment, identified by the second argument. The source code must be a valid shader in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • stream Source stream to read from

  • type Type of shader (vertex, geometry or fragment)

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromMemory

public bool loadFromStream(InputStream & vertexShaderStream,InputStream & fragmentShaderStream)

Load both the vertex and fragment shaders from custom streams.

This function loads both the vertex and the fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The source codes must be valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • vertexShaderStream Source stream to read the vertex shader from

  • fragmentShaderStream Source stream to read the fragment shader from

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromMemory

public bool loadFromStream(InputStream & vertexShaderStream,InputStream & geometryShaderStream,InputStream & fragmentShaderStream)

Load the vertex, geometry and fragment shaders from custom streams.

This function loads the vertex, geometry and fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The source codes must be valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.

Parameters

  • vertexShaderStream Source stream to read the vertex shader from

  • geometryShaderStream Source stream to read the geometry shader from

  • fragmentShaderStream Source stream to read the fragment shader from

Returns

True if loading succeeded, false if it failed

See also: loadFromFile, loadFromMemory

public void setUniform(const std::string & name,float x)

Specify value for float uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • x Value of the float scalar

public void setUniform(const std::string & name,const Glsl::Vec2 & vector)

Specify value for vec2 uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the vec2 vector

public void setUniform(const std::string & name,const Glsl::Vec3 & vector)

Specify value for vec3 uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the vec3 vector

public void setUniform(const std::string & name,const Glsl::Vec4 & vector)

Specify value for vec4 uniform.

This overload can also be called with sf::Color objects that are converted to sf::Glsl::Vec4.

It is important to note that the components of the color are normalized before being passed to the shader. Therefore, they are converted from range [0 .. 255] to range [0 .. 1]. For example, a sf::Color(255, 127, 0, 255) will be transformed to a vec4(1.0, 0.5, 0.0, 1.0) in the shader.

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the vec4 vector

public void setUniform(const std::string & name,int x)

Specify value for int uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • x Value of the int scalar

public void setUniform(const std::string & name,const Glsl::Ivec2 & vector)

Specify value for ivec2 uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the ivec2 vector

public void setUniform(const std::string & name,const Glsl::Ivec3 & vector)

Specify value for ivec3 uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the ivec3 vector

public void setUniform(const std::string & name,const Glsl::Ivec4 & vector)

Specify value for ivec4 uniform.

This overload can also be called with sf::Color objects that are converted to sf::Glsl::Ivec4.

If color conversions are used, the ivec4 uniform in GLSL will hold the same values as the original sf::Color instance. For example, sf::Color(255, 127, 0, 255) is mapped to ivec4(255, 127, 0, 255).

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the ivec4 vector

public void setUniform(const std::string & name,bool x)

Specify value for bool uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • x Value of the bool scalar

public void setUniform(const std::string & name,const Glsl::Bvec2 & vector)

Specify value for bvec2 uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the bvec2 vector

public void setUniform(const std::string & name,const Glsl::Bvec3 & vector)

Specify value for bvec3 uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the bvec3 vector

public void setUniform(const std::string & name,const Glsl::Bvec4 & vector)

Specify value for bvec4 uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vector Value of the bvec4 vector

public void setUniform(const std::string & name,const Glsl::Mat3 & matrix)

Specify value for mat3 matrix.

Parameters

  • name Name of the uniform variable in GLSL

  • matrix Value of the mat3 matrix

public void setUniform(const std::string & name,const Glsl::Mat4 & matrix)

Specify value for mat4 matrix.

Parameters

  • name Name of the uniform variable in GLSL

  • matrix Value of the mat4 matrix

public void setUniform(const std::string & name,const Texture & texture)

Specify a texture as sampler2D uniform.

name is the name of the variable to change in the shader. The corresponding parameter in the shader must be a 2D texture (sampler2D GLSL type).

Example:

uniform sampler2D the_texture; // this is the variable in the shader
sf::Texture texture;
...
shader.setUniform("the_texture", texture);

It is important to note that texture must remain alive as long as the shader uses it, no copy is made internally.

To use the texture of the object being drawn, which cannot be known in advance, you can pass the special value sf::Shader::CurrentTexture:

shader.setUniform("the_texture", sf::Shader::CurrentTexture).

Parameters

  • name Name of the texture in the shader

  • texture Texture to assign

public void setUniform(const std::string & name,CurrentTextureType)

Specify current texture as sampler2D uniform.

This overload maps a shader texture variable to the texture of the object being drawn, which cannot be known in advance. The second argument must be sf::Shader::CurrentTexture. The corresponding parameter in the shader must be a 2D texture (sampler2D GLSL type).

Example:

uniform sampler2D current; // this is the variable in the shader
shader.setUniform("current", sf::Shader::CurrentTexture);

Parameters

  • name Name of the texture in the shader

public void setUniformArray(const std::string & name,const float * scalarArray,std::size_t length)

Specify values for float[] array uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • scalarArray pointer to array of float values

  • length Number of elements in the array

public void setUniformArray(const std::string & name,const Glsl::Vec2 * vectorArray,std::size_t length)

Specify values for vec2[] array uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vectorArray pointer to array of vec2 values

  • length Number of elements in the array

public void setUniformArray(const std::string & name,const Glsl::Vec3 * vectorArray,std::size_t length)

Specify values for vec3[] array uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vectorArray pointer to array of vec3 values

  • length Number of elements in the array

public void setUniformArray(const std::string & name,const Glsl::Vec4 * vectorArray,std::size_t length)

Specify values for vec4[] array uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • vectorArray pointer to array of vec4 values

  • length Number of elements in the array

public void setUniformArray(const std::string & name,const Glsl::Mat3 * matrixArray,std::size_t length)

Specify values for mat3[] array uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • matrixArray pointer to array of mat3 values

  • length Number of elements in the array

public void setUniformArray(const std::string & name,const Glsl::Mat4 * matrixArray,std::size_t length)

Specify values for mat4[] array uniform.

Parameters

  • name Name of the uniform variable in GLSL

  • matrixArray pointer to array of mat4 values

  • length Number of elements in the array

public void setParameter(const std::string & name,float x)

Change a float parameter of the shader.

Deprecated: Use setUniform(const std::string&, float) instead.

public void setParameter(const std::string & name,float x,float y)

Change a 2-components vector parameter of the shader.

Deprecated: Use setUniform(const std::string&, const Glsl::Vec2&) instead.

public void setParameter(const std::string & name,float x,float y,float z)

Change a 3-components vector parameter of the shader.

Deprecated: Use setUniform(const std::string&, const Glsl::Vec3&) instead.

public void setParameter(const std::string & name,float x,float y,float z,float w)

Change a 4-components vector parameter of the shader.

Deprecated: Use setUniform(const std::string&, const Glsl::Vec4&) instead.

public void setParameter(const std::string & name,const Vector2f & vector)

Change a 2-components vector parameter of the shader.

Deprecated: Use setUniform(const std::string&, const Glsl::Vec2&) instead.

public void setParameter(const std::string & name,const Vector3f & vector)

Change a 3-components vector parameter of the shader.

Deprecated: Use setUniform(const std::string&, const Glsl::Vec3&) instead.

public void setParameter(const std::string & name,const Color & color)

Change a color parameter of the shader.

Deprecated: Use setUniform(const std::string&, const Glsl::Vec4&) instead.

public void setParameter(const std::string & name,const Transform & transform)

Change a matrix parameter of the shader.

Deprecated: Use setUniform(const std::string&, const Glsl::Mat4&) instead.

public void setParameter(const std::string & name,const Texture & texture)

Change a texture parameter of the shader.

Deprecated: Use setUniform(const std::string&, const Texture&) instead.

public void setParameter(const std::string & name,CurrentTextureType)

Change a texture parameter of the shader.

Deprecated: Use setUniform(const std::string&, CurrentTextureType) instead.

public unsigned int getNativeHandle() const

Get the underlying OpenGL handle of the shader.

You shouldn't need to use this function, unless you have very specific stuff to implement that SFML doesn't support, or implement a temporary workaround until a bug is fixed.

Returns

OpenGL handle of the shader or 0 if not yet loaded

enum Type

Values Descriptions
Vertex Vertex shader
Geometry Geometry shader.
Fragment Fragment (pixel) shader.

Types of shaders.

class sf::Shape

class sf::Shape
  : public sf::Drawable
  : public sf::Transformable

Base class for textured shapes with outline.

sf::Shape is a drawable class that allows to define and display a custom convex shape on a render target.

It's only an abstract base, it needs to be specialized for concrete types of shapes (circle, rectangle, convex polygon, star, ...).

In addition to the attributes provided by the specialized shape classes, a shape always has the following attributes:

  • a texture

  • a texture rectangle

  • a fill color

  • an outline color

  • an outline thickness

Each feature is optional, and can be disabled easily:

  • the texture can be null

  • the fill/outline colors can be sf::Color::Transparent

  • the outline thickness can be zero

You can write your own derived shape class, there are only two virtual functions to override:

  • getPointCount must return the number of points of the shape

  • getPoint must return the points of the shape

See also: sf::RectangleShape, sf::CircleShape, sf::ConvexShape, sf::Transformable

Summary

Members Descriptions
public virtual ~Shape() Virtual destructor.
public void setTexture(const Texture * texture,bool resetRect) Change the source texture of the shape.
public void setTextureRect(const IntRect & rect) Set the sub-rectangle of the texture that the shape will display.
public void setFillColor(const Color & color) Set the fill color of the shape.
public void setOutlineColor(const Color & color) Set the outline color of the shape.
public void setOutlineThickness(float thickness) Set the thickness of the shape's outline.
public const Texture*getTexture() const Get the source texture of the shape.
public const IntRect&getTextureRect() const Get the sub-rectangle of the texture displayed by the shape.
public const Color&getFillColor() const Get the fill color of the shape.
public const Color&getOutlineColor() const Get the outline color of the shape.
public float getOutlineThickness() const Get the outline thickness of the shape.
public std::size_t getPointCount() const Get the total number of points of the shape.
public Vector2f getPoint(std::size_t index) const Get a point of the shape.
public FloatRect getLocalBounds() const Get the local bounding rectangle of the entity.
public FloatRect getGlobalBounds() const Get the global (non-minimal) bounding rectangle of the entity.
public void setPosition(float x,float y) set the position of the object
public void setPosition(const Vector2f & position) set the position of the object
public void setRotation(float angle) set the orientation of the object
public void setScale(float factorX,float factorY) set the scale factors of the object
public void setScale(const Vector2f & factors) set the scale factors of the object
public void setOrigin(float x,float y) set the local origin of the object
public void setOrigin(const Vector2f & origin) set the local origin of the object
public const Vector2f&getPosition() const get the position of the object
public float getRotation() const get the orientation of the object
public const Vector2f&getScale() const get the current scale of the object
public const Vector2f&getOrigin() const get the local origin of the object
public void move(float offsetX,float offsetY) Move the object by a given offset.
public void move(const Vector2f & offset) Move the object by a given offset.
public void rotate(float angle) Rotate the object.
public void scale(float factorX,float factorY) Scale the object.
public void scale(const Vector2f & factor) Scale the object.
public const Transform&getTransform() const get the combined transform of the object
public const Transform&getInverseTransform() const get the inverse of the combined transform of the object
protected Shape() Default constructor.
protected void update() Recompute the internal geometry of the shape.

Members

public virtual ~Shape()

Virtual destructor.

public void setTexture(const Texture * texture,bool resetRect)

Change the source texture of the shape.

The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behavior is undefined. texture can be NULL to disable texturing. If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.

Parameters

  • texture New texture

  • resetRect Should the texture rect be reset to the size of the new texture?

See also: getTexture, setTextureRect

public void setTextureRect(const IntRect & rect)

Set the sub-rectangle of the texture that the shape will display.

The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.

Parameters

  • rect Rectangle defining the region of the texture to display

See also: getTextureRect, setTexture

public void setFillColor(const Color & color)

Set the fill color of the shape.

This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use sf::Color::Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.

Parameters

  • color New color of the shape

See also: getFillColor, setOutlineColor

public void setOutlineColor(const Color & color)

Set the outline color of the shape.

By default, the shape's outline color is opaque white.

Parameters

  • color New outline color of the shape

See also: getOutlineColor, setFillColor

public void setOutlineThickness(float thickness)

Set the thickness of the shape's outline.

Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.

Parameters

  • thickness New outline thickness

See also: getOutlineThickness

public const Texture*getTexture() const

Get the source texture of the shape.

If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.

Returns

Pointer to the shape's texture

See also: setTexture

public const IntRect&getTextureRect() const

Get the sub-rectangle of the texture displayed by the shape.

Returns

Texture rectangle of the shape

See also: setTextureRect

public const Color&getFillColor() const

Get the fill color of the shape.

Returns

Fill color of the shape

See also: setFillColor

public const Color&getOutlineColor() const

Get the outline color of the shape.

Returns

Outline color of the shape

See also: setOutlineColor

public float getOutlineThickness() const

Get the outline thickness of the shape.

Returns

Outline thickness of the shape

See also: setOutlineThickness

public std::size_t getPointCount() const

Get the total number of points of the shape.

Returns

Number of points of the shape

See also: getPoint

public Vector2f getPoint(std::size_t index) const

Get a point of the shape.

The returned point is in local coordinates, that is, the shape's transforms (position, rotation, scale) are not taken into account. The result is undefined if index is out of the valid range.

Parameters

Returns

index-th point of the shape

See also: getPointCount

public FloatRect getLocalBounds() const

Get the local bounding rectangle of the entity.

The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.

Returns

Local bounding rectangle of the entity

public FloatRect getGlobalBounds() const

Get the global (non-minimal) bounding rectangle of the entity.

The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the shape in the global 2D world's coordinate system.

This function does not necessarily return the minimal bounding rectangle. It merely ensures that the returned rectangle covers all the vertices (but possibly more). This allows for a fast approximation of the bounds as a first check; you may want to use more precise checks on top of that.

Returns

Global bounding rectangle of the entity

public void setPosition(float x,float y)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new position

  • y Y coordinate of the new position

See also: move, getPosition

public void setPosition(const Vector2f & position)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • position New position

See also: move, getPosition

public void setRotation(float angle)

set the orientation of the object

This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.

Parameters

  • angle New rotation, in degrees

See also: rotate, getRotation

public void setScale(float factorX,float factorY)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factorX New horizontal scale factor

  • factorY New vertical scale factor

See also: scale, getScale

public void setScale(const Vector2f & factors)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factors New scale factors

See also: scale, getScale

public void setOrigin(float x,float y)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new origin

  • y Y coordinate of the new origin

See also: getOrigin

public void setOrigin(const Vector2f & origin)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • origin New origin

See also: getOrigin

public const Vector2f&getPosition() const

get the position of the object

Returns

Current position

See also: setPosition

public float getRotation() const

get the orientation of the object

The rotation is always in the range [0, 360].

Returns

Current rotation, in degrees

See also: setRotation

public const Vector2f&getScale() const

get the current scale of the object

Returns

Current scale factors

See also: setScale

public const Vector2f&getOrigin() const

get the local origin of the object

Returns

Current origin

See also: setOrigin

public void move(float offsetX,float offsetY)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f pos = object.getPosition();
object.setPosition(pos.x + offsetX, pos.y + offsetY);

Parameters

  • offsetX X offset

  • offsetY Y offset

See also: setPosition

public void move(const Vector2f & offset)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

object.setPosition(object.getPosition() + offset);

Parameters

  • offset Offset

See also: setPosition

public void rotate(float angle)

Rotate the object.

This function adds to the current rotation of the object, unlike setRotation which overwrites it. Thus, it is equivalent to the following code:

object.setRotation(object.getRotation() + angle);

Parameters

  • angle Angle of rotation, in degrees

public void scale(float factorX,float factorY)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factorX, scale.y * factorY);

Parameters

  • factorX Horizontal scale factor

  • factorY Vertical scale factor

See also: setScale

public void scale(const Vector2f & factor)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factor.x, scale.y * factor.y);

Parameters

  • factor Scale factors

See also: setScale

public const Transform&getTransform() const

get the combined transform of the object

Returns

Transform combining the position/rotation/scale/origin of the object

See also: getInverseTransform

public const Transform&getInverseTransform() const

get the inverse of the combined transform of the object

Returns

Inverse of the combined transformations applied to the object

See also: getTransform

protected Shape()

Default constructor.

protected void update()

Recompute the internal geometry of the shape.

This function must be called by the derived class everytime the shape's points change (i.e. the result of either getPointCount or getPoint is different).

class sf::Sprite

class sf::Sprite
  : public sf::Drawable
  : public sf::Transformable

Drawable representation of a texture, with its own transformations, color, etc.

sf::Sprite is a drawable class that allows to easily display a texture (or a part of it) on a render target.

It inherits all the functions from sf::Transformable: position, rotation, scale, origin. It also adds sprite-specific properties such as the texture to use, the part of it to display, and some convenience functions to change the overall color of the sprite, or to get its bounding rectangle.

sf::Sprite works in combination with the sf::Texture class, which loads and provides the pixel data of a given texture.

The separation of sf::Sprite and sf::Texture allows more flexibility and better performances: indeed a sf::Texture is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Sprite is a lightweight object which can use the pixel data of a sf::Texture and draw it with its own transformation/color/blending attributes.

It is important to note that the sf::Sprite instance doesn't copy the texture that it uses, it only keeps a reference to it. Thus, a sf::Texture must not be destroyed while it is used by a sf::Sprite (i.e. never write a function that uses a local sf::Texture instance for creating a sprite).

See also the note on coordinates and undistorted rendering in sf::Transformable.

Usage example:

// Declare and load a texture
sf::Texture texture;
texture.loadFromFile("texture.png");

// Create a sprite
sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setTextureRect(sf::IntRect(10, 10, 50, 30));
sprite.setColor(sf::Color(255, 255, 255, 200));
sprite.setPosition(100, 25);

// Draw it
window.draw(sprite);

See also: sf::Texture, sf::Transformable

Summary

Members Descriptions
public Sprite() Default constructor.
public explicit Sprite(const Texture & texture) Construct the sprite from a source texture.
public Sprite(const Texture& texture,constIntRect & rectangle) Construct the sprite from a sub-rectangle of a source texture.
public void setTexture(const Texture & texture,bool resetRect) Change the source texture of the sprite.
public void setTextureRect(const IntRect & rectangle) Set the sub-rectangle of the texture that the sprite will display.
public void setColor(const Color & color) Set the global color of the sprite.
public const Texture*getTexture() const Get the source texture of the sprite.
public const IntRect&getTextureRect() const Get the sub-rectangle of the texture displayed by the sprite.
public const Color&getColor() const Get the global color of the sprite.
public FloatRect getLocalBounds() const Get the local bounding rectangle of the entity.
public FloatRect getGlobalBounds() const Get the global bounding rectangle of the entity.
public void setPosition(float x,float y) set the position of the object
public void setPosition(const Vector2f & position) set the position of the object
public void setRotation(float angle) set the orientation of the object
public void setScale(float factorX,float factorY) set the scale factors of the object
public void setScale(const Vector2f & factors) set the scale factors of the object
public void setOrigin(float x,float y) set the local origin of the object
public void setOrigin(const Vector2f & origin) set the local origin of the object
public const Vector2f&getPosition() const get the position of the object
public float getRotation() const get the orientation of the object
public const Vector2f&getScale() const get the current scale of the object
public const Vector2f&getOrigin() const get the local origin of the object
public void move(float offsetX,float offsetY) Move the object by a given offset.
public void move(const Vector2f & offset) Move the object by a given offset.
public void rotate(float angle) Rotate the object.
public void scale(float factorX,float factorY) Scale the object.
public void scale(const Vector2f & factor) Scale the object.
public const Transform&getTransform() const get the combined transform of the object
public const Transform&getInverseTransform() const get the inverse of the combined transform of the object

Members

public Sprite()

Default constructor.

Creates an empty sprite with no source texture.

public explicit Sprite(const Texture & texture)

Construct the sprite from a source texture.

Parameters

  • texture Source texture

See also: setTexture

public Sprite(const Texture& texture,constIntRect & rectangle)

Construct the sprite from a sub-rectangle of a source texture.

Parameters

  • texture Source texture

  • rectangle Sub-rectangle of the texture to assign to the sprite

See also: setTexture, setTextureRect

public void setTexture(const Texture & texture,bool resetRect)

Change the source texture of the sprite.

The texture argument refers to a texture that must exist as long as the sprite uses it. Indeed, the sprite doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the sprite tries to use it, the behavior is undefined. If resetRect is true, the TextureRect property of the sprite is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.

Parameters

  • texture New texture

  • resetRect Should the texture rect be reset to the size of the new texture?

See also: getTexture, setTextureRect

public void setTextureRect(const IntRect & rectangle)

Set the sub-rectangle of the texture that the sprite will display.

The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.

Parameters

  • rectangle Rectangle defining the region of the texture to display

See also: getTextureRect, setTexture

public void setColor(const Color & color)

Set the global color of the sprite.

This color is modulated (multiplied) with the sprite's texture. It can be used to colorize the sprite, or change its global opacity. By default, the sprite's color is opaque white.

Parameters

  • color New color of the sprite

See also: getColor

public const Texture*getTexture() const

Get the source texture of the sprite.

If the sprite has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.

Returns

Pointer to the sprite's texture

See also: setTexture

public const IntRect&getTextureRect() const

Get the sub-rectangle of the texture displayed by the sprite.

Returns

Texture rectangle of the sprite

See also: setTextureRect

public const Color&getColor() const

Get the global color of the sprite.

Returns

Global color of the sprite

See also: setColor

public FloatRect getLocalBounds() const

Get the local bounding rectangle of the entity.

The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.

Returns

Local bounding rectangle of the entity

public FloatRect getGlobalBounds() const

Get the global bounding rectangle of the entity.

The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the sprite in the global 2D world's coordinate system.

Returns

Global bounding rectangle of the entity

public void setPosition(float x,float y)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new position

  • y Y coordinate of the new position

See also: move, getPosition

public void setPosition(const Vector2f & position)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • position New position

See also: move, getPosition

public void setRotation(float angle)

set the orientation of the object

This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.

Parameters

  • angle New rotation, in degrees

See also: rotate, getRotation

public void setScale(float factorX,float factorY)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factorX New horizontal scale factor

  • factorY New vertical scale factor

See also: scale, getScale

public void setScale(const Vector2f & factors)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factors New scale factors

See also: scale, getScale

public void setOrigin(float x,float y)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new origin

  • y Y coordinate of the new origin

See also: getOrigin

public void setOrigin(const Vector2f & origin)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • origin New origin

See also: getOrigin

public const Vector2f&getPosition() const

get the position of the object

Returns

Current position

See also: setPosition

public float getRotation() const

get the orientation of the object

The rotation is always in the range [0, 360].

Returns

Current rotation, in degrees

See also: setRotation

public const Vector2f&getScale() const

get the current scale of the object

Returns

Current scale factors

See also: setScale

public const Vector2f&getOrigin() const

get the local origin of the object

Returns

Current origin

See also: setOrigin

public void move(float offsetX,float offsetY)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f pos = object.getPosition();
object.setPosition(pos.x + offsetX, pos.y + offsetY);

Parameters

  • offsetX X offset

  • offsetY Y offset

See also: setPosition

public void move(const Vector2f & offset)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

object.setPosition(object.getPosition() + offset);

Parameters

  • offset Offset

See also: setPosition

public void rotate(float angle)

Rotate the object.

This function adds to the current rotation of the object, unlike setRotation which overwrites it. Thus, it is equivalent to the following code:

object.setRotation(object.getRotation() + angle);

Parameters

  • angle Angle of rotation, in degrees

public void scale(float factorX,float factorY)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factorX, scale.y * factorY);

Parameters

  • factorX Horizontal scale factor

  • factorY Vertical scale factor

See also: setScale

public void scale(const Vector2f & factor)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factor.x, scale.y * factor.y);

Parameters

  • factor Scale factors

See also: setScale

public const Transform&getTransform() const

get the combined transform of the object

Returns

Transform combining the position/rotation/scale/origin of the object

See also: getInverseTransform

public const Transform&getInverseTransform() const

get the inverse of the combined transform of the object

Returns

Inverse of the combined transformations applied to the object

See also: getTransform

class sf::Text

class sf::Text
  : public sf::Drawable
  : public sf::Transformable

Graphical text that can be drawn to a render target.

sf::Text is a drawable class that allows to easily display some text with custom style and color on a render target.

It inherits all the functions from sf::Transformable: position, rotation, scale, origin. It also adds text-specific properties such as the font to use, the character size, the font style (bold, italic, underlined and strike through), the text color, the outline thickness, the outline color, the character spacing, the line spacing and the text to display of course. It also provides convenience functions to calculate the graphical size of the text, or to get the global position of a given character.

sf::Text works in combination with the sf::Font class, which loads and provides the glyphs (visual characters) of a given font.

The separation of sf::Font and sf::Text allows more flexibility and better performances: indeed a sf::Font is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Text is a lightweight object which can combine the glyphs data and metrics of a sf::Font to display any text on a render target.

It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text).

See also the note on coordinates and undistorted rendering in sf::Transformable.

Usage example:

// Declare and load a font
sf::Font font;
font.loadFromFile("arial.ttf");

// Create a text
sf::Text text("hello", font);
text.setCharacterSize(30);
text.setStyle(sf::Text::Bold);
text.setFillColor(sf::Color::Red);

// Draw it
window.draw(text);

See also: sf::Font, sf::Transformable

Summary

Members Descriptions
public Text() Default constructor.
public Text(const String& string,constFont & font,unsigned int characterSize) Construct the text from a string, font and size.
public void setString(const String & string) Set the text's string.
public void setFont(const Font & font) Set the text's font.
public void setCharacterSize(unsigned int size) Set the character size.
public void setLineSpacing(float spacingFactor) Set the line spacing factor.
public void setLetterSpacing(float spacingFactor) Set the letter spacing factor.
public void setStyle(Uint32 style) Set the text's style.
public void setColor(const Color & color) Set the fill color of the text.
public void setFillColor(const Color & color) Set the fill color of the text.
public void setOutlineColor(const Color & color) Set the outline color of the text.
public void setOutlineThickness(float thickness) Set the thickness of the text's outline.
public const String&getString() const Get the text's string.
public const Font*getFont() const Get the text's font.
public unsigned int getCharacterSize() const Get the character size.
public float getLetterSpacing() const Get the size of the letter spacing factor.
public float getLineSpacing() const Get the size of the line spacing factor.
public Uint32 getStyle() const Get the text's style.
public const Color&getColor() const Get the fill color of the text.
public const Color&getFillColor() const Get the fill color of the text.
public const Color&getOutlineColor() const Get the outline color of the text.
public float getOutlineThickness() const Get the outline thickness of the text.
public Vector2f findCharacterPos(std::size_t index) const Return the position of the index-th character.
public FloatRect getLocalBounds() const Get the local bounding rectangle of the entity.
public FloatRect getGlobalBounds() const Get the global bounding rectangle of the entity.
public void setPosition(float x,float y) set the position of the object
public void setPosition(const Vector2f & position) set the position of the object
public void setRotation(float angle) set the orientation of the object
public void setScale(float factorX,float factorY) set the scale factors of the object
public void setScale(const Vector2f & factors) set the scale factors of the object
public void setOrigin(float x,float y) set the local origin of the object
public void setOrigin(const Vector2f & origin) set the local origin of the object
public const Vector2f&getPosition() const get the position of the object
public float getRotation() const get the orientation of the object
public const Vector2f&getScale() const get the current scale of the object
public const Vector2f&getOrigin() const get the local origin of the object
public void move(float offsetX,float offsetY) Move the object by a given offset.
public void move(const Vector2f & offset) Move the object by a given offset.
public void rotate(float angle) Rotate the object.
public void scale(float factorX,float factorY) Scale the object.
public void scale(const Vector2f & factor) Scale the object.
public const Transform&getTransform() const get the combined transform of the object
public const Transform&getInverseTransform() const get the inverse of the combined transform of the object
enum Style Enumeration of the string drawing styles.

Members

public Text()

Default constructor.

Creates an empty text.

public Text(const String& string,constFont & font,unsigned int characterSize)

Construct the text from a string, font and size.

Note that if the used font is a bitmap font, it is not scalable, thus not all requested sizes will be available to use. This needs to be taken into consideration when setting the character size. If you need to display text of a certain size, make sure the corresponding bitmap font that supports that size is used.

Parameters

  • string Text assigned to the string

  • font Font used to draw the string

  • characterSize Base size of characters, in pixels

public void setString(const String & string)

Set the text's string.

The string argument is a sf::String, which can automatically be constructed from standard string types. So, the following calls are all valid:

text.setString("hello");
text.setString(L"hello");
text.setString(std::string("hello"));
text.setString(std::wstring(L"hello"));

A text's string is empty by default.

Parameters

  • string New string

See also: getString

public void setFont(const Font & font)

Set the text's font.

The font argument refers to a font that must exist as long as the text uses it. Indeed, the text doesn't store its own copy of the font, but rather keeps a pointer to the one that you passed to this function. If the font is destroyed and the text tries to use it, the behavior is undefined.

Parameters

  • font New font

See also: getFont

public void setCharacterSize(unsigned int size)

Set the character size.

The default size is 30.

Note that if the used font is a bitmap font, it is not scalable, thus not all requested sizes will be available to use. This needs to be taken into consideration when setting the character size. If you need to display text of a certain size, make sure the corresponding bitmap font that supports that size is used.

Parameters

  • size New character size, in pixels

See also: getCharacterSize

public void setLineSpacing(float spacingFactor)

Set the line spacing factor.

The default spacing between lines is defined by the font. This method enables you to set a factor for the spacing between lines. By default the line spacing factor is 1.

Parameters

  • spacingFactor New line spacing factor

See also: getLineSpacing

public void setLetterSpacing(float spacingFactor)

Set the letter spacing factor.

The default spacing between letters is defined by the font. This factor doesn't directly apply to the existing spacing between each character, it rather adds a fixed space between them which is calculated from the font metrics and the character size. Note that factors below 1 (including negative numbers) bring characters closer to each other. By default the letter spacing factor is 1.

Parameters

  • spacingFactor New letter spacing factor

See also: getLetterSpacing

public void setStyle(Uint32 style)

Set the text's style.

You can pass a combination of one or more styles, for example sf::Text::Bold | sf::Text::Italic. The default style is sf::Text::Regular.

Parameters

  • style New style

See also: getStyle

public void setColor(const Color & color)

Set the fill color of the text.

By default, the text's fill color is opaque white. Setting the fill color to a transparent color with an outline will cause the outline to be displayed in the fill area of the text.

Parameters

  • color New fill color of the text

See also: getFillColor

Deprecated: There is now fill and outline colors instead of a single global color. Use setFillColor() or setOutlineColor() instead.

public void setFillColor(const Color & color)

Set the fill color of the text.

By default, the text's fill color is opaque white. Setting the fill color to a transparent color with an outline will cause the outline to be displayed in the fill area of the text.

Parameters

  • color New fill color of the text

See also: getFillColor

public void setOutlineColor(const Color & color)

Set the outline color of the text.

By default, the text's outline color is opaque black.

Parameters

  • color New outline color of the text

See also: getOutlineColor

public void setOutlineThickness(float thickness)

Set the thickness of the text's outline.

By default, the outline thickness is 0.

Be aware that using a negative value for the outline thickness will cause distorted rendering.

Parameters

  • thickness New outline thickness, in pixels

See also: getOutlineThickness

public const String&getString() const

Get the text's string.

The returned string is a sf::String, which can automatically be converted to standard string types. So, the following lines of code are all valid:

sf::String   s1 = text.getString();
std::string  s2 = text.getString();
std::wstring s3 = text.getString();

Returns

Text's string

See also: setString

public const Font*getFont() const

Get the text's font.

If the text has no font attached, a NULL pointer is returned. The returned pointer is const, which means that you cannot modify the font when you get it from this function.

Returns

Pointer to the text's font

See also: setFont

public unsigned int getCharacterSize() const

Get the character size.

Returns

Size of the characters, in pixels

See also: setCharacterSize

public float getLetterSpacing() const

Get the size of the letter spacing factor.

Returns

Size of the letter spacing factor

See also: setLetterSpacing

public float getLineSpacing() const

Get the size of the line spacing factor.

Returns

Size of the line spacing factor

See also: setLineSpacing

public Uint32 getStyle() const

Get the text's style.

Returns

Text's style

See also: setStyle

public const Color&getColor() const

Get the fill color of the text.

Returns

Fill color of the text

See also: setFillColor

Deprecated: There is now fill and outline colors instead of a single global color. Use getFillColor() or getOutlineColor() instead.

public const Color&getFillColor() const

Get the fill color of the text.

Returns

Fill color of the text

See also: setFillColor

public const Color&getOutlineColor() const

Get the outline color of the text.

Returns

Outline color of the text

See also: setOutlineColor

public float getOutlineThickness() const

Get the outline thickness of the text.

Returns

Outline thickness of the text, in pixels

See also: setOutlineThickness

public Vector2f findCharacterPos(std::size_t index) const

Return the position of the index-th character.

This function computes the visual position of a character from its index in the string. The returned position is in global coordinates (translation, rotation, scale and origin are applied). If index is out of range, the position of the end of the string is returned.

Parameters

  • index Index of the character

Returns

Position of the character

public FloatRect getLocalBounds() const

Get the local bounding rectangle of the entity.

The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.

Returns

Local bounding rectangle of the entity

public FloatRect getGlobalBounds() const

Get the global bounding rectangle of the entity.

The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the text in the global 2D world's coordinate system.

Returns

Global bounding rectangle of the entity

public void setPosition(float x,float y)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new position

  • y Y coordinate of the new position

See also: move, getPosition

public void setPosition(const Vector2f & position)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • position New position

See also: move, getPosition

public void setRotation(float angle)

set the orientation of the object

This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.

Parameters

  • angle New rotation, in degrees

See also: rotate, getRotation

public void setScale(float factorX,float factorY)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factorX New horizontal scale factor

  • factorY New vertical scale factor

See also: scale, getScale

public void setScale(const Vector2f & factors)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factors New scale factors

See also: scale, getScale

public void setOrigin(float x,float y)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new origin

  • y Y coordinate of the new origin

See also: getOrigin

public void setOrigin(const Vector2f & origin)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • origin New origin

See also: getOrigin

public const Vector2f&getPosition() const

get the position of the object

Returns

Current position

See also: setPosition

public float getRotation() const

get the orientation of the object

The rotation is always in the range [0, 360].

Returns

Current rotation, in degrees

See also: setRotation

public const Vector2f&getScale() const

get the current scale of the object

Returns

Current scale factors

See also: setScale

public const Vector2f&getOrigin() const

get the local origin of the object

Returns

Current origin

See also: setOrigin

public void move(float offsetX,float offsetY)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f pos = object.getPosition();
object.setPosition(pos.x + offsetX, pos.y + offsetY);

Parameters

  • offsetX X offset

  • offsetY Y offset

See also: setPosition

public void move(const Vector2f & offset)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

object.setPosition(object.getPosition() + offset);

Parameters

  • offset Offset

See also: setPosition

public void rotate(float angle)

Rotate the object.

This function adds to the current rotation of the object, unlike setRotation which overwrites it. Thus, it is equivalent to the following code:

object.setRotation(object.getRotation() + angle);

Parameters

  • angle Angle of rotation, in degrees

public void scale(float factorX,float factorY)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factorX, scale.y * factorY);

Parameters

  • factorX Horizontal scale factor

  • factorY Vertical scale factor

See also: setScale

public void scale(const Vector2f & factor)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factor.x, scale.y * factor.y);

Parameters

  • factor Scale factors

See also: setScale

public const Transform&getTransform() const

get the combined transform of the object

Returns

Transform combining the position/rotation/scale/origin of the object

See also: getInverseTransform

public const Transform&getInverseTransform() const

get the inverse of the combined transform of the object

Returns

Inverse of the combined transformations applied to the object

See also: getTransform

enum Style

Values Descriptions
Regular Regular characters, no style.
Bold Bold characters.
Italic Italic characters.
Underlined Underlined characters.
StrikeThrough Strike through characters.

Enumeration of the string drawing styles.

class sf::Texture

class sf::Texture
  : private sf::GlResource

Image living on the graphics card that can be used for drawing.

sf::Texture stores pixels that can be drawn, with a sprite for example.

A texture lives in the graphics card memory, therefore it is very fast to draw a texture to a render target, or copy a render target to a texture (the graphics card can access both directly).

Being stored in the graphics card memory has some drawbacks. A texture cannot be manipulated as freely as a sf::Image, you need to prepare the pixels first and then upload them to the texture in a single operation (see Texture::update).

sf::Texture makes it easy to convert from/to sf::Image, but keep in mind that these calls require transfers between the graphics card and the central memory, therefore they are slow operations.

A texture can be loaded from an image, but also directly from a file/memory/stream. The necessary shortcuts are defined so that you don't need an image first for the most common cases. However, if you want to perform some modifications on the pixels before creating the final texture, you can load your file to a sf::Image, do whatever you need with the pixels, and then call Texture::loadFromImage.

Since they live in the graphics card memory, the pixels of a texture cannot be accessed without a slow copy first. And they cannot be accessed individually. Therefore, if you need to read the texture's pixels (like for pixel-perfect collisions), it is recommended to store the collision information separately, for example in an array of booleans.

Like sf::Image, sf::Texture can handle a unique internal representation of pixels, which is RGBA 32 bits. This means that a pixel must be composed of 8 bits red, green, blue and alpha channels just like a sf::Color.

Usage example:

// This example shows the most common use of sf::Texture:
// drawing a sprite

// Load a texture from a file
sf::Texture texture;
if (!texture.loadFromFile("texture.png"))
    return -1;

// Assign it to a sprite
sf::Sprite sprite;
sprite.setTexture(texture);

// Draw the textured sprite
window.draw(sprite);
// This example shows another common use of sf::Texture:
// streaming real-time data, like video frames

// Create an empty texture
sf::Texture texture;
if (!texture.create(640, 480))
    return -1;

// Create a sprite that will display the texture
sf::Sprite sprite(texture);

while (...) // the main loop
{
    ...

    // update the texture
    sf::Uint8* pixels = ...; // get a fresh chunk of pixels (the next frame of a movie, for example)
    texture.update(pixels);

    // draw it
    window.draw(sprite);

    ...
}

Like sf::Shader that can be used as a raw OpenGL shader, sf::Texture can also be used directly as a raw texture for custom OpenGL geometry.

sf::Texture::bind(&texture);
... render OpenGL geometry ...
sf::Texture::bind(NULL);

See also: sf::Sprite, sf::Image, sf::RenderTexture

Summary

Members Descriptions
public Texture() Default constructor.
public Texture(const Texture & copy) Copy constructor.
public ~Texture() Destructor.
public bool create(unsigned int width,unsigned int height) Create the texture.
public bool loadFromFile(const std::string & filename,const IntRect & area) Load the texture from a file on disk.
public bool loadFromMemory(const void * data,std::size_t size,const IntRect & area) Load the texture from a file in memory.
public bool loadFromStream(InputStream& stream,constIntRect & area) Load the texture from a custom stream.
public bool loadFromImage(const Image& image,constIntRect & area) Load the texture from an image.
public Vector2u getSize() const Return the size of the texture.
public Image copyToImage() const Copy the texture pixels to an image.
public void update(const Uint8 * pixels) Update the whole texture from an array of pixels.
public void update(const Uint8 * pixels,unsigned int width,unsigned int height,unsigned int x,unsigned int y) Update a part of the texture from an array of pixels.
public void update(const Texture & texture) Update a part of this texture from another texture.
public void update(const Texture & texture,unsigned int x,unsigned int y) Update a part of this texture from another texture.
public void update(const Image & image) Update the texture from an image.
public void update(const Image & image,unsigned int x,unsigned int y) Update a part of the texture from an image.
public void update(const Window & window) Update the texture from the contents of a window.
public void update(const Window & window,unsigned int x,unsigned int y) Update a part of the texture from the contents of a window.
public void setSmooth(bool smooth) Enable or disable the smooth filter.
public bool isSmooth() const Tell whether the smooth filter is enabled or not.
public void setSrgb(bool sRgb) Enable or disable conversion from sRGB.
public bool isSrgb() const Tell whether the texture source is converted from sRGB or not.
public void setRepeated(bool repeated) Enable or disable repeating.
public bool isRepeated() const Tell whether the texture is repeated or not.
public bool generateMipmap() Generate a mipmap using the current texture data.
public Texture&operator=(const Texture & right) Overload of assignment operator.
public void swap(Texture & right) Swap the contents of this texture with those of another.
public unsigned int getNativeHandle() const Get the underlying OpenGL handle of the texture.
enum CoordinateType Types of texture coordinates that can be used for rendering.

Members

public Texture()

Default constructor.

Creates an empty texture.

public Texture(const Texture & copy)

Copy constructor.

Parameters

  • copy instance to copy

public ~Texture()

Destructor.

public bool create(unsigned int width,unsigned int height)

Create the texture.

If this function fails, the texture is left unchanged.

Parameters

  • width Width of the texture

  • height Height of the texture

Returns

True if creation was successful

public bool loadFromFile(const std::string & filename,const IntRect & area)

Load the texture from a file on disk.

This function is a shortcut for the following code:

sf::Image image;
image.loadFromFile(filename);
texture.loadFromImage(image, area);

The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then leave the default value (which is an empty IntRect). If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.

The maximum size for a texture depends on the graphics driver and can be retrieved with the getMaximumSize function.

If this function fails, the texture is left unchanged.

Parameters

  • filename Path of the image file to load

  • area Area of the image to load

Returns

True if loading was successful

See also: loadFromMemory, loadFromStream, loadFromImage

public bool loadFromMemory(const void * data,std::size_t size,const IntRect & area)

Load the texture from a file in memory.

This function is a shortcut for the following code:

sf::Image image;
image.loadFromMemory(data, size);
texture.loadFromImage(image, area);

The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then leave the default value (which is an empty IntRect). If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.

The maximum size for a texture depends on the graphics driver and can be retrieved with the getMaximumSize function.

If this function fails, the texture is left unchanged.

Parameters

  • data Pointer to the file data in memory

  • size Size of the data to load, in bytes

  • area Area of the image to load

Returns

True if loading was successful

See also: loadFromFile, loadFromStream, loadFromImage

public bool loadFromStream(InputStream& stream,constIntRect & area)

Load the texture from a custom stream.

This function is a shortcut for the following code:

sf::Image image;
image.loadFromStream(stream);
texture.loadFromImage(image, area);

The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then leave the default value (which is an empty IntRect). If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.

The maximum size for a texture depends on the graphics driver and can be retrieved with the getMaximumSize function.

If this function fails, the texture is left unchanged.

Parameters

  • stream Source stream to read from

  • area Area of the image to load

Returns

True if loading was successful

See also: loadFromFile, loadFromMemory, loadFromImage

public bool loadFromImage(const Image& image,constIntRect & area)

Load the texture from an image.

The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then leave the default value (which is an empty IntRect). If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.

The maximum size for a texture depends on the graphics driver and can be retrieved with the getMaximumSize function.

If this function fails, the texture is left unchanged.

Parameters

  • image Image to load into the texture

  • area Area of the image to load

Returns

True if loading was successful

See also: loadFromFile, loadFromMemory

public Vector2u getSize() const

Return the size of the texture.

Returns

Size in pixels

public Image copyToImage() const

Copy the texture pixels to an image.

This function performs a slow operation that downloads the texture's pixels from the graphics card and copies them to a new image, potentially applying transformations to pixels if necessary (texture may be padded or flipped).

Returns

Image containing the texture's pixels

See also: loadFromImage

public void update(const Uint8 * pixels)

Update the whole texture from an array of pixels.

The pixel array is assumed to have the same size as the area rectangle, and to contain 32-bits RGBA pixels.

No additional check is performed on the size of the pixel array, passing invalid arguments will lead to an undefined behavior.

This function does nothing if pixels is null or if the texture was not previously created.

Parameters

  • pixels Array of pixels to copy to the texture

public void update(const Uint8 * pixels,unsigned int width,unsigned int height,unsigned int x,unsigned int y)

Update a part of the texture from an array of pixels.

The size of the pixel array must match the width and height arguments, and it must contain 32-bits RGBA pixels.

No additional check is performed on the size of the pixel array or the bounds of the area to update, passing invalid arguments will lead to an undefined behavior.

This function does nothing if pixels is null or if the texture was not previously created.

Parameters

  • pixels Array of pixels to copy to the texture

  • width Width of the pixel region contained in pixels

  • height Height of the pixel region contained in pixels

  • x X offset in the texture where to copy the source pixels

  • y Y offset in the texture where to copy the source pixels

public void update(const Texture & texture)

Update a part of this texture from another texture.

Although the source texture can be smaller than this texture, this function is usually used for updating the whole texture. The other overload, which has (x, y) additional arguments, is more convenient for updating a sub-area of this texture.

No additional check is performed on the size of the passed texture, passing a texture bigger than this texture will lead to an undefined behavior.

This function does nothing if either texture was not previously created.

Parameters

  • texture Source texture to copy to this texture

public void update(const Texture & texture,unsigned int x,unsigned int y)

Update a part of this texture from another texture.

No additional check is performed on the size of the texture, passing an invalid combination of texture size and offset will lead to an undefined behavior.

This function does nothing if either texture was not previously created.

Parameters

  • texture Source texture to copy to this texture

  • x X offset in this texture where to copy the source texture

  • y Y offset in this texture where to copy the source texture

public void update(const Image & image)

Update the texture from an image.

Although the source image can be smaller than the texture, this function is usually used for updating the whole texture. The other overload, which has (x, y) additional arguments, is more convenient for updating a sub-area of the texture.

No additional check is performed on the size of the image, passing an image bigger than the texture will lead to an undefined behavior.

This function does nothing if the texture was not previously created.

Parameters

  • image Image to copy to the texture

public void update(const Image & image,unsigned int x,unsigned int y)

Update a part of the texture from an image.

No additional check is performed on the size of the image, passing an invalid combination of image size and offset will lead to an undefined behavior.

This function does nothing if the texture was not previously created.

Parameters

  • image Image to copy to the texture

  • x X offset in the texture where to copy the source image

  • y Y offset in the texture where to copy the source image

public void update(const Window & window)

Update the texture from the contents of a window.

Although the source window can be smaller than the texture, this function is usually used for updating the whole texture. The other overload, which has (x, y) additional arguments, is more convenient for updating a sub-area of the texture.

No additional check is performed on the size of the window, passing a window bigger than the texture will lead to an undefined behavior.

This function does nothing if either the texture or the window was not previously created.

Parameters

  • window Window to copy to the texture

public void update(const Window & window,unsigned int x,unsigned int y)

Update a part of the texture from the contents of a window.

No additional check is performed on the size of the window, passing an invalid combination of window size and offset will lead to an undefined behavior.

This function does nothing if either the texture or the window was not previously created.

Parameters

  • window Window to copy to the texture

  • x X offset in the texture where to copy the source window

  • y Y offset in the texture where to copy the source window

public void setSmooth(bool smooth)

Enable or disable the smooth filter.

When the filter is activated, the texture appears smoother so that pixels are less noticeable. However if you want the texture to look exactly the same as its source file, you should leave it disabled. The smooth filter is disabled by default.

Parameters

  • smooth True to enable smoothing, false to disable it

See also: isSmooth

public bool isSmooth() const

Tell whether the smooth filter is enabled or not.

Returns

True if smoothing is enabled, false if it is disabled

See also: setSmooth

public void setSrgb(bool sRgb)

Enable or disable conversion from sRGB.

When providing texture data from an image file or memory, it can either be stored in a linear color space or an sRGB color space. Most digital images account for gamma correction already, so they would need to be "uncorrected" back to linear color space before being processed by the hardware. The hardware can automatically convert it from the sRGB color space to a linear color space when it gets sampled. When the rendered image gets output to the final framebuffer, it gets converted back to sRGB.

After enabling or disabling sRGB conversion, make sure to reload the texture data in order for the setting to take effect.

This option is only useful in conjunction with an sRGB capable framebuffer. This can be requested during window creation.

Parameters

  • sRgb True to enable sRGB conversion, false to disable it

See also: isSrgb

public bool isSrgb() const

Tell whether the texture source is converted from sRGB or not.

Returns

True if the texture source is converted from sRGB, false if not

See also: setSrgb

public void setRepeated(bool repeated)

Enable or disable repeating.

Repeating is involved when using texture coordinates outside the texture rectangle [0, 0, width, height]. In this case, if repeat mode is enabled, the whole texture will be repeated as many times as needed to reach the coordinate (for example, if the X texture coordinate is 3 * width, the texture will be repeated 3 times). If repeat mode is disabled, the "extra space" will instead be filled with border pixels. Warning: on very old graphics cards, white pixels may appear when the texture is repeated. With such cards, repeat mode can be used reliably only if the texture has power-of-two dimensions (such as 256x128). Repeating is disabled by default.

Parameters

  • repeated True to repeat the texture, false to disable repeating

See also: isRepeated

public bool isRepeated() const

Tell whether the texture is repeated or not.

Returns

True if repeat mode is enabled, false if it is disabled

See also: setRepeated

public bool generateMipmap()

Generate a mipmap using the current texture data.

Mipmaps are pre-computed chains of optimized textures. Each level of texture in a mipmap is generated by halving each of the previous level's dimensions. This is done until the final level has the size of 1x1. The textures generated in this process may make use of more advanced filters which might improve the visual quality of textures when they are applied to objects much smaller than they are. This is known as minification. Because fewer texels (texture elements) have to be sampled from when heavily minified, usage of mipmaps can also improve rendering performance in certain scenarios.

Mipmap generation relies on the necessary OpenGL extension being available. If it is unavailable or generation fails due to another reason, this function will return false. Mipmap data is only valid from the time it is generated until the next time the base level image is modified, at which point this function will have to be called again to regenerate it.

Returns

True if mipmap generation was successful, false if unsuccessful

public Texture&operator=(const Texture & right)

Overload of assignment operator.

Parameters

  • right Instance to assign

Returns

Reference to self

public void swap(Texture & right)

Swap the contents of this texture with those of another.

Parameters

  • right Instance to swap with

public unsigned int getNativeHandle() const

Get the underlying OpenGL handle of the texture.

You shouldn't need to use this function, unless you have very specific stuff to implement that SFML doesn't support, or implement a temporary workaround until a bug is fixed.

Returns

OpenGL handle of the texture or 0 if not yet created

Values Descriptions
Normalized Texture coordinates in range [0 .. 1].
Pixels Texture coordinates in range [0 .. size].

Types of texture coordinates that can be used for rendering.

class sf::Transform

Define a 3x3 transform matrix.

A sf::Transform specifies how to translate, rotate, scale, shear, project, whatever things.

In mathematical terms, it defines how to transform a coordinate system into another.

For example, if you apply a rotation transform to a sprite, the result will be a rotated sprite. And anything that is transformed by this rotation transform will be rotated the same way, according to its initial position.

Transforms are typically used for drawing. But they can also be used for any computation that requires to transform points between the local and global coordinate systems of an entity (like collision detection).

Example:

// define a translation transform
sf::Transform translation;
translation.translate(20, 50);

// define a rotation transform
sf::Transform rotation;
rotation.rotate(45);

// combine them
sf::Transform transform = translation * rotation;

// use the result to transform stuff...
sf::Vector2f point = transform.transformPoint(10, 20);
sf::FloatRect rect = transform.transformRect(sf::FloatRect(0, 0, 10, 100));

See also: sf::Transformable, sf::RenderStates

Summary

Members Descriptions
public Transform() Default constructor.
public Transform(float a00,float a01,float a02,float a10,float a11,float a12,float a20,float a21,float a22) Construct a transform from a 3x3 matrix.
public const float * getMatrix() const Return the transform as a 4x4 matrix.
public Transform getInverse() const Return the inverse of the transform.
public Vector2f transformPoint(float x,float y) const Transform a 2D point.
public Vector2f transformPoint(const Vector2f & point) const Transform a 2D point.
public FloatRect transformRect(const FloatRect & rectangle) const Transform a rectangle.
public Transform&combine(const Transform & transform) Combine the current transform with another one.
public Transform&translate(float x,float y) Combine the current transform with a translation.
public Transform&translate(const Vector2f & offset) Combine the current transform with a translation.
public Transform&rotate(float angle) Combine the current transform with a rotation.
public Transform&rotate(float angle,float centerX,float centerY) Combine the current transform with a rotation.
public Transform&rotate(float angle,const Vector2f & center) Combine the current transform with a rotation.
public Transform&scale(float scaleX,float scaleY) Combine the current transform with a scaling.
public Transform&scale(float scaleX,float scaleY,float centerX,float centerY) Combine the current transform with a scaling.
public Transform&scale(const Vector2f & factors) Combine the current transform with a scaling.
public Transform&scale(const Vector2f& factors,constVector2f & center) Combine the current transform with a scaling.

Members

public Transform()

Default constructor.

Creates an identity transform (a transform that does nothing).

public Transform(float a00,float a01,float a02,float a10,float a11,float a12,float a20,float a21,float a22)

Construct a transform from a 3x3 matrix.

Parameters

  • a00 Element (0, 0) of the matrix

  • a01 Element (0, 1) of the matrix

  • a02 Element (0, 2) of the matrix

  • a10 Element (1, 0) of the matrix

  • a11 Element (1, 1) of the matrix

  • a12 Element (1, 2) of the matrix

  • a20 Element (2, 0) of the matrix

  • a21 Element (2, 1) of the matrix

  • a22 Element (2, 2) of the matrix

public const float * getMatrix() const

Return the transform as a 4x4 matrix.

This function returns a pointer to an array of 16 floats containing the transform elements as a 4x4 matrix, which is directly compatible with OpenGL functions.

sf::Transform transform = ...;
glLoadMatrixf(transform.getMatrix());

Returns

Pointer to a 4x4 matrix

public Transform getInverse() const

Return the inverse of the transform.

If the inverse cannot be computed, an identity transform is returned.

Returns

A new transform which is the inverse of self

public Vector2f transformPoint(float x,float y) const

Transform a 2D point.

Parameters

  • x X coordinate of the point to transform

  • y Y coordinate of the point to transform

Returns

Transformed point

public Vector2f transformPoint(const Vector2f & point) const

Transform a 2D point.

Parameters

  • point Point to transform

Returns

Transformed point

public FloatRect transformRect(const FloatRect & rectangle) const

Transform a rectangle.

Since SFML doesn't provide support for oriented rectangles, the result of this function is always an axis-aligned rectangle. Which means that if the transform contains a rotation, the bounding rectangle of the transformed rectangle is returned.

Parameters

  • rectangle Rectangle to transform

Returns

Transformed rectangle

public Transform&combine(const Transform & transform)

Combine the current transform with another one.

The result is a transform that is equivalent to applying *this followed by transform. Mathematically, it is equivalent to a matrix multiplication.

Parameters

  • transform Transform to combine with this transform

Returns

Reference to *this

public Transform&translate(float x,float y)

Combine the current transform with a translation.

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.translate(100, 200).rotate(45);

Parameters

  • x Offset to apply on X axis

  • y Offset to apply on Y axis

Returns

Reference to *this

See also: rotate, scale

public Transform&translate(const Vector2f & offset)

Combine the current transform with a translation.

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.translate(sf::Vector2f(100, 200)).rotate(45);

Parameters

  • offset Translation offset to apply

Returns

Reference to *this

See also: rotate, scale

public Transform&rotate(float angle)

Combine the current transform with a rotation.

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.rotate(90).translate(50, 20);

Parameters

  • angle Rotation angle, in degrees

Returns

Reference to *this

See also: translate, scale

public Transform&rotate(float angle,float centerX,float centerY)

Combine the current transform with a rotation.

The center of rotation is provided for convenience as a second argument, so that you can build rotations around arbitrary points more easily (and efficiently) than the usual translate(-center).rotate(angle).translate(center).

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.rotate(90, 8, 3).translate(50, 20);

Parameters

  • angle Rotation angle, in degrees

  • centerX X coordinate of the center of rotation

  • centerY Y coordinate of the center of rotation

Returns

Reference to *this

See also: translate, scale

public Transform&rotate(float angle,const Vector2f & center)

Combine the current transform with a rotation.

The center of rotation is provided for convenience as a second argument, so that you can build rotations around arbitrary points more easily (and efficiently) than the usual translate(-center).rotate(angle).translate(center).

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.rotate(90, sf::Vector2f(8, 3)).translate(sf::Vector2f(50, 20));

Parameters

  • angle Rotation angle, in degrees

  • center Center of rotation

Returns

Reference to *this

See also: translate, scale

public Transform&scale(float scaleX,float scaleY)

Combine the current transform with a scaling.

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.scale(2, 1).rotate(45);

Parameters

  • scaleX Scaling factor on the X axis

  • scaleY Scaling factor on the Y axis

Returns

Reference to *this

See also: translate, rotate

public Transform&scale(float scaleX,float scaleY,float centerX,float centerY)

Combine the current transform with a scaling.

The center of scaling is provided for convenience as a second argument, so that you can build scaling around arbitrary points more easily (and efficiently) than the usual translate(-center).scale(factors).translate(center).

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.scale(2, 1, 8, 3).rotate(45);

Parameters

  • scaleX Scaling factor on X axis

  • scaleY Scaling factor on Y axis

  • centerX X coordinate of the center of scaling

  • centerY Y coordinate of the center of scaling

Returns

Reference to *this

See also: translate, rotate

public Transform&scale(const Vector2f & factors)

Combine the current transform with a scaling.

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.scale(sf::Vector2f(2, 1)).rotate(45);

Parameters

  • factors Scaling factors

Returns

Reference to *this

See also: translate, rotate

public Transform&scale(const Vector2f& factors,constVector2f & center)

Combine the current transform with a scaling.

The center of scaling is provided for convenience as a second argument, so that you can build scaling around arbitrary points more easily (and efficiently) than the usual translate(-center).scale(factors).translate(center).

This function returns a reference to *this, so that calls can be chained.

sf::Transform transform;
transform.scale(sf::Vector2f(2, 1), sf::Vector2f(8, 3)).rotate(45);

Parameters

  • factors Scaling factors

  • center Center of scaling

Returns

Reference to *this

See also: translate, rotate

class sf::Transformable

Decomposed transform defined by a position, a rotation and a scale.

This class is provided for convenience, on top of sf::Transform.

sf::Transform, as a low-level class, offers a great level of flexibility but it is not always convenient to manage. Indeed, one can easily combine any kind of operation, such as a translation followed by a rotation followed by a scaling, but once the result transform is built, there's no way to go backward and, let's say, change only the rotation without modifying the translation and scaling. The entire transform must be recomputed, which means that you need to retrieve the initial translation and scale factors as well, and combine them the same way you did before updating the rotation. This is a tedious operation, and it requires to store all the individual components of the final transform.

That's exactly what sf::Transformable was written for: it hides these variables and the composed transform behind an easy to use interface. You can set or get any of the individual components without worrying about the others. It also provides the composed transform (as a sf::Transform), and keeps it up-to-date.

In addition to the position, rotation and scale, sf::Transformable provides an "origin" component, which represents the local origin of the three other components. Let's take an example with a 10x10 pixels sprite. By default, the sprite is positioned/rotated/scaled relatively to its top-left corner, because it is the local point (0, 0). But if we change the origin to be (5, 5), the sprite will be positioned/rotated/scaled around its center instead. And if we set the origin to (10, 10), it will be transformed around its bottom-right corner.

To keep the sf::Transformable class simple, there's only one origin for all the components. You cannot position the sprite relatively to its top-left corner while rotating it around its center, for example. To do such things, use sf::Transform directly.

sf::Transformable can be used as a base class. It is often combined with sf::Drawable that's what SFML's sprites, texts and shapes do.

class MyEntity : public sf::Transformable, public sf::Drawable
{
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
        states.transform *= getTransform();
        target.draw(..., states);
    }
};

MyEntity entity;
entity.setPosition(10, 20);
entity.setRotation(45);
window.draw(entity);

It can also be used as a member, if you don't want to use its API directly (because you don't need all its functions, or you have different naming conventions for example).

class MyEntity
{
public:
    void SetPosition(const MyVector& v)
    {
        myTransform.setPosition(v.x(), v.y());
    }

    void Draw(sf::RenderTarget& target) const
    {
        target.draw(..., myTransform.getTransform());
    }

private:
    sf::Transformable myTransform;
};

A note on coordinates and undistorted rendering: By default, SFML (or more exactly, OpenGL) may interpolate drawable objects such as sprites or texts when rendering. While this allows transitions like slow movements or rotations to appear smoothly, it can lead to unwanted results in some cases, for example blurred or distorted objects. In order to render a sf::Drawable object pixel-perfectly, make sure the involved coordinates allow a 1:1 mapping of pixels in the window to texels (pixels in the texture). More specifically, this means:

  • The object's position, origin and scale have no fractional part

  • The object's and the view's rotation are a multiple of 90 degrees

  • The view's center and size have no fractional part

See also: sf::Transform

Summary

Members Descriptions
public Transformable() Default constructor.
public virtual ~Transformable() Virtual destructor.
public void setPosition(float x,float y) set the position of the object
public void setPosition(const Vector2f & position) set the position of the object
public void setRotation(float angle) set the orientation of the object
public void setScale(float factorX,float factorY) set the scale factors of the object
public void setScale(const Vector2f & factors) set the scale factors of the object
public void setOrigin(float x,float y) set the local origin of the object
public void setOrigin(const Vector2f & origin) set the local origin of the object
public const Vector2f&getPosition() const get the position of the object
public float getRotation() const get the orientation of the object
public const Vector2f&getScale() const get the current scale of the object
public const Vector2f&getOrigin() const get the local origin of the object
public void move(float offsetX,float offsetY) Move the object by a given offset.
public void move(const Vector2f & offset) Move the object by a given offset.
public void rotate(float angle) Rotate the object.
public void scale(float factorX,float factorY) Scale the object.
public void scale(const Vector2f & factor) Scale the object.
public const Transform&getTransform() const get the combined transform of the object
public const Transform&getInverseTransform() const get the inverse of the combined transform of the object

Members

public Transformable()

Default constructor.

public virtual ~Transformable()

Virtual destructor.

public void setPosition(float x,float y)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new position

  • y Y coordinate of the new position

See also: move, getPosition

public void setPosition(const Vector2f & position)

set the position of the object

This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).

Parameters

  • position New position

See also: move, getPosition

public void setRotation(float angle)

set the orientation of the object

This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.

Parameters

  • angle New rotation, in degrees

See also: rotate, getRotation

public void setScale(float factorX,float factorY)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factorX New horizontal scale factor

  • factorY New vertical scale factor

See also: scale, getScale

public void setScale(const Vector2f & factors)

set the scale factors of the object

This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).

Parameters

  • factors New scale factors

See also: scale, getScale

public void setOrigin(float x,float y)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • x X coordinate of the new origin

  • y Y coordinate of the new origin

See also: getOrigin

public void setOrigin(const Vector2f & origin)

set the local origin of the object

The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).

Parameters

  • origin New origin

See also: getOrigin

public const Vector2f&getPosition() const

get the position of the object

Returns

Current position

See also: setPosition

public float getRotation() const

get the orientation of the object

The rotation is always in the range [0, 360].

Returns

Current rotation, in degrees

See also: setRotation

public const Vector2f&getScale() const

get the current scale of the object

Returns

Current scale factors

See also: setScale

public const Vector2f&getOrigin() const

get the local origin of the object

Returns

Current origin

See also: setOrigin

public void move(float offsetX,float offsetY)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f pos = object.getPosition();
object.setPosition(pos.x + offsetX, pos.y + offsetY);

Parameters

  • offsetX X offset

  • offsetY Y offset

See also: setPosition

public void move(const Vector2f & offset)

Move the object by a given offset.

This function adds to the current position of the object, unlike setPosition which overwrites it. Thus, it is equivalent to the following code:

object.setPosition(object.getPosition() + offset);

Parameters

  • offset Offset

See also: setPosition

public void rotate(float angle)

Rotate the object.

This function adds to the current rotation of the object, unlike setRotation which overwrites it. Thus, it is equivalent to the following code:

object.setRotation(object.getRotation() + angle);

Parameters

  • angle Angle of rotation, in degrees

public void scale(float factorX,float factorY)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factorX, scale.y * factorY);

Parameters

  • factorX Horizontal scale factor

  • factorY Vertical scale factor

See also: setScale

public void scale(const Vector2f & factor)

Scale the object.

This function multiplies the current scale of the object, unlike setScale which overwrites it. Thus, it is equivalent to the following code:

sf::Vector2f scale = object.getScale();
object.setScale(scale.x * factor.x, scale.y * factor.y);

Parameters

  • factor Scale factors

See also: setScale

public const Transform&getTransform() const

get the combined transform of the object

Returns

Transform combining the position/rotation/scale/origin of the object

See also: getInverseTransform

public const Transform&getInverseTransform() const

get the inverse of the combined transform of the object

Returns

Inverse of the combined transformations applied to the object

See also: getTransform

class sf::Vertex

Define a point with color and texture coordinates.

A vertex is an improved point.

It has a position and other extra attributes that will be used for drawing: in SFML, vertices also have a color and a pair of texture coordinates.

The vertex is the building block of drawing. Everything which is visible on screen is made of vertices. They are grouped as 2D primitives (triangles, quads, ...), and these primitives are grouped to create even more complex 2D entities such as sprites, texts, etc.

If you use the graphical entities of SFML (sprite, text, shape) you won't have to deal with vertices directly. But if you want to define your own 2D entities, such as tiled maps or particle systems, using vertices will allow you to get maximum performances.

Example:

// define a 100x100 square, red, with a 10x10 texture mapped on it
sf::Vertex vertices[] =
{
    sf::Vertex(sf::Vector2f(  0,   0), sf::Color::Red, sf::Vector2f( 0,  0)),
    sf::Vertex(sf::Vector2f(  0, 100), sf::Color::Red, sf::Vector2f( 0, 10)),
    sf::Vertex(sf::Vector2f(100, 100), sf::Color::Red, sf::Vector2f(10, 10)),
    sf::Vertex(sf::Vector2f(100,   0), sf::Color::Red, sf::Vector2f(10,  0))
};

// draw it
window.draw(vertices, 4, sf::Quads);

Note: although texture coordinates are supposed to be an integer amount of pixels, their type is float because of some buggy graphics drivers that are not able to process integer coordinates correctly.

See also: sf::VertexArray

Summary

Members Descriptions
public Vector2f position 2D position of the vertex
public Color color Color of the vertex.
public Vector2f texCoords Coordinates of the texture's pixel to map to the vertex.
public Vertex() Default constructor.
public Vertex(const Vector2f & thePosition) Construct the vertex from its position.
public Vertex(const Vector2f& thePosition,constColor & theColor) Construct the vertex from its position and color.
public Vertex(const Vector2f& thePosition,constVector2f & theTexCoords) Construct the vertex from its position and texture coordinates.
public Vertex(const Vector2f& thePosition,constColor& theColor,constVector2f & theTexCoords) Construct the vertex from its position, color and texture coordinates.

Members

2D position of the vertex

public Color color

Color of the vertex.

Coordinates of the texture's pixel to map to the vertex.

public Vertex()

Default constructor.

public Vertex(const Vector2f & thePosition)

Construct the vertex from its position.

The vertex color is white and texture coordinates are (0, 0).

Parameters

public Vertex(const Vector2f& thePosition,constColor & theColor)

Construct the vertex from its position and color.

The texture coordinates are (0, 0).

Parameters

public Vertex(const Vector2f& thePosition,constVector2f & theTexCoords)

Construct the vertex from its position and texture coordinates.

The vertex color is white.

Parameters

  • thePosition Vertex position

  • theTexCoords Vertex texture coordinates

public Vertex(const Vector2f& thePosition,constColor& theColor,constVector2f & theTexCoords)

Construct the vertex from its position, color and texture coordinates.

Parameters

  • thePosition Vertex position

  • theColor Vertex color

  • theTexCoords Vertex texture coordinates

class sf::VertexArray

class sf::VertexArray
  : public sf::Drawable

Define a set of one or more 2D primitives.

sf::VertexArray is a very simple wrapper around a dynamic array of vertices and a primitives type.

It inherits sf::Drawable, but unlike other drawables it is not transformable.

Example:

sf::VertexArray lines(sf::LineStrip, 4);
lines[0].position = sf::Vector2f(10, 0);
lines[1].position = sf::Vector2f(20, 0);
lines[2].position = sf::Vector2f(30, 5);
lines[3].position = sf::Vector2f(40, 2);

window.draw(lines);

See also: sf::Vertex

Summary

Members Descriptions
public VertexArray() Default constructor.
public explicit VertexArray(PrimitiveType type,std::size_t vertexCount) Construct the vertex array with a type and an initial number of vertices.
public std::size_t getVertexCount() const Return the vertex count.
public Vertex&operator[](std::size_t index) Get a read-write access to a vertex by its index.
public const Vertex&operator[](std::size_t index) const Get a read-only access to a vertex by its index.
public void clear() Clear the vertex array.
public void resize(std::size_t vertexCount) Resize the vertex array.
public void append(const Vertex & vertex) Add a vertex to the array.
public void setPrimitiveType(PrimitiveType type) Set the type of primitives to draw.
public PrimitiveType getPrimitiveType() const Get the type of primitives drawn by the vertex array.
public FloatRect getBounds() const Compute the bounding rectangle of the vertex array.

Members

public VertexArray()

Default constructor.

Creates an empty vertex array.

public explicit VertexArray(PrimitiveType type,std::size_t vertexCount)

Construct the vertex array with a type and an initial number of vertices.

Parameters

  • type Type of primitives

  • vertexCount Initial number of vertices in the array

public std::size_t getVertexCount() const

Return the vertex count.

Returns

Number of vertices in the array

public Vertex&operator[](std::size_t index)

Get a read-write access to a vertex by its index.

This function doesn't check index, it must be in range [0, getVertexCount() - 1]. The behavior is undefined otherwise.

Parameters

  • index Index of the vertex to get

Returns

Reference to the index-th vertex

See also: getVertexCount

public const Vertex&operator[](std::size_t index) const

Get a read-only access to a vertex by its index.

This function doesn't check index, it must be in range [0, getVertexCount() - 1]. The behavior is undefined otherwise.

Parameters

  • index Index of the vertex to get

Returns

Const reference to the index-th vertex

See also: getVertexCount

public void clear()

Clear the vertex array.

This function removes all the vertices from the array. It doesn't deallocate the corresponding memory, so that adding new vertices after clearing doesn't involve reallocating all the memory.

public void resize(std::size_t vertexCount)

Resize the vertex array.

If vertexCount is greater than the current size, the previous vertices are kept and new (default-constructed) vertices are added. If vertexCount is less than the current size, existing vertices are removed from the array.

Parameters

  • vertexCount New size of the array (number of vertices)

public void append(const Vertex & vertex)

Add a vertex to the array.

Parameters

Set the type of primitives to draw.

This function defines how the vertices must be interpreted when it's time to draw them:

  • As points

  • As lines

  • As triangles

  • As quads The default primitive type is sf::Points.

Parameters

  • type Type of primitive

Get the type of primitives drawn by the vertex array.

Returns

Primitive type

public FloatRect getBounds() const

Compute the bounding rectangle of the vertex array.

This function returns the minimal axis-aligned rectangle that contains all the vertices of the array.

Returns

Bounding rectangle of the vertex array

class sf::VertexBuffer

class sf::VertexBuffer
  : public sf::Drawable
  : private sf::GlResource

Vertex buffer storage for one or more 2D primitives.

sf::VertexBuffer is a simple wrapper around a dynamic buffer of vertices and a primitives type.

Unlike sf::VertexArray, the vertex data is stored in graphics memory.

In situations where a large amount of vertex data would have to be transferred from system memory to graphics memory every frame, using sf::VertexBuffer can help. By using a sf::VertexBuffer, data that has not been changed between frames does not have to be re-transferred from system to graphics memory as would be the case with sf::VertexArray. If data transfer is a bottleneck, this can lead to performance gains.

Using sf::VertexBuffer, the user also has the ability to only modify a portion of the buffer in graphics memory. This way, a large buffer can be allocated at the start of the application and only the applicable portions of it need to be updated during the course of the application. This allows the user to take full control of data transfers between system and graphics memory if they need to.

In special cases, the user can make use of multiple threads to update vertex data in multiple distinct regions of the buffer simultaneously. This might make sense when e.g. the position of multiple objects has to be recalculated very frequently. The computation load can be spread across multiple threads as long as there are no other data dependencies.

Simultaneous updates to the vertex buffer are not guaranteed to be carried out by the driver in any specific order. Updating the same region of the buffer from multiple threads will not cause undefined behaviour, however the final state of the buffer will be unpredictable.

Simultaneous updates of distinct non-overlapping regions of the buffer are also not guaranteed to complete in a specific order. However, in this case the user can make sure to synchronize the writer threads at well-defined points in their code. The driver will make sure that all pending data transfers complete before the vertex buffer is sourced by the rendering pipeline.

It inherits sf::Drawable, but unlike other drawables it is not transformable.

Example:

sf::Vertex vertices[15];
...
sf::VertexBuffer triangles(sf::Triangles);
triangles.create(15);
triangles.update(vertices);
...
window.draw(triangles);

See also: sf::Vertex, sf::VertexArray

Summary

Members Descriptions
public VertexBuffer() Default constructor.
public explicit VertexBuffer(PrimitiveType type) Construct a VertexBuffer with a specific PrimitiveType.
public explicit VertexBuffer(Usage usage) Construct a VertexBuffer with a specific usage specifier.
public VertexBuffer(PrimitiveType type,Usage usage) Construct a VertexBuffer with a specific PrimitiveType and usage specifier.
public VertexBuffer(const VertexBuffer & copy) Copy constructor.
public ~VertexBuffer() Destructor.
public bool create(std::size_t vertexCount) Create the vertex buffer.
public std::size_t getVertexCount() const Return the vertex count.
public bool update(const Vertex * vertices) Update the whole buffer from an array of vertices.
public bool update(const Vertex * vertices,std::size_t vertexCount,unsigned int offset) Update a part of the buffer from an array of vertices.
public bool update(const VertexBuffer & vertexBuffer) Copy the contents of another buffer into this buffer.
public VertexBuffer&operator=(const VertexBuffer & right) Overload of assignment operator.
public void swap(VertexBuffer & right) Swap the contents of this vertex buffer with those of another.
public unsigned int getNativeHandle() const Get the underlying OpenGL handle of the vertex buffer.
public void setPrimitiveType(PrimitiveType type) Set the type of primitives to draw.
public PrimitiveType getPrimitiveType() const Get the type of primitives drawn by the vertex buffer.
public void setUsage(Usage usage) Set the usage specifier of this vertex buffer.
public Usage getUsage() const Get the usage specifier of this vertex buffer.
enum Usage Usage specifiers.

Members

public VertexBuffer()

Default constructor.

Creates an empty vertex buffer.

public explicit VertexBuffer(PrimitiveType type)

Construct a VertexBuffer with a specific PrimitiveType.

Creates an empty vertex buffer and sets its primitive type to type.

Parameters

  • type Type of primitive

public explicit VertexBuffer(Usage usage)

Construct a VertexBuffer with a specific usage specifier.

Creates an empty vertex buffer and sets its usage to usage.

Parameters

  • usage Usage specifier

public VertexBuffer(PrimitiveType type,Usage usage)

Construct a VertexBuffer with a specific PrimitiveType and usage specifier.

Creates an empty vertex buffer and sets its primitive type to type and usage to usage.

Parameters

  • type Type of primitive

  • usage Usage specifier

public VertexBuffer(const VertexBuffer & copy)

Copy constructor.

Parameters

  • copy instance to copy

public ~VertexBuffer()

Destructor.

public bool create(std::size_t vertexCount)

Create the vertex buffer.

Creates the vertex buffer and allocates enough graphics memory to hold vertexCount vertices. Any previously allocated memory is freed in the process.

In order to deallocate previously allocated memory pass 0 as vertexCount. Don't forget to recreate with a non-zero value when graphics memory should be allocated again.

Parameters

  • vertexCount Number of vertices worth of memory to allocate

Returns

True if creation was successful

public std::size_t getVertexCount() const

Return the vertex count.

Returns

Number of vertices in the vertex buffer

public bool update(const Vertex * vertices)

Update the whole buffer from an array of vertices.

The vertex array is assumed to have the same size as the created buffer.

No additional check is performed on the size of the vertex array, passing invalid arguments will lead to undefined behavior.

This function does nothing if vertices is null or if the buffer was not previously created.

Parameters

  • vertices Array of vertices to copy to the buffer

Returns

True if the update was successful

public bool update(const Vertex * vertices,std::size_t vertexCount,unsigned int offset)

Update a part of the buffer from an array of vertices.

offset is specified as the number of vertices to skip from the beginning of the buffer.

If offset is 0 and vertexCount is equal to the size of the currently created buffer, its whole contents are replaced.

If offset is 0 and vertexCount is greater than the size of the currently created buffer, a new buffer is created containing the vertex data.

If offset is 0 and vertexCount is less than the size of the currently created buffer, only the corresponding region is updated.

If offset is not 0 and offset + vertexCount is greater than the size of the currently created buffer, the update fails.

No additional check is performed on the size of the vertex array, passing invalid arguments will lead to undefined behavior.

Parameters

  • vertices Array of vertices to copy to the buffer

  • vertexCount Number of vertices to copy

  • offset Offset in the buffer to copy to

Returns

True if the update was successful

public bool update(const VertexBuffer & vertexBuffer)

Copy the contents of another buffer into this buffer.

Parameters

  • vertexBuffer Vertex buffer whose contents to copy into this vertex buffer

Returns

True if the copy was successful

public VertexBuffer&operator=(const VertexBuffer & right)

Overload of assignment operator.

Parameters

  • right Instance to assign

Returns

Reference to self

public void swap(VertexBuffer & right)

Swap the contents of this vertex buffer with those of another.

Parameters

  • right Instance to swap with

public unsigned int getNativeHandle() const

Get the underlying OpenGL handle of the vertex buffer.

You shouldn't need to use this function, unless you have very specific stuff to implement that SFML doesn't support, or implement a temporary workaround until a bug is fixed.

Returns

OpenGL handle of the vertex buffer or 0 if not yet created

Set the type of primitives to draw.

This function defines how the vertices must be interpreted when it's time to draw them.

The default primitive type is sf::Points.

Parameters

  • type Type of primitive

Get the type of primitives drawn by the vertex buffer.

Returns

Primitive type

public void setUsage(Usage usage)

Set the usage specifier of this vertex buffer.

This function provides a hint about how this vertex buffer is going to be used in terms of data update frequency.

After changing the usage specifier, the vertex buffer has to be updated with new data for the usage specifier to take effect.

The default primitive type is sf::VertexBuffer::Stream.

Parameters

  • usage Usage specifier

public Usage getUsage() const

Get the usage specifier of this vertex buffer.

Returns

Usage specifier

enum Usage

Values Descriptions
Stream Constantly changing data.
Dynamic Occasionally changing data.
Static Rarely changing data.

Usage specifiers.

If data is going to be updated once or more every frame, set the usage to Stream. If data is going to be set once and used for a long time without being modified, set the usage to Static. For everything else Dynamic should be a good compromise.

class sf::View

2D camera that defines what region is shown on screen

sf::View defines a camera in the 2D scene.

This is a very powerful concept: you can scroll, rotate or zoom the entire scene without altering the way that your drawable objects are drawn.

A view is composed of a source rectangle, which defines what part of the 2D scene is shown, and a target viewport, which defines where the contents of the source rectangle will be displayed on the render target (window or texture).

The viewport allows to map the scene to a custom part of the render target, and can be used for split-screen or for displaying a minimap, for example. If the source rectangle doesn't have the same size as the viewport, its contents will be stretched to fit in.

To apply a view, you have to assign it to the render target. Then, objects drawn in this render target will be affected by the view until you use another view.

Usage example:

sf::RenderWindow window;
sf::View view;

// Initialize the view to a rectangle located at (100, 100) and with a size of 400x200
view.reset(sf::FloatRect(100, 100, 400, 200));

// Rotate it by 45 degrees
view.rotate(45);

// Set its target viewport to be half of the window
view.setViewport(sf::FloatRect(0.f, 0.f, 0.5f, 1.f));

// Apply it
window.setView(view);

// Render stuff
window.draw(someSprite);

// Set the default view back
window.setView(window.getDefaultView());

// Render stuff not affected by the view
window.draw(someText);

See also the note on coordinates and undistorted rendering in sf::Transformable.

See also: sf::RenderWindow, sf::RenderTexture

Summary

Members Descriptions
public View() Default constructor.
public explicit View(const FloatRect & rectangle) Construct the view from a rectangle.
public View(const Vector2f& center,constVector2f & size) Construct the view from its center and size.
public void setCenter(float x,float y) Set the center of the view.
public void setCenter(const Vector2f & center) Set the center of the view.
public void setSize(float width,float height) Set the size of the view.
public void setSize(const Vector2f & size) Set the size of the view.
public void setRotation(float angle) Set the orientation of the view.
public void setViewport(const FloatRect & viewport) Set the target viewport.
public void reset(const FloatRect & rectangle) Reset the view to the given rectangle.
public const Vector2f&getCenter() const Get the center of the view.
public const Vector2f&getSize() const Get the size of the view.
public float getRotation() const Get the current orientation of the view.
public const FloatRect&getViewport() const Get the target viewport rectangle of the view.
public void move(float offsetX,float offsetY) Move the view relatively to its current position.
public void move(const Vector2f & offset) Move the view relatively to its current position.
public void rotate(float angle) Rotate the view relatively to its current orientation.
public void zoom(float factor) Resize the view rectangle relatively to its current size.
public const Transform&getTransform() const Get the projection transform of the view.
public const Transform&getInverseTransform() const Get the inverse projection transform of the view.

Members

public View()

Default constructor.

This constructor creates a default view of (0, 0, 1000, 1000)

public explicit View(const FloatRect & rectangle)

Construct the view from a rectangle.

Parameters

  • rectangle Rectangle defining the zone to display

public View(const Vector2f& center,constVector2f & size)

Construct the view from its center and size.

Parameters

  • center Center of the zone to display

  • size Size of zone to display

public void setCenter(float x,float y)

Set the center of the view.

Parameters

  • x X coordinate of the new center

  • y Y coordinate of the new center

See also: setSize, getCenter

public void setCenter(const Vector2f & center)

Set the center of the view.

Parameters

  • center New center

See also: setSize, getCenter

public void setSize(float width,float height)

Set the size of the view.

Parameters

  • width New width of the view

  • height New height of the view

See also: setCenter, getCenter

public void setSize(const Vector2f & size)

Set the size of the view.

Parameters

  • size New size

See also: setCenter, getCenter

public void setRotation(float angle)

Set the orientation of the view.

The default rotation of a view is 0 degree.

Parameters

  • angle New angle, in degrees

See also: getRotation

public void setViewport(const FloatRect & viewport)

Set the target viewport.

The viewport is the rectangle into which the contents of the view are displayed, expressed as a factor (between 0 and 1) of the size of the RenderTarget to which the view is applied. For example, a view which takes the left side of the target would be defined with View.setViewport(sf::FloatRect(0, 0, 0.5, 1)). By default, a view has a viewport which covers the entire target.

Parameters

  • viewport New viewport rectangle

See also: getViewport

public void reset(const FloatRect & rectangle)

Reset the view to the given rectangle.

Note that this function resets the rotation angle to 0.

Parameters

  • rectangle Rectangle defining the zone to display

See also: setCenter, setSize, setRotation

public const Vector2f&getCenter() const

Get the center of the view.

Returns

Center of the view

See also: getSize, setCenter

public const Vector2f&getSize() const

Get the size of the view.

Returns

Size of the view

See also: getCenter, setSize

public float getRotation() const

Get the current orientation of the view.

Returns

Rotation angle of the view, in degrees

See also: setRotation

public const FloatRect&getViewport() const

Get the target viewport rectangle of the view.

Returns

Viewport rectangle, expressed as a factor of the target size

See also: setViewport

public void move(float offsetX,float offsetY)

Move the view relatively to its current position.

Parameters

  • offsetX X coordinate of the move offset

  • offsetY Y coordinate of the move offset

See also: setCenter, rotate, zoom

public void move(const Vector2f & offset)

Move the view relatively to its current position.

Parameters

  • offset Move offset

See also: setCenter, rotate, zoom

public void rotate(float angle)

Rotate the view relatively to its current orientation.

Parameters

  • angle Angle to rotate, in degrees

See also: setRotation, move, zoom

public void zoom(float factor)

Resize the view rectangle relatively to its current size.

Resizing the view simulates a zoom, as the zone displayed on screen grows or shrinks. factor is a multiplier:

  • 1 keeps the size unchanged

  • 1 makes the view bigger (objects appear smaller)

  • < 1 makes the view smaller (objects appear bigger)

Parameters

  • factor Zoom factor to apply

See also: setSize, move, rotate

public const Transform&getTransform() const

Get the projection transform of the view.

This function is meant for internal use only.

Returns

Projection transform defining the view

See also: getInverseTransform

public const Transform&getInverseTransform() const

Get the inverse projection transform of the view.

This function is meant for internal use only.

Returns

Inverse of the projection transform defining the view

See also: getTransform

group network

Socket-based communication, utilities and higher-level network protocols (HTTP, FTP).

Summary

Members Descriptions
class sf::Ftp A FTP client.
class sf::Http A HTTP client.
class sf::IpAddress Encapsulate an IPv4 network address.
class sf::Packet Utility class to build blocks of data to transfer over the network.
class sf::Socket Base class for all the socket types.
class sf::SocketSelector Multiplexer that allows to read from multiple sockets.
class sf::TcpListener Socket that listens to new TCP connections.
class sf::TcpSocket Specialized socket using the TCP protocol.
class sf::UdpSocket Specialized socket using the UDP protocol.

class sf::Ftp

class sf::Ftp
  : private sf::NonCopyable

A FTP client.

sf::Ftp is a very simple FTP client that allows you to communicate with a FTP server.

The FTP protocol allows you to manipulate a remote file system (list files, upload, download, create, remove, ...).

Using the FTP client consists of 4 parts:

  • Connecting to the FTP server

  • Logging in (either as a registered user or anonymously)

  • Sending commands to the server

  • Disconnecting (this part can be done implicitly by the destructor)

Every command returns a FTP response, which contains the status code as well as a message from the server. Some commands such as getWorkingDirectory() and getDirectoryListing() return additional data, and use a class derived from sf::Ftp::Response to provide this data. The most often used commands are directly provided as member functions, but it is also possible to use specific commands with the sendCommand() function.

Note that response statuses >= 1000 are not part of the FTP standard, they are generated by SFML when an internal error occurs.

All commands, especially upload and download, may take some time to complete. This is important to know if you don't want to block your application while the server is completing the task.

Usage example:

// Create a new FTP client
sf::Ftp ftp;

// Connect to the server
sf::Ftp::Response response = ftp.connect("ftp://ftp.myserver.com");
if (response.isOk())
    std::cout << "Connected" << std::endl;

// Log in
response = ftp.login("laurent", "dF6Zm89D");
if (response.isOk())
    std::cout << "Logged in" << std::endl;

// Print the working directory
sf::Ftp::DirectoryResponse directory = ftp.getWorkingDirectory();
if (directory.isOk())
    std::cout << "Working directory: " << directory.getDirectory() << std::endl;

// Create a new directory
response = ftp.createDirectory("files");
if (response.isOk())
    std::cout << "Created new directory" << std::endl;

// Upload a file to this new directory
response = ftp.upload("local-path/file.txt", "files", sf::Ftp::Ascii);
if (response.isOk())
    std::cout << "File uploaded" << std::endl;

// Send specific commands (here: FEAT to list supported FTP features)
response = ftp.sendCommand("FEAT");
if (response.isOk())
    std::cout << "Feature list:\n" << response.getMessage() << std::endl;

// Disconnect from the server (optional)
ftp.disconnect();

Summary

Members Descriptions
public ~Ftp() Destructor.
public Response connect(const IpAddress & server,unsigned short port,Time timeout) Connect to the specified FTP server.
public Response disconnect() Close the connection with the server.
public Response login() Log in using an anonymous account.
public Response login(const std::string & name,const std::string & password) Log in using a username and a password.
public Response keepAlive() Send a null command to keep the connection alive.
public DirectoryResponse getWorkingDirectory() Get the current working directory.
public ListingResponse getDirectoryListing(const std::string & directory) Get the contents of the given directory.
public Response changeDirectory(const std::string & directory) Change the current working directory.
public Response parentDirectory() Go to the parent directory of the current one.
public Response createDirectory(const std::string & name) Create a new directory.
public Response deleteDirectory(const std::string & name) Remove an existing directory.
public Response renameFile(const std::string & file,const std::string & newName) Rename an existing file.
public Response deleteFile(const std::string & name) Remove an existing file.
public Response download(const std::string & remoteFile,const std::string & localPath,TransferMode mode) Download a file from the server.
public Response upload(const std::string & localFile,const std::string & remotePath,TransferMode mode,bool append) Upload a file to the server.
public Response sendCommand(const std::string & command,const std::string & parameter) Send a command to the FTP server.
enum TransferMode Enumeration of transfer modes.

Members

public ~Ftp()

Destructor.

Automatically closes the connection with the server if it is still opened.

public Response connect(const IpAddress & server,unsigned short port,Time timeout)

Connect to the specified FTP server.

The port has a default value of 21, which is the standard port used by the FTP protocol. You shouldn't use a different value, unless you really know what you do. This function tries to connect to the server so it may take a while to complete, especially if the server is not reachable. To avoid blocking your application for too long, you can use a timeout. The default value, Time::Zero, means that the system timeout will be used (which is usually pretty long).

Parameters

  • server Name or address of the FTP server to connect to

  • port Port used for the connection

  • timeout Maximum time to wait

Returns

Server response to the request

See also: disconnect

Close the connection with the server.

Returns

Server response to the request

See also: connect

public Response login()

Log in using an anonymous account.

Logging in is mandatory after connecting to the server. Users that are not logged in cannot perform any operation.

Returns

Server response to the request

public Response login(const std::string & name,const std::string & password)

Log in using a username and a password.

Logging in is mandatory after connecting to the server. Users that are not logged in cannot perform any operation.

Parameters

  • name User name

  • password Password

Returns

Server response to the request

Send a null command to keep the connection alive.

This command is useful because the server may close the connection automatically if no command is sent.

Returns

Server response to the request

Get the current working directory.

The working directory is the root path for subsequent operations involving directories and/or filenames.

Returns

Server response to the request

See also: getDirectoryListing, changeDirectory, parentDirectory

public ListingResponse getDirectoryListing(const std::string & directory)

Get the contents of the given directory.

This function retrieves the sub-directories and files contained in the given directory. It is not recursive. The directory parameter is relative to the current working directory.

Parameters

  • directory Directory to list

Returns

Server response to the request

See also: getWorkingDirectory, changeDirectory, parentDirectory

public Response changeDirectory(const std::string & directory)

Change the current working directory.

The new directory must be relative to the current one.

Parameters

  • directory New working directory

Returns

Server response to the request

See also: getWorkingDirectory, getDirectoryListing, parentDirectory

Go to the parent directory of the current one.

Returns

Server response to the request

See also: getWorkingDirectory, getDirectoryListing, changeDirectory

public Response createDirectory(const std::string & name)

Create a new directory.

The new directory is created as a child of the current working directory.

Parameters

  • name Name of the directory to create

Returns

Server response to the request

See also: deleteDirectory

public Response deleteDirectory(const std::string & name)

Remove an existing directory.

The directory to remove must be relative to the current working directory. Use this function with caution, the directory will be removed permanently!

Parameters

  • name Name of the directory to remove

Returns

Server response to the request

See also: createDirectory

public Response renameFile(const std::string & file,const std::string & newName)

Rename an existing file.

The filenames must be relative to the current working directory.

Parameters

  • file File to rename

  • newName New name of the file

Returns

Server response to the request

See also: deleteFile

public Response deleteFile(const std::string & name)

Remove an existing file.

The file name must be relative to the current working directory. Use this function with caution, the file will be removed permanently!

Parameters

  • name File to remove

Returns

Server response to the request

See also: renameFile

public Response download(const std::string & remoteFile,const std::string & localPath,TransferMode mode)

Download a file from the server.

The filename of the distant file is relative to the current working directory of the server, and the local destination path is relative to the current directory of your application. If a file with the same filename as the distant file already exists in the local destination path, it will be overwritten.

Parameters

  • remoteFile Filename of the distant file to download

  • localPath The directory in which to put the file on the local computer

  • mode Transfer mode

Returns

Server response to the request

See also: upload

public Response upload(const std::string & localFile,const std::string & remotePath,TransferMode mode,bool append)

Upload a file to the server.

The name of the local file is relative to the current working directory of your application, and the remote path is relative to the current directory of the FTP server.

The append parameter controls whether the remote file is appended to or overwritten if it already exists.

Parameters

  • localFile Path of the local file to upload

  • remotePath The directory in which to put the file on the server

  • mode Transfer mode

  • append Pass true to append to or false to overwrite the remote file if it already exists

Returns

Server response to the request

See also: download

public Response sendCommand(const std::string & command,const std::string & parameter)

Send a command to the FTP server.

While the most often used commands are provided as member functions in the sf::Ftp class, this method can be used to send any FTP command to the server. If the command requires one or more parameters, they can be specified in parameter. If the server returns information, you can extract it from the response using Response::getMessage().

Parameters

  • command Command to send

  • parameter Command parameter

Returns

Server response to the request

Values Descriptions
Binary Binary mode (file is transfered as a sequence of bytes)
Ascii Text mode using ASCII encoding.
Ebcdic Text mode using EBCDIC encoding.

Enumeration of transfer modes.

class sf::Http

class sf::Http
  : private sf::NonCopyable

A HTTP client.

sf::Http is a very simple HTTP client that allows you to communicate with a web server.

You can retrieve web pages, send data to an interactive resource, download a remote file, etc. The HTTPS protocol is not supported.

The HTTP client is split into 3 classes:

sf::Http::Request builds the request that will be sent to the server. A request is made of:

  • a method (what you want to do)

  • a target URI (usually the name of the web page or file)

  • one or more header fields (options that you can pass to the server)

  • an optional body (for POST requests)

sf::Http::Response parse the response from the web server and provides getters to read them. The response contains:

  • a status code

  • header fields (that may be answers to the ones that you requested)

  • a body, which contains the contents of the requested resource

sf::Http provides a simple function, SendRequest, to send a sf::Http::Request and return the corresponding sf::Http::Response from the server.

Usage example:

// Create a new HTTP client
sf::Http http;

// We'll work on http://www.sfml-dev.org
http.setHost("http://www.sfml-dev.org");

// Prepare a request to get the 'features.php' page
sf::Http::Request request("features.php");

// Send the request
sf::Http::Response response = http.sendRequest(request);

// Check the status code and display the result
sf::Http::Response::Status status = response.getStatus();
if (status == sf::Http::Response::Ok)
{
    std::cout << response.getBody() << std::endl;
}
else
{
    std::cout << "Error " << status << std::endl;
}

Summary

Members Descriptions
public Http() Default constructor.
public Http(const std::string & host,unsigned short port) Construct the HTTP client with the target host.
public void setHost(const std::string & host,unsigned short port) Set the target host.
public Response sendRequest(const Request & request,Time timeout) Send a HTTP request and return the server's response.

Members

public Http()

Default constructor.

public Http(const std::string & host,unsigned short port)

Construct the HTTP client with the target host.

This is equivalent to calling setHost(host, port). The port has a default value of 0, which means that the HTTP client will use the right port according to the protocol used (80 for HTTP). You should leave it like this unless you really need a port other than the standard one, or use an unknown protocol.

Parameters

  • host Web server to connect to

  • port Port to use for connection

public void setHost(const std::string & host,unsigned short port)

Set the target host.

This function just stores the host address and port, it doesn't actually connect to it until you send a request. The port has a default value of 0, which means that the HTTP client will use the right port according to the protocol used (80 for HTTP). You should leave it like this unless you really need a port other than the standard one, or use an unknown protocol.

Parameters

  • host Web server to connect to

  • port Port to use for connection

public Response sendRequest(const Request & request,Time timeout)

Send a HTTP request and return the server's response.

You must have a valid host before sending a request (see setHost). Any missing mandatory header field in the request will be added with an appropriate value. Warning: this function waits for the server's response and may not return instantly; use a thread if you don't want to block your application, or use a timeout to limit the time to wait. A value of Time::Zero means that the client will use the system default timeout (which is usually pretty long).

Parameters

  • request Request to send

  • timeout Maximum time to wait

Returns

Server's response

class sf::IpAddress

Encapsulate an IPv4 network address.

sf::IpAddress is a utility class for manipulating network addresses.

It provides a set a implicit constructors and conversion functions to easily build or transform an IP address from/to various representations.

Usage example:

sf::IpAddress a0;                                     // an invalid address
sf::IpAddress a1 = sf::IpAddress::None;               // an invalid address (same as a0)
sf::IpAddress a2("127.0.0.1");                        // the local host address
sf::IpAddress a3 = sf::IpAddress::Broadcast;          // the broadcast address
sf::IpAddress a4(192, 168, 1, 56);                    // a local address
sf::IpAddress a5("my_computer");                      // a local address created from a network name
sf::IpAddress a6("89.54.1.169");                      // a distant address
sf::IpAddress a7("www.google.com");                   // a distant address created from a network name
sf::IpAddress a8 = sf::IpAddress::getLocalAddress();  // my address on the local network
sf::IpAddress a9 = sf::IpAddress::getPublicAddress(); // my address on the internet

Note that sf::IpAddress currently doesn't support IPv6 nor other types of network addresses.

Summary

Members Descriptions
public IpAddress() Default constructor.
public IpAddress(const std::string & address) Construct the address from a string.
public IpAddress(const char * address) Construct the address from a string.
public IpAddress(Uint8 byte0,Uint8 byte1,Uint8 byte2,Uint8 byte3) Construct the address from 4 bytes.
public explicit IpAddress(Uint32 address) Construct the address from a 32-bits integer.
public std::string toString() const Get a string representation of the address.
public Uint32 toInteger() const Get an integer representation of the address.

Members

public IpAddress()

Default constructor.

This constructor creates an empty (invalid) address

public IpAddress(const std::string & address)

Construct the address from a string.

Here address can be either a decimal address (ex: "192.168.1.56") or a network name (ex: "localhost").

Parameters

  • address IP address or network name

public IpAddress(const char * address)

Construct the address from a string.

Here address can be either a decimal address (ex: "192.168.1.56") or a network name (ex: "localhost"). This is equivalent to the constructor taking a std::string parameter, it is defined for convenience so that the implicit conversions from literal strings to IpAddress work.

Parameters

  • address IP address or network name

public IpAddress(Uint8 byte0,Uint8 byte1,Uint8 byte2,Uint8 byte3)

Construct the address from 4 bytes.

Calling IpAddress(a, b, c, d) is equivalent to calling IpAddress("a.b.c.d"), but safer as it doesn't have to parse a string to get the address components.

Parameters

  • byte0 First byte of the address

  • byte1 Second byte of the address

  • byte2 Third byte of the address

  • byte3 Fourth byte of the address

public explicit IpAddress(Uint32 address)

Construct the address from a 32-bits integer.

This constructor uses the internal representation of the address directly. It should be used for optimization purposes, and only if you got that representation from IpAddress::toInteger().

Parameters

  • address 4 bytes of the address packed into a 32-bits integer

See also: toInteger

public std::string toString() const

Get a string representation of the address.

The returned string is the decimal representation of the IP address (like "192.168.1.56"), even if it was constructed from a host name.

Returns

String representation of the address

See also: toInteger

public Uint32 toInteger() const

Get an integer representation of the address.

The returned number is the internal representation of the address, and should be used for optimization purposes only (like sending the address through a socket). The integer produced by this function can then be converted back to a sf::IpAddress with the proper constructor.

Returns

32-bits unsigned integer representation of the address

See also: toString

class sf::Packet

Utility class to build blocks of data to transfer over the network.

Packets provide a safe and easy way to serialize data, in order to send it over the network using sockets (sf::TcpSocket, sf::UdpSocket).

Packets solve 2 fundamental problems that arise when transferring data over the network:

  • data is interpreted correctly according to the endianness

  • the bounds of the packet are preserved (one send == one receive)

The sf::Packet class provides both input and output modes. It is designed to follow the behavior of standard C++ streams, using operators >> and << to extract and insert data.

It is recommended to use only fixed-size types (like sf::Int32, etc.), to avoid possible differences between the sender and the receiver. Indeed, the native C++ types may have different sizes on two platforms and your data may be corrupted if that happens.

Usage example:

sf::Uint32 x = 24;
std::string s = "hello";
double d = 5.89;

// Group the variables to send into a packet
sf::Packet packet;
packet << x << s << d;

// Send it over the network (socket is a valid sf::TcpSocket)
socket.send(packet);

-----------------------------------------------------------------

// Receive the packet at the other end
sf::Packet packet;
socket.receive(packet);

// Extract the variables contained in the packet
sf::Uint32 x;
std::string s;
double d;
if (packet >> x >> s >> d)
{
    // Data extracted successfully...
}

Packets have built-in operator >> and << overloads for standard types:

  • bool

  • fixed-size integer types (sf::Int8/16/32, sf::Uint8/16/32)

  • floating point numbers (float, double)

  • string types (char*, wchar_t*, std::string, std::wstring, sf::String)

Like standard streams, it is also possible to define your own overloads of operators >> and << in order to handle your custom types.

struct MyStruct
{
    float       number;
    sf::Int8    integer;
    std::string str;
};

sf::Packet& operator <<(sf::Packet& packet, const MyStruct& m)
{
    return packet << m.number << m.integer << m.str;
}

sf::Packet& operator >>(sf::Packet& packet, MyStruct& m)
{
    return packet >> m.number >> m.integer >> m.str;
}

Packets also provide an extra feature that allows to apply custom transformations to the data before it is sent, and after it is received. This is typically used to handle automatic compression or encryption of the data. This is achieved by inheriting from sf::Packet, and overriding the onSend and onReceive functions.

Here is an example:

class ZipPacket : public sf::Packet
{
    virtual const void* onSend(std::size_t& size)
    {
        const void* srcData = getData();
        std::size_t srcSize = getDataSize();

        return MySuperZipFunction(srcData, srcSize, &size);
    }

    virtual void onReceive(const void* data, std::size_t size)
    {
        std::size_t dstSize;
        const void* dstData = MySuperUnzipFunction(data, size, &dstSize);

        append(dstData, dstSize);
    }
};

// Use like regular packets:
ZipPacket packet;
packet << x << s << d;
...

See also: sf::TcpSocket, sf::UdpSocket

Summary

Members Descriptions
public Packet() Default constructor.
public virtual ~Packet() Virtual destructor.
public void append(const void * data,std::size_t sizeInBytes) Append data to the end of the packet.
public void clear() Clear the packet.
public const void * getData() const Get a pointer to the data contained in the packet.
public std::size_t getDataSize() const Get the size of the data contained in the packet.
public bool endOfPacket() const Tell if the reading position has reached the end of the packet.
public operator BoolType() const Test the validity of the packet, for reading.
public Packet&operator>>(bool & data) Overloads of operator >> to read data from the packet.
public Packet&operator>>(Int8 & data)
public Packet&operator>>(Uint8 & data)
public Packet&operator>>(Int16 & data)
public Packet&operator>>(Uint16 & data)
public Packet&operator>>(Int32 & data)
public Packet&operator>>(Uint32 & data)
public Packet&operator>>(Int64 & data)
public Packet&operator>>(Uint64 & data)
public Packet&operator>>(float & data)
public Packet&operator>>(double & data)
public Packet&operator>>(char * data)
public Packet&operator>>(std::string & data)
public Packet&operator>>(wchar_t * data)
public Packet&operator>>(std::wstring & data)
public Packet&operator>>(String & data)
public Packet&operator<<(bool data) Overloads of operator << to write data into the packet.
public Packet&operator<<(Int8 data)
public Packet&operator<<(Uint8 data)
public Packet&operator<<(Int16 data)
public Packet&operator<<(Uint16 data)
public Packet&operator<<(Int32 data)
public Packet&operator<<(Uint32 data)
public Packet&operator<<(Int64 data)
public Packet&operator<<(Uint64 data)
public Packet&operator<<(float data)
public Packet&operator<<(double data)
public Packet&operator<<(const char * data)
public Packet&operator<<(const std::string & data)
public Packet&operator<<(const wchar_t * data)
public Packet&operator<<(const std::wstring & data)
public Packet&operator<<(const String & data)
protected virtual const void * onSend(std::size_t & size) Called before the packet is sent over the network.
protected virtual void onReceive(const void * data,std::size_t size) Called after the packet is received over the network.

Members

public Packet()

Default constructor.

Creates an empty packet.

public virtual ~Packet()

Virtual destructor.

public void append(const void * data,std::size_t sizeInBytes)

Append data to the end of the packet.

Parameters

  • data Pointer to the sequence of bytes to append

  • sizeInBytes Number of bytes to append

See also: clear

public void clear()

Clear the packet.

After calling Clear, the packet is empty.

See also: append

public const void * getData() const

Get a pointer to the data contained in the packet.

Warning: the returned pointer may become invalid after you append data to the packet, therefore it should never be stored. The return pointer is NULL if the packet is empty.

Returns

Pointer to the data

See also: getDataSize

public std::size_t getDataSize() const

Get the size of the data contained in the packet.

This function returns the number of bytes pointed to by what getData returns.

Returns

Data size, in bytes

See also: getData

public bool endOfPacket() const

Tell if the reading position has reached the end of the packet.

This function is useful to know if there is some data left to be read, without actually reading it.

Returns

True if all data was read, false otherwise

See also: operator bool

public operator BoolType() const

Test the validity of the packet, for reading.

This operator allows to test the packet as a boolean variable, to check if a reading operation was successful.

A packet will be in an invalid state if it has no more data to read.

This behavior is the same as standard C++ streams.

Usage example:

float x;
packet >> x;
if (packet)
{
   // ok, x was extracted successfully
}

// -- or --

float x;
if (packet >> x)
{
   // ok, x was extracted successfully
}

Don't focus on the return type, it's equivalent to bool but it disallows unwanted implicit conversions to integer or pointer types.

Returns

True if last data extraction from packet was successful

See also: endOfPacket

public Packet&operator>>(bool & data)

Overloads of operator >> to read data from the packet.

public Packet&operator>>(Int8 & data)

public Packet&operator>>(Uint8 & data)

public Packet&operator>>(Int16 & data)

public Packet&operator>>(Uint16 & data)

public Packet&operator>>(Int32 & data)

public Packet&operator>>(Uint32 & data)

public Packet&operator>>(Int64 & data)

public Packet&operator>>(Uint64 & data)

public Packet&operator>>(float & data)

public Packet&operator>>(double & data)

public Packet&operator>>(char * data)

public Packet&operator>>(std::string & data)

public Packet&operator>>(wchar_t * data)

public Packet&operator>>(std::wstring & data)

public Packet&operator>>(String & data)

public Packet&operator<<(bool data)

Overloads of operator << to write data into the packet.

public Packet&operator<<(Int8 data)

public Packet&operator<<(Uint8 data)

public Packet&operator<<(Int16 data)

public Packet&operator<<(Uint16 data)

public Packet&operator<<(Int32 data)

public Packet&operator<<(Uint32 data)

public Packet&operator<<(Int64 data)

public Packet&operator<<(Uint64 data)

public Packet&operator<<(float data)

public Packet&operator<<(double data)

public Packet&operator<<(const char * data)

public Packet&operator<<(const std::string & data)

public Packet&operator<<(const wchar_t * data)

public Packet&operator<<(const std::wstring & data)

public Packet&operator<<(const String & data)

protected virtual const void * onSend(std::size_t & size)

Called before the packet is sent over the network.

This function can be defined by derived classes to transform the data before it is sent; this can be used for compression, encryption, etc. The function must return a pointer to the modified data, as well as the number of bytes pointed. The default implementation provides the packet's data without transforming it.

Parameters

  • size Variable to fill with the size of data to send

Returns

Pointer to the array of bytes to send

See also: onReceive

protected virtual void onReceive(const void * data,std::size_t size)

Called after the packet is received over the network.

This function can be defined by derived classes to transform the data after it is received; this can be used for decompression, decryption, etc. The function receives a pointer to the received data, and must fill the packet with the transformed bytes. The default implementation fills the packet directly without transforming the data.

Parameters

  • data Pointer to the received bytes

  • size Number of bytes

See also: onSend

class sf::Socket

class sf::Socket
  : private sf::NonCopyable

Base class for all the socket types.

This class mainly defines internal stuff to be used by derived classes.

The only public features that it defines, and which is therefore common to all the socket classes, is the blocking state. All sockets can be set as blocking or non-blocking.

In blocking mode, socket functions will hang until the operation completes, which means that the entire program (well, in fact the current thread if you use multiple ones) will be stuck waiting for your socket operation to complete.

In non-blocking mode, all the socket functions will return immediately. If the socket is not ready to complete the requested operation, the function simply returns the proper status code (Socket::NotReady).

The default mode, which is blocking, is the one that is generally used, in combination with threads or selectors. The non-blocking mode is rather used in real-time applications that run an endless loop that can poll the socket often enough, and cannot afford blocking this loop.

See also: sf::TcpListener, sf::TcpSocket, sf::UdpSocket

Summary

Members Descriptions
public virtual ~Socket() Destructor.
public void setBlocking(bool blocking) Set the blocking state of the socket.
public bool isBlocking() const Tell whether the socket is in blocking or non-blocking mode.
protected Socket(Type type) Default constructor.
protected SocketHandle getHandle() const Return the internal handle of the socket.
protected void create() Create the internal representation of the socket.
protected void create(SocketHandle handle) Create the internal representation of the socket from a socket handle.
protected void close() Close the socket gracefully.
enum Status Status codes that may be returned by socket functions.
enum @3 Some special values used by sockets.

Members

public virtual ~Socket()

Destructor.

public void setBlocking(bool blocking)

Set the blocking state of the socket.

In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.

Parameters

  • blocking True to set the socket as blocking, false for non-blocking

See also: isBlocking

public bool isBlocking() const

Tell whether the socket is in blocking or non-blocking mode.

Returns

True if the socket is blocking, false otherwise

See also: setBlocking

protected Socket(Type type)

Default constructor.

This constructor can only be accessed by derived classes.

Parameters

  • type Type of the socket (TCP or UDP)

protected SocketHandle getHandle() const

Return the internal handle of the socket.

The returned handle may be invalid if the socket was not created yet (or already destroyed). This function can only be accessed by derived classes.

Returns

The internal (OS-specific) handle of the socket

protected void create()

Create the internal representation of the socket.

This function can only be accessed by derived classes.

protected void create(SocketHandle handle)

Create the internal representation of the socket from a socket handle.

This function can only be accessed by derived classes.

Parameters

  • handle OS-specific handle of the socket to wrap

protected void close()

Close the socket gracefully.

This function can only be accessed by derived classes.

enum Status

Values Descriptions
Done The socket has sent / received the data.
NotReady The socket is not ready to send / receive data yet.
Partial The socket sent a part of the data.
Disconnected The TCP socket has been disconnected.
Error An unexpected error happened.

Status codes that may be returned by socket functions.

enum @3

Values Descriptions
AnyPort Special value that tells the system to pick any available port.

Some special values used by sockets.

class sf::SocketSelector

Multiplexer that allows to read from multiple sockets.

Socket selectors provide a way to wait until some data is available on a set of sockets, instead of just one.

This is convenient when you have multiple sockets that may possibly receive data, but you don't know which one will be ready first. In particular, it avoids to use a thread for each socket; with selectors, a single thread can handle all the sockets.

All types of sockets can be used in a selector:

A selector doesn't store its own copies of the sockets (socket classes are not copyable anyway), it simply keeps a reference to the original sockets that you pass to the "add" function. Therefore, you can't use the selector as a socket container, you must store them outside and make sure that they are alive as long as they are used in the selector.

Using a selector is simple:

  • populate the selector with all the sockets that you want to observe

  • make it wait until there is data available on any of the sockets

  • test each socket to find out which ones are ready

Usage example:

// Create a socket to listen to new connections
sf::TcpListener listener;
listener.listen(55001);

// Create a list to store the future clients
std::list<sf::TcpSocket*> clients;

// Create a selector
sf::SocketSelector selector;

// Add the listener to the selector
selector.add(listener);

// Endless loop that waits for new connections
while (running)
{
    // Make the selector wait for data on any socket
    if (selector.wait())
    {
        // Test the listener
        if (selector.isReady(listener))
        {
            // The listener is ready: there is a pending connection
            sf::TcpSocket* client = new sf::TcpSocket;
            if (listener.accept(*client) == sf::Socket::Done)
            {
                // Add the new client to the clients list
                clients.push_back(client);

                // Add the new client to the selector so that we will
                // be notified when he sends something
                selector.add(*client);
            }
            else
            {
                // Error, we won't get a new connection, delete the socket
                delete client;
            }
        }
        else
        {
            // The listener socket is not ready, test all other sockets (the clients)
            for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it)
            {
                sf::TcpSocket& client = **it;
                if (selector.isReady(client))
                {
                    // The client has sent some data, we can receive it
                    sf::Packet packet;
                    if (client.receive(packet) == sf::Socket::Done)
                    {
                        ...
                    }
                }
            }
        }
    }
}

See also: sf::Socket

Summary

Members Descriptions
public SocketSelector() Default constructor.
public SocketSelector(const SocketSelector & copy) Copy constructor.
public ~SocketSelector() Destructor.
public void add(Socket & socket) Add a new socket to the selector.
public void remove(Socket & socket) Remove a socket from the selector.
public void clear() Remove all the sockets stored in the selector.
public bool wait(Time timeout) Wait until one or more sockets are ready to receive.
public bool isReady(Socket & socket) const Test a socket to know if it is ready to receive data.
public SocketSelector&operator=(const SocketSelector & right) Overload of assignment operator.

Members

Default constructor.

public SocketSelector(const SocketSelector & copy)

Copy constructor.

Parameters

  • copy Instance to copy

Destructor.

public void add(Socket & socket)

Add a new socket to the selector.

This function keeps a weak reference to the socket, so you have to make sure that the socket is not destroyed while it is stored in the selector. This function does nothing if the socket is not valid.

Parameters

  • socket Reference to the socket to add

See also: remove, clear

public void remove(Socket & socket)

Remove a socket from the selector.

This function doesn't destroy the socket, it simply removes the reference that the selector has to it.

Parameters

  • socket Reference to the socket to remove

See also: add, clear

public void clear()

Remove all the sockets stored in the selector.

This function doesn't destroy any instance, it simply removes all the references that the selector has to external sockets.

See also: add, remove

public bool wait(Time timeout)

Wait until one or more sockets are ready to receive.

This function returns as soon as at least one socket has some data available to be received. To know which sockets are ready, use the isReady function. If you use a timeout and no socket is ready before the timeout is over, the function returns false.

Parameters

  • timeout Maximum time to wait, (use Time::Zero for infinity)

Returns

True if there are sockets ready, false otherwise

See also: isReady

public bool isReady(Socket & socket) const

Test a socket to know if it is ready to receive data.

This function must be used after a call to Wait, to know which sockets are ready to receive data. If a socket is ready, a call to receive will never block because we know that there is data available to read. Note that if this function returns true for a TcpListener, this means that it is ready to accept a new connection.

Parameters

Returns

True if the socket is ready to read, false otherwise

See also: isReady

Overload of assignment operator.

Parameters

  • right Instance to assign

Returns

Reference to self

class sf::TcpListener

class sf::TcpListener
  : public sf::Socket

Socket that listens to new TCP connections.

A listener socket is a special type of socket that listens to a given port and waits for connections on that port.

This is all it can do.

When a new connection is received, you must call accept and the listener returns a new instance of sf::TcpSocket that is properly initialized and can be used to communicate with the new client.

Listener sockets are specific to the TCP protocol, UDP sockets are connectionless and can therefore communicate directly. As a consequence, a listener socket will always return the new connections as sf::TcpSocket instances.

A listener is automatically closed on destruction, like all other types of socket. However if you want to stop listening before the socket is destroyed, you can call its close() function.

Usage example:

// Create a listener socket and make it wait for new
// connections on port 55001
sf::TcpListener listener;
listener.listen(55001);

// Endless loop that waits for new connections
while (running)
{
    sf::TcpSocket client;
    if (listener.accept(client) == sf::Socket::Done)
    {
        // A new client just connected!
        std::cout << "New connection received from " << client.getRemoteAddress() << std::endl;
        doSomethingWith(client);
    }
}

See also: sf::TcpSocket, sf::Socket

Summary

Members Descriptions
public TcpListener() Default constructor.
public unsigned short getLocalPort() const Get the port to which the socket is bound locally.
public Status listen(unsigned short port,const IpAddress & address) Start listening for connections.
public void close() Stop listening and close the socket.
public Status accept(TcpSocket & socket) Accept a new connection.
public void setBlocking(bool blocking) Set the blocking state of the socket.
public bool isBlocking() const Tell whether the socket is in blocking or non-blocking mode.
protected SocketHandle getHandle() const Return the internal handle of the socket.
protected void create() Create the internal representation of the socket.
protected void create(SocketHandle handle) Create the internal representation of the socket from a socket handle.
enum Status Status codes that may be returned by socket functions.
enum @3 Some special values used by sockets.

Members

public TcpListener()

Default constructor.

public unsigned short getLocalPort() const

Get the port to which the socket is bound locally.

If the socket is not listening to a port, this function returns 0.

Returns

Port to which the socket is bound

See also: listen

public Status listen(unsigned short port,const IpAddress & address)

Start listening for connections.

This functions makes the socket listen to the specified port, waiting for new connections. If the socket was previously listening to another port, it will be stopped first and bound to the new port.

Parameters

  • port Port to listen for new connections

  • address Address of the interface to listen on

Returns

Status code

See also: accept, close

public void close()

Stop listening and close the socket.

This function gracefully stops the listener. If the socket is not listening, this function has no effect.

See also: listen

public Status accept(TcpSocket & socket)

Accept a new connection.

If the socket is in blocking mode, this function will not return until a connection is actually received.

Parameters

  • socket Socket that will hold the new connection

Returns

Status code

See also: listen

public void setBlocking(bool blocking)

Set the blocking state of the socket.

In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.

Parameters

  • blocking True to set the socket as blocking, false for non-blocking

See also: isBlocking

public bool isBlocking() const

Tell whether the socket is in blocking or non-blocking mode.

Returns

True if the socket is blocking, false otherwise

See also: setBlocking

protected SocketHandle getHandle() const

Return the internal handle of the socket.

The returned handle may be invalid if the socket was not created yet (or already destroyed). This function can only be accessed by derived classes.

Returns

The internal (OS-specific) handle of the socket

protected void create()

Create the internal representation of the socket.

This function can only be accessed by derived classes.

protected void create(SocketHandle handle)

Create the internal representation of the socket from a socket handle.

This function can only be accessed by derived classes.

Parameters

  • handle OS-specific handle of the socket to wrap

enum Status

Values Descriptions
Done The socket has sent / received the data.
NotReady The socket is not ready to send / receive data yet.
Partial The socket sent a part of the data.
Disconnected The TCP socket has been disconnected.
Error An unexpected error happened.

Status codes that may be returned by socket functions.

enum @3

Values Descriptions
AnyPort Special value that tells the system to pick any available port.

Some special values used by sockets.

class sf::TcpSocket

class sf::TcpSocket
  : public sf::Socket

Specialized socket using the TCP protocol.

TCP is a connected protocol, which means that a TCP socket can only communicate with the host it is connected to.

It can't send or receive anything if it is not connected.

The TCP protocol is reliable but adds a slight overhead. It ensures that your data will always be received in order and without errors (no data corrupted, lost or duplicated).

When a socket is connected to a remote host, you can retrieve informations about this host with the getRemoteAddress and getRemotePort functions. You can also get the local port to which the socket is bound (which is automatically chosen when the socket is connected), with the getLocalPort function.

Sending and receiving data can use either the low-level or the high-level functions. The low-level functions process a raw sequence of bytes, and cannot ensure that one call to Send will exactly match one call to Receive at the other end of the socket.

The high-level interface uses packets (see sf::Packet), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the sf::Packet class to get more details about how they work.

The socket is automatically disconnected when it is destroyed, but if you want to explicitly close the connection while the socket instance is still alive, you can call disconnect.

Usage example:

// ----- The client -----

// Create a socket and connect it to 192.168.1.50 on port 55001
sf::TcpSocket socket;
socket.connect("192.168.1.50", 55001);

// Send a message to the connected host
std::string message = "Hi, I am a client";
socket.send(message.c_str(), message.size() + 1);

// Receive an answer from the server
char buffer[1024];
std::size_t received = 0;
socket.receive(buffer, sizeof(buffer), received);
std::cout << "The server said: " << buffer << std::endl;

// ----- The server -----

// Create a listener to wait for incoming connections on port 55001
sf::TcpListener listener;
listener.listen(55001);

// Wait for a connection
sf::TcpSocket socket;
listener.accept(socket);
std::cout << "New client connected: " << socket.getRemoteAddress() << std::endl;

// Receive a message from the client
char buffer[1024];
std::size_t received = 0;
socket.receive(buffer, sizeof(buffer), received);
std::cout << "The client said: " << buffer << std::endl;

// Send an answer
std::string message = "Welcome, client";
socket.send(message.c_str(), message.size() + 1);

See also: sf::Socket, sf::UdpSocket, sf::Packet

Summary

Members Descriptions
public TcpSocket() Default constructor.
public unsigned short getLocalPort() const Get the port to which the socket is bound locally.
public IpAddress getRemoteAddress() const Get the address of the connected peer.
public unsigned short getRemotePort() const Get the port of the connected peer to which the socket is connected.
public Status connect(const IpAddress & remoteAddress,unsigned short remotePort,Time timeout) Connect the socket to a remote peer.
public void disconnect() Disconnect the socket from its remote peer.
public Status send(const void * data,std::size_t size) Send raw data to the remote peer.
public Status send(const void * data,std::size_t size,std::size_t & sent) Send raw data to the remote peer.
public Status receive(void * data,std::size_t size,std::size_t & received) Receive raw data from the remote peer.
public Status send(Packet & packet) Send a formatted packet of data to the remote peer.
public Status receive(Packet & packet) Receive a formatted packet of data from the remote peer.
public void setBlocking(bool blocking) Set the blocking state of the socket.
public bool isBlocking() const Tell whether the socket is in blocking or non-blocking mode.
protected SocketHandle getHandle() const Return the internal handle of the socket.
protected void create() Create the internal representation of the socket.
protected void create(SocketHandle handle) Create the internal representation of the socket from a socket handle.
protected void close() Close the socket gracefully.
enum Status Status codes that may be returned by socket functions.
enum @3 Some special values used by sockets.

Members

public TcpSocket()

Default constructor.

public unsigned short getLocalPort() const

Get the port to which the socket is bound locally.

If the socket is not connected, this function returns 0.

Returns

Port to which the socket is bound

See also: connect, getRemotePort

Get the address of the connected peer.

It the socket is not connected, this function returns sf::IpAddress::None.

Returns

Address of the remote peer

See also: getRemotePort

public unsigned short getRemotePort() const

Get the port of the connected peer to which the socket is connected.

If the socket is not connected, this function returns 0.

Returns

Remote port to which the socket is connected

See also: getRemoteAddress

public Status connect(const IpAddress & remoteAddress,unsigned short remotePort,Time timeout)

Connect the socket to a remote peer.

In blocking mode, this function may take a while, especially if the remote peer is not reachable. The last parameter allows you to stop trying to connect after a given timeout. If the socket was previously connected, it is first disconnected.

Parameters

  • remoteAddress Address of the remote peer

  • remotePort Port of the remote peer

  • timeout Optional maximum time to wait

Returns

Status code

See also: disconnect

public void disconnect()

Disconnect the socket from its remote peer.

This function gracefully closes the connection. If the socket is not connected, this function has no effect.

See also: connect

public Status send(const void * data,std::size_t size)

Send raw data to the remote peer.

To be able to handle partial sends over non-blocking sockets, use the send(const void*, std::size_t, std::size_t&) overload instead. This function will fail if the socket is not connected.

Parameters

  • data Pointer to the sequence of bytes to send

  • size Number of bytes to send

Returns

Status code

See also: receive

public Status send(const void * data,std::size_t size,std::size_t & sent)

Send raw data to the remote peer.

This function will fail if the socket is not connected.

Parameters

  • data Pointer to the sequence of bytes to send

  • size Number of bytes to send

  • sent The number of bytes sent will be written here

Returns

Status code

See also: receive

public Status receive(void * data,std::size_t size,std::size_t & received)

Receive raw data from the remote peer.

In blocking mode, this function will wait until some bytes are actually received. This function will fail if the socket is not connected.

Parameters

  • data Pointer to the array to fill with the received bytes

  • size Maximum number of bytes that can be received

  • received This variable is filled with the actual number of bytes received

Returns

Status code

See also: send

public Status send(Packet & packet)

Send a formatted packet of data to the remote peer.

In non-blocking mode, if this function returns sf::Socket::Partial, you must retry sending the same unmodified packet before sending anything else in order to guarantee the packet arrives at the remote peer uncorrupted. This function will fail if the socket is not connected.

Parameters

Returns

Status code

See also: receive

public Status receive(Packet & packet)

Receive a formatted packet of data from the remote peer.

In blocking mode, this function will wait until the whole packet has been received. This function will fail if the socket is not connected.

Parameters

  • packet Packet to fill with the received data

Returns

Status code

See also: send

public void setBlocking(bool blocking)

Set the blocking state of the socket.

In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.

Parameters

  • blocking True to set the socket as blocking, false for non-blocking

See also: isBlocking

public bool isBlocking() const

Tell whether the socket is in blocking or non-blocking mode.

Returns

True if the socket is blocking, false otherwise

See also: setBlocking

protected SocketHandle getHandle() const

Return the internal handle of the socket.

The returned handle may be invalid if the socket was not created yet (or already destroyed). This function can only be accessed by derived classes.

Returns

The internal (OS-specific) handle of the socket

protected void create()

Create the internal representation of the socket.

This function can only be accessed by derived classes.

protected void create(SocketHandle handle)

Create the internal representation of the socket from a socket handle.

This function can only be accessed by derived classes.

Parameters

  • handle OS-specific handle of the socket to wrap

protected void close()

Close the socket gracefully.

This function can only be accessed by derived classes.

enum Status

Values Descriptions
Done The socket has sent / received the data.
NotReady The socket is not ready to send / receive data yet.
Partial The socket sent a part of the data.
Disconnected The TCP socket has been disconnected.
Error An unexpected error happened.

Status codes that may be returned by socket functions.

enum @3

Values Descriptions
AnyPort Special value that tells the system to pick any available port.

Some special values used by sockets.

class sf::UdpSocket

class sf::UdpSocket
  : public sf::Socket

Specialized socket using the UDP protocol.

A UDP socket is a connectionless socket.

Instead of connecting once to a remote host, like TCP sockets, it can send to and receive from any host at any time.

It is a datagram protocol: bounded blocks of data (datagrams) are transfered over the network rather than a continuous stream of data (TCP). Therefore, one call to send will always match one call to receive (if the datagram is not lost), with the same data that was sent.

The UDP protocol is lightweight but unreliable. Unreliable means that datagrams may be duplicated, be lost or arrive reordered. However, if a datagram arrives, its data is guaranteed to be valid.

UDP is generally used for real-time communication (audio or video streaming, real-time games, etc.) where speed is crucial and lost data doesn't matter much.

Sending and receiving data can use either the low-level or the high-level functions. The low-level functions process a raw sequence of bytes, whereas the high-level interface uses packets (see sf::Packet), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the sf::Packet class to get more details about how they work.

It is important to note that UdpSocket is unable to send datagrams bigger than MaxDatagramSize. In this case, it returns an error and doesn't send anything. This applies to both raw data and packets. Indeed, even packets are unable to split and recompose data, due to the unreliability of the protocol (dropped, mixed or duplicated datagrams may lead to a big mess when trying to recompose a packet).

If the socket is bound to a port, it is automatically unbound from it when the socket is destroyed. However, you can unbind the socket explicitly with the Unbind function if necessary, to stop receiving messages or make the port available for other sockets.

Usage example:

// ----- The client -----

// Create a socket and bind it to the port 55001
sf::UdpSocket socket;
socket.bind(55001);

// Send a message to 192.168.1.50 on port 55002
std::string message = "Hi, I am " + sf::IpAddress::getLocalAddress().toString();
socket.send(message.c_str(), message.size() + 1, "192.168.1.50", 55002);

// Receive an answer (most likely from 192.168.1.50, but could be anyone else)
char buffer[1024];
std::size_t received = 0;
sf::IpAddress sender;
unsigned short port;
socket.receive(buffer, sizeof(buffer), received, sender, port);
std::cout << sender.ToString() << " said: " << buffer << std::endl;

// ----- The server -----

// Create a socket and bind it to the port 55002
sf::UdpSocket socket;
socket.bind(55002);

// Receive a message from anyone
char buffer[1024];
std::size_t received = 0;
sf::IpAddress sender;
unsigned short port;
socket.receive(buffer, sizeof(buffer), received, sender, port);
std::cout << sender.ToString() << " said: " << buffer << std::endl;

// Send an answer
std::string message = "Welcome " + sender.toString();
socket.send(message.c_str(), message.size() + 1, sender, port);

See also: sf::Socket, sf::TcpSocket, sf::Packet

Summary

Members Descriptions
public UdpSocket() Default constructor.
public unsigned short getLocalPort() const Get the port to which the socket is bound locally.
public Status bind(unsigned short port,const IpAddress & address) Bind the socket to a specific port.
public void unbind() Unbind the socket from the local port to which it is bound.
public Status send(const void * data,std::size_t size,const IpAddress & remoteAddress,unsigned short remotePort) Send raw data to a remote peer.
public Status receive(void * data,std::size_t size,std::size_t & received,IpAddress & remoteAddress,unsigned short & remotePort) Receive raw data from a remote peer.
public Status send(Packet& packet,constIpAddress & remoteAddress,unsigned short remotePort) Send a formatted packet of data to a remote peer.
public Status receive(Packet & packet,IpAddress & remoteAddress,unsigned short & remotePort) Receive a formatted packet of data from a remote peer.
public void setBlocking(bool blocking) Set the blocking state of the socket.
public bool isBlocking() const Tell whether the socket is in blocking or non-blocking mode.
protected SocketHandle getHandle() const Return the internal handle of the socket.
protected void create() Create the internal representation of the socket.
protected void create(SocketHandle handle) Create the internal representation of the socket from a socket handle.
protected void close() Close the socket gracefully.
enum @4
enum Status Status codes that may be returned by socket functions.
enum @3 Some special values used by sockets.

Members

public UdpSocket()

Default constructor.

public unsigned short getLocalPort() const

Get the port to which the socket is bound locally.

If the socket is not bound to a port, this function returns 0.

Returns

Port to which the socket is bound

See also: bind

public Status bind(unsigned short port,const IpAddress & address)

Bind the socket to a specific port.

Binding the socket to a port is necessary for being able to receive data on that port. You can use the special value Socket::AnyPort to tell the system to automatically pick an available port, and then call getLocalPort to retrieve the chosen port.

Parameters

  • port Port to bind the socket to

  • address Address of the interface to bind to

Returns

Status code

See also: unbind, getLocalPort

public void unbind()

Unbind the socket from the local port to which it is bound.

The port that the socket was previously bound to is immediately made available to the operating system after this function is called. This means that a subsequent call to bind() will be able to re-bind the port if no other process has done so in the mean time. If the socket is not bound to a port, this function has no effect.

See also: bind

public Status send(const void * data,std::size_t size,const IpAddress & remoteAddress,unsigned short remotePort)

Send raw data to a remote peer.

Make sure that size is not greater than UdpSocket::MaxDatagramSize, otherwise this function will fail and no data will be sent.

Parameters

  • data Pointer to the sequence of bytes to send

  • size Number of bytes to send

  • remoteAddress Address of the receiver

  • remotePort Port of the receiver to send the data to

Returns

Status code

See also: receive

public Status receive(void * data,std::size_t size,std::size_t & received,IpAddress & remoteAddress,unsigned short & remotePort)

Receive raw data from a remote peer.

In blocking mode, this function will wait until some bytes are actually received. Be careful to use a buffer which is large enough for the data that you intend to receive, if it is too small then an error will be returned and all the data will be lost.

Parameters

  • data Pointer to the array to fill with the received bytes

  • size Maximum number of bytes that can be received

  • received This variable is filled with the actual number of bytes received

  • remoteAddress Address of the peer that sent the data

  • remotePort Port of the peer that sent the data

Returns

Status code

See also: send

public Status send(Packet& packet,constIpAddress & remoteAddress,unsigned short remotePort)

Send a formatted packet of data to a remote peer.

Make sure that the packet size is not greater than UdpSocket::MaxDatagramSize, otherwise this function will fail and no data will be sent.

Parameters

  • packet Packet to send

  • remoteAddress Address of the receiver

  • remotePort Port of the receiver to send the data to

Returns

Status code

See also: receive

public Status receive(Packet & packet,IpAddress & remoteAddress,unsigned short & remotePort)

Receive a formatted packet of data from a remote peer.

In blocking mode, this function will wait until the whole packet has been received.

Parameters

  • packet Packet to fill with the received data

  • remoteAddress Address of the peer that sent the data

  • remotePort Port of the peer that sent the data

Returns

Status code

See also: send

public void setBlocking(bool blocking)

Set the blocking state of the socket.

In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.

Parameters

  • blocking True to set the socket as blocking, false for non-blocking

See also: isBlocking

public bool isBlocking() const

Tell whether the socket is in blocking or non-blocking mode.

Returns

True if the socket is blocking, false otherwise

See also: setBlocking

protected SocketHandle getHandle() const

Return the internal handle of the socket.

The returned handle may be invalid if the socket was not created yet (or already destroyed). This function can only be accessed by derived classes.

Returns

The internal (OS-specific) handle of the socket

protected void create()

Create the internal representation of the socket.

This function can only be accessed by derived classes.

protected void create(SocketHandle handle)

Create the internal representation of the socket from a socket handle.

This function can only be accessed by derived classes.

Parameters

  • handle OS-specific handle of the socket to wrap

protected void close()

Close the socket gracefully.

This function can only be accessed by derived classes.

enum @4

Values Descriptions
MaxDatagramSize The maximum number of bytes that can be sent in a single UDP datagram.

enum Status

Values Descriptions
Done The socket has sent / received the data.
NotReady The socket is not ready to send / receive data yet.
Partial The socket sent a part of the data.
Disconnected The TCP socket has been disconnected.
Error An unexpected error happened.

Status codes that may be returned by socket functions.

enum @3

Values Descriptions
AnyPort Special value that tells the system to pick any available port.

Some special values used by sockets.

group system

Base module of SFML, defining various utilities.

It provides vector classes, Unicode strings and conversion functions, threads and mutexes, timing classes.

Summary

Members Descriptions
public ANativeActivity * getNativeActivity() Return a pointer to the Android native activity.
public void sleep(Time duration) Make the current thread sleep for a given duration.
public std::ostream & err() Standard stream used by SFML to output warnings and errors.
class sf::Clock Utility class that measures the elapsed time.
class sf::FileInputStream Implementation of input stream based on a file.
class sf::InputStream Abstract class for custom file input streams.
class sf::Lock Automatic wrapper for locking and unlocking mutexes.
class sf::MemoryInputStream Implementation of input stream based on a memory chunk.
class sf::Mutex Blocks concurrent access to shared resources from multiple threads.
class sf::NonCopyable Utility class that makes any derived class non-copyable.
class sf::String Utility string class that automatically handles conversions between types and encodings.
class sf::Thread Utility class to manipulate threads.
class sf::ThreadLocal Defines variables with thread-local storage.
class sf::ThreadLocalPtr Pointer to a thread-local variable.
class sf::Time Represents a time value.
class sf::Utf Utility class providing generic functions for UTF conversions.
class sf::Vector2 Utility template class for manipulating 2-dimensional vectors.
class sf::Vector3 Utility template class for manipulating 3-dimensional vectors.

Members

public ANativeActivity * getNativeActivity()

Return a pointer to the Android native activity.

You shouldn't have to use this function, unless you want to implement very specific details, that SFML doesn't support, or to use a workaround for a known issue.

Returns

Pointer to Android native activity structure

Platform Limitation* This is only available on Android and to use it, you'll have to specifically include SFML/System/NativeActivity.hpp in your code.

public void sleep(Time duration)

Make the current thread sleep for a given duration.

sf::sleep is the best way to block a program or one of its threads, as it doesn't consume any CPU power.

Parameters

  • duration Time to sleep

public std::ostream & err()

Standard stream used by SFML to output warnings and errors.

By default, sf::err() outputs to the same location as std::cerr, (-> the stderr descriptor) which is the console if there's one available.

It is a standard std::ostream instance, so it supports all the insertion operations defined by the STL (operator <<, manipulators, etc.).

sf::err() can be redirected to write to another output, independently of std::cerr, by using the rdbuf() function provided by the std::ostream class.

Example:

// Redirect to a file
std::ofstream file("sfml-log.txt");
std::streambuf* previous = sf::err().rdbuf(file.rdbuf());

// Redirect to nothing
sf::err().rdbuf(NULL);

// Restore the original output
sf::err().rdbuf(previous);

Returns

Reference to std::ostream representing the SFML error stream

class sf::Clock

Utility class that measures the elapsed time.

sf::Clock is a lightweight class for measuring time.

Its provides the most precise time that the underlying OS can achieve (generally microseconds or nanoseconds). It also ensures monotonicity, which means that the returned time can never go backward, even if the system time is changed.

Usage example:

sf::Clock clock;
...
Time time1 = clock.getElapsedTime();
...
Time time2 = clock.restart();

The sf::Time value returned by the clock can then be converted to a number of seconds, milliseconds or even microseconds.

See also: sf::Time

Summary

Members Descriptions
public Clock() Default constructor.
public Time getElapsedTime() const Get the elapsed time.
public Time restart() Restart the clock.

Members

public Clock()

Default constructor.

The clock starts automatically after being constructed.

public Time getElapsedTime() const

Get the elapsed time.

This function returns the time elapsed since the last call to restart() (or the construction of the instance if restart() has not been called).

Returns

Time elapsed

public Time restart()

Restart the clock.

This function puts the time counter back to zero. It also returns the time elapsed since the clock was started.

Returns

Time elapsed

class sf::FileInputStream

class sf::FileInputStream
  : public sf::InputStream
  : private sf::NonCopyable

Implementation of input stream based on a file.

This class is a specialization of InputStream that reads from a file on disk.

It wraps a file in the common InputStream interface and therefore allows to use generic classes or functions that accept such a stream, with a file on disk as the data source.

In addition to the virtual functions inherited from InputStream, FileInputStream adds a function to specify the file to open.

SFML resource classes can usually be loaded directly from a filename, so this class shouldn't be useful to you unless you create your own algorithms that operate on an InputStream.

Usage example:

void process(InputStream& stream);

FileInputStream stream;
if (stream.open("some_file.dat"))
   process(stream);

InputStream, MemoryInputStream

Summary

Members Descriptions
public FileInputStream() Default constructor.
public virtual ~FileInputStream() Default destructor.
public bool open(const std::string & filename) Open the stream from a file path.
public virtual Int64 read(void * data,Int64 size) Read data from the stream.
public virtual Int64 seek(Int64 position) Change the current reading position.
public virtual Int64 tell() Get the current reading position in the stream.
public virtual Int64 getSize() Return the size of the stream.

Members

Default constructor.

public virtual ~FileInputStream()

Default destructor.

public bool open(const std::string & filename)

Open the stream from a file path.

Parameters

  • filename Name of the file to open

Returns

True on success, false on error

public virtual Int64 read(void * data,Int64 size)

Read data from the stream.

After reading, the stream's reading position must be advanced by the amount of bytes read.

Parameters

  • data Buffer where to copy the read data

  • size Desired number of bytes to read

Returns

The number of bytes actually read, or -1 on error

public virtual Int64 seek(Int64 position)

Change the current reading position.

Parameters

  • position The position to seek to, from the beginning

Returns

The position actually sought to, or -1 on error

public virtual Int64 tell()

Get the current reading position in the stream.

Returns

The current position, or -1 on error.

public virtual Int64 getSize()

Return the size of the stream.

Returns

The total number of bytes available in the stream, or -1 on error

class sf::InputStream

Abstract class for custom file input streams.

This class allows users to define their own file input sources from which SFML can load resources.

SFML resource classes like sf::Texture and sf::SoundBuffer provide loadFromFile and loadFromMemory functions, which read data from conventional sources. However, if you have data coming from a different source (over a network, embedded, encrypted, compressed, etc) you can derive your own class from sf::InputStream and load SFML resources with their loadFromStream function.

Usage example:

// custom stream class that reads from inside a zip file
class ZipStream : public sf::InputStream
{
public:

    ZipStream(std::string archive);

    bool open(std::string filename);

    Int64 read(void* data, Int64 size);

    Int64 seek(Int64 position);

    Int64 tell();

    Int64 getSize();

private:

    ...
};

// now you can load textures...
sf::Texture texture;
ZipStream stream("resources.zip");
stream.open("images/img.png");
texture.loadFromStream(stream);

// musics...
sf::Music music;
ZipStream stream("resources.zip");
stream.open("musics/msc.ogg");
music.openFromStream(stream);

// etc.

Summary

Members Descriptions
public inline virtual ~InputStream() Virtual destructor.
public Int64 read(void * data,Int64 size) Read data from the stream.
public Int64 seek(Int64 position) Change the current reading position.
public Int64 tell() Get the current reading position in the stream.
public Int64 getSize() Return the size of the stream.

Members

public inline virtual ~InputStream()

Virtual destructor.

public Int64 read(void * data,Int64 size)

Read data from the stream.

After reading, the stream's reading position must be advanced by the amount of bytes read.

Parameters

  • data Buffer where to copy the read data

  • size Desired number of bytes to read

Returns

The number of bytes actually read, or -1 on error

public Int64 seek(Int64 position)

Change the current reading position.

Parameters

  • position The position to seek to, from the beginning

Returns

The position actually sought to, or -1 on error

public Int64 tell()

Get the current reading position in the stream.

Returns

The current position, or -1 on error.

public Int64 getSize()

Return the size of the stream.

Returns

The total number of bytes available in the stream, or -1 on error

class sf::Lock

class sf::Lock
  : private sf::NonCopyable

Automatic wrapper for locking and unlocking mutexes.

sf::Lock is a RAII wrapper for sf::Mutex.

By unlocking it in its destructor, it ensures that the mutex will always be released when the current scope (most likely a function) ends. This is even more important when an exception or an early return statement can interrupt the execution flow of the function.

For maximum robustness, sf::Lock should always be used to lock/unlock a mutex.

Usage example:

sf::Mutex mutex;

void function()
{
    sf::Lock lock(mutex); // mutex is now locked

    functionThatMayThrowAnException(); // mutex is unlocked if this function throws

    if (someCondition)
        return; // mutex is unlocked

} // mutex is unlocked

Because the mutex is not explicitly unlocked in the code, it may remain locked longer than needed. If the region of the code that needs to be protected by the mutex is not the entire function, a good practice is to create a smaller, inner scope so that the lock is limited to this part of the code.

sf::Mutex mutex;

void function()
{
    {
      sf::Lock lock(mutex);
      codeThatRequiresProtection();

    } // mutex is unlocked here

    codeThatDoesntCareAboutTheMutex();
}

Having a mutex locked longer than required is a bad practice which can lead to bad performances. Don't forget that when a mutex is locked, other threads may be waiting doing nothing until it is released.

See also: sf::Mutex

Summary

Members Descriptions
public explicit Lock(Mutex & mutex) Construct the lock with a target mutex.
public ~Lock() Destructor.

Members

public explicit Lock(Mutex & mutex)

Construct the lock with a target mutex.

The mutex passed to sf::Lock is automatically locked.

Parameters

public ~Lock()

Destructor.

The destructor of sf::Lock automatically unlocks its mutex.

class sf::MemoryInputStream

class sf::MemoryInputStream
  : public sf::InputStream

Implementation of input stream based on a memory chunk.

This class is a specialization of InputStream that reads from data in memory.

It wraps a memory chunk in the common InputStream interface and therefore allows to use generic classes or functions that accept such a stream, with content already loaded in memory.

In addition to the virtual functions inherited from InputStream, MemoryInputStream adds a function to specify the pointer and size of the data in memory.

SFML resource classes can usually be loaded directly from memory, so this class shouldn't be useful to you unless you create your own algorithms that operate on an InputStream.

Usage example:

void process(InputStream& stream);

MemoryInputStream stream;
stream.open(thePtr, theSize);
process(stream);

InputStream, FileInputStream

Summary

Members Descriptions
public MemoryInputStream() Default constructor.
public void open(const void * data,std::size_t sizeInBytes) Open the stream from its data.
public virtual Int64 read(void * data,Int64 size) Read data from the stream.
public virtual Int64 seek(Int64 position) Change the current reading position.
public virtual Int64 tell() Get the current reading position in the stream.
public virtual Int64 getSize() Return the size of the stream.

Members

Default constructor.

public void open(const void * data,std::size_t sizeInBytes)

Open the stream from its data.

Parameters

  • data Pointer to the data in memory

  • sizeInBytes Size of the data, in bytes

public virtual Int64 read(void * data,Int64 size)

Read data from the stream.

After reading, the stream's reading position must be advanced by the amount of bytes read.

Parameters

  • data Buffer where to copy the read data

  • size Desired number of bytes to read

Returns

The number of bytes actually read, or -1 on error

public virtual Int64 seek(Int64 position)

Change the current reading position.

Parameters

  • position The position to seek to, from the beginning

Returns

The position actually sought to, or -1 on error

public virtual Int64 tell()

Get the current reading position in the stream.

Returns

The current position, or -1 on error.

public virtual Int64 getSize()

Return the size of the stream.

Returns

The total number of bytes available in the stream, or -1 on error

class sf::Mutex

class sf::Mutex
  : private sf::NonCopyable

Blocks concurrent access to shared resources from multiple threads.

Mutex stands for "MUTual EXclusion".

A mutex is a synchronization object, used when multiple threads are involved.

When you want to protect a part of the code from being accessed simultaneously by multiple threads, you typically use a mutex. When a thread is locked by a mutex, any other thread trying to lock it will be blocked until the mutex is released by the thread that locked it. This way, you can allow only one thread at a time to access a critical region of your code.

Usage example:

Database database; // this is a critical resource that needs some protection
sf::Mutex mutex;

void thread1()
{
    mutex.lock(); // this call will block the thread if the mutex is already locked by thread2
    database.write(...);
    mutex.unlock(); // if thread2 was waiting, it will now be unblocked
}

void thread2()
{
    mutex.lock(); // this call will block the thread if the mutex is already locked by thread1
    database.write(...);
    mutex.unlock(); // if thread1 was waiting, it will now be unblocked
}

Be very careful with mutexes. A bad usage can lead to bad problems, like deadlocks (two threads are waiting for each other and the application is globally stuck).

To make the usage of mutexes more robust, particularly in environments where exceptions can be thrown, you should use the helper class sf::Lock to lock/unlock mutexes.

SFML mutexes are recursive, which means that you can lock a mutex multiple times in the same thread without creating a deadlock. In this case, the first call to lock() behaves as usual, and the following ones have no effect. However, you must call unlock() exactly as many times as you called lock(). If you don't, the mutex won't be released.

See also: sf::Lock

Summary

Members Descriptions
public Mutex() Default constructor.
public ~Mutex() Destructor.
public void lock() Lock the mutex.
public void unlock() Unlock the mutex.

Members

public Mutex()

Default constructor.

public ~Mutex()

Destructor.

public void lock()

Lock the mutex.

If the mutex is already locked in another thread, this call will block the execution until the mutex is released.

See also: unlock

public void unlock()

Unlock the mutex.

See also: lock

class sf::NonCopyable

Utility class that makes any derived class non-copyable.

This class makes its instances non-copyable, by explicitly disabling its copy constructor and its assignment operator.

To create a non-copyable class, simply inherit from sf::NonCopyable.

The type of inheritance (public or private) doesn't matter, the copy constructor and assignment operator are declared private in sf::NonCopyable so they will end up being inaccessible in both cases. Thus you can use a shorter syntax for inheriting from it (see below).

Usage example:

class MyNonCopyableClass : sf::NonCopyable
{
    ...
};

Deciding whether the instances of a class can be copied or not is a very important design choice. You are strongly encouraged to think about it before writing a class, and to use sf::NonCopyable when necessary to prevent many potential future errors when using it. This is also a very important indication to users of your class.

Summary

Members Descriptions
protected inline NonCopyable() Default constructor.
protected inline ~NonCopyable() Default destructor.

Members

protected inline NonCopyable()

Default constructor.

Because this class has a copy constructor, the compiler will not automatically generate the default constructor. That's why we must define it explicitly.

protected inline ~NonCopyable()

Default destructor.

By declaring a protected destructor it's impossible to call delete on a pointer of sf::NonCopyable, thus preventing possible resource leaks.

class sf::String

Utility string class that automatically handles conversions between types and encodings.

sf::String is a utility string class defined mainly for convenience.

It is a Unicode string (implemented using UTF-32), thus it can store any character in the world (European, Chinese, Arabic, Hebrew, etc.).

It automatically handles conversions from/to ANSI and wide strings, so that you can work with standard string classes and still be compatible with functions taking a sf::String.

sf::String s;

std::string s1 = s;  // automatically converted to ANSI string
std::wstring s2 = s; // automatically converted to wide string
s = "hello";         // automatically converted from ANSI string
s = L"hello";        // automatically converted from wide string
s += 'a';            // automatically converted from ANSI string
s += L'a';           // automatically converted from wide string

Conversions involving ANSI strings use the default user locale. However it is possible to use a custom locale if necessary:

std::locale locale;
sf::String s;
...
std::string s1 = s.toAnsiString(locale);
s = sf::String("hello", locale);

sf::String defines the most important functions of the standard std::string class: removing, random access, iterating, appending, comparing, etc. However it is a simple class provided for convenience, and you may have to consider using a more optimized class if your program requires complex string handling. The automatic conversion functions will then take care of converting your string to sf::String whenever SFML requires it.

Please note that SFML also defines a low-level, generic interface for Unicode handling, see the sf::Utf classes.

Summary

Members Descriptions
public String() Default constructor.
public String(char ansiChar,const std::locale & locale) Construct from a single ANSI character and a locale.
public String(wchar_t wideChar) Construct from single wide character.
public String(Uint32 utf32Char) Construct from single UTF-32 character.
public String(const char * ansiString,const std::locale & locale) Construct from a null-terminated C-style ANSI string and a locale.
public String(const std::string & ansiString,const std::locale & locale) Construct from an ANSI string and a locale.
public String(const wchar_t * wideString) Construct from null-terminated C-style wide string.
public String(const std::wstring & wideString) Construct from a wide string.
public String(const Uint32 * utf32String) Construct from a null-terminated C-style UTF-32 string.
public String(const std::basic_string< Uint32 > & utf32String) Construct from an UTF-32 string.
public String(const String & copy) Copy constructor.
public operator std::string() const Implicit conversion operator to std::string (ANSI string)
public operator std::wstring() const Implicit conversion operator to std::wstring (wide string)
public std::string toAnsiString(const std::locale & locale) const Convert the Unicode string to an ANSI string.
public std::wstring toWideString() const Convert the Unicode string to a wide string.
public std::basic_string< Uint8 > toUtf8() const Convert the Unicode string to a UTF-8 string.
public std::basic_string< Uint16 > toUtf16() const Convert the Unicode string to a UTF-16 string.
public std::basic_string< Uint32 > toUtf32() const Convert the Unicode string to a UTF-32 string.
public String&operator=(const String & right) Overload of assignment operator.
public String&operator+=(const String & right) Overload of += operator to append an UTF-32 string.
public Uint32 operator[](std::size_t index) const Overload of [] operator to access a character by its position.
public Uint32 & operator[](std::size_t index) Overload of [] operator to access a character by its position.
public void clear() Clear the string.
public std::size_t getSize() const Get the size of the string.
public bool isEmpty() const Check whether the string is empty or not.
public void erase(std::size_t position,std::size_t count) Erase one or more characters from the string.
public void insert(std::size_t position,const String & str) Insert one or more characters into the string.
public std::size_t find(const String & str,std::size_t start) const Find a sequence of one or more characters in the string.
public void replace(std::size_t position,std::size_t length,const String & replaceWith) Replace a substring with another string.
public void replace(const String& searchFor,constString & replaceWith) Replace all occurrences of a substring with a replacement string.
public String substring(std::size_t position,std::size_t length) const Return a part of the string.
public const Uint32 * getData() const Get a pointer to the C-style array of characters.
public Iterator begin() Return an iterator to the beginning of the string.
public ConstIterator begin() const Return an iterator to the beginning of the string.
public Iterator end() Return an iterator to the end of the string.
public ConstIterator end() const Return an iterator to the end of the string.
typedef Iterator Iterator type.
typedef ConstIterator Read-only iterator type.

Members

public String()

Default constructor.

This constructor creates an empty string.

public String(char ansiChar,const std::locale & locale)

Construct from a single ANSI character and a locale.

The source character is converted to UTF-32 according to the given locale.

Parameters

  • ansiChar ANSI character to convert

  • locale Locale to use for conversion

public String(wchar_t wideChar)

Construct from single wide character.

Parameters

  • wideChar Wide character to convert

public String(Uint32 utf32Char)

Construct from single UTF-32 character.

Parameters

  • utf32Char UTF-32 character to convert

public String(const char * ansiString,const std::locale & locale)

Construct from a null-terminated C-style ANSI string and a locale.

The source string is converted to UTF-32 according to the given locale.

Parameters

  • ansiString ANSI string to convert

  • locale Locale to use for conversion

public String(const std::string & ansiString,const std::locale & locale)

Construct from an ANSI string and a locale.

The source string is converted to UTF-32 according to the given locale.

Parameters

  • ansiString ANSI string to convert

  • locale Locale to use for conversion

public String(const wchar_t * wideString)

Construct from null-terminated C-style wide string.

Parameters

  • wideString Wide string to convert

public String(const std::wstring & wideString)

Construct from a wide string.

Parameters

  • wideString Wide string to convert

public String(const Uint32 * utf32String)

Construct from a null-terminated C-style UTF-32 string.

Parameters

  • utf32String UTF-32 string to assign

public String(const std::basic_string< Uint32 > & utf32String)

Construct from an UTF-32 string.

Parameters

  • utf32String UTF-32 string to assign

public String(const String & copy)

Copy constructor.

Parameters

  • copy Instance to copy

public operator std::string() const

Implicit conversion operator to std::string (ANSI string)

The current global locale is used for conversion. If you want to explicitly specify a locale, see toAnsiString. Characters that do not fit in the target encoding are discarded from the returned string. This operator is defined for convenience, and is equivalent to calling toAnsiString().

Returns

Converted ANSI string

See also: toAnsiString, operator std::wstring

public operator std::wstring() const

Implicit conversion operator to std::wstring (wide string)

Characters that do not fit in the target encoding are discarded from the returned string. This operator is defined for convenience, and is equivalent to calling toWideString().

Returns

Converted wide string

See also: toWideString, operator std::string

public std::string toAnsiString(const std::locale & locale) const

Convert the Unicode string to an ANSI string.

The UTF-32 string is converted to an ANSI string in the encoding defined by locale. Characters that do not fit in the target encoding are discarded from the returned string.

Parameters

  • locale Locale to use for conversion

Returns

Converted ANSI string

See also: toWideString, operator std::string

public std::wstring toWideString() const

Convert the Unicode string to a wide string.

Characters that do not fit in the target encoding are discarded from the returned string.

Returns

Converted wide string

See also: toAnsiString, operator std::wstring

public std::basic_string< Uint8 > toUtf8() const

Convert the Unicode string to a UTF-8 string.

Returns

Converted UTF-8 string

See also: toUtf16, toUtf32

public std::basic_string< Uint16 > toUtf16() const

Convert the Unicode string to a UTF-16 string.

Returns

Converted UTF-16 string

See also: toUtf8, toUtf32

public std::basic_string< Uint32 > toUtf32() const

Convert the Unicode string to a UTF-32 string.

This function doesn't perform any conversion, since the string is already stored as UTF-32 internally.

Returns

Converted UTF-32 string

See also: toUtf8, toUtf16

public String&operator=(const String & right)

Overload of assignment operator.

Parameters

  • right Instance to assign

Returns

Reference to self

public String&operator+=(const String & right)

Overload of += operator to append an UTF-32 string.

Parameters

Returns

Reference to self

public Uint32 operator[](std::size_t index) const

Overload of [] operator to access a character by its position.

This function provides read-only access to characters. Note: the behavior is undefined if index is out of range.

Parameters

  • index Index of the character to get

Returns

Character at position index

public Uint32 & operator[](std::size_t index)

Overload of [] operator to access a character by its position.

This function provides read and write access to characters. Note: the behavior is undefined if index is out of range.

Parameters

  • index Index of the character to get

Returns

Reference to the character at position index

public void clear()

Clear the string.

This function removes all the characters from the string.

See also: isEmpty, erase

public std::size_t getSize() const

Get the size of the string.

Returns

Number of characters in the string

See also: isEmpty

public bool isEmpty() const

Check whether the string is empty or not.

Returns

True if the string is empty (i.e. contains no character)

See also: clear, getSize

public void erase(std::size_t position,std::size_t count)

Erase one or more characters from the string.

This function removes a sequence of count characters starting from position.

Parameters

  • position Position of the first character to erase

  • count Number of characters to erase

public void insert(std::size_t position,const String & str)

Insert one or more characters into the string.

This function inserts the characters of str into the string, starting from position.

Parameters

  • position Position of insertion

  • str Characters to insert

public std::size_t find(const String & str,std::size_t start) const

Find a sequence of one or more characters in the string.

This function searches for the characters of str in the string, starting from start.

Parameters

  • str Characters to find

  • start Where to begin searching

Returns

Position of str in the string, or String::InvalidPos if not found

public void replace(std::size_t position,std::size_t length,const String & replaceWith)

Replace a substring with another string.

This function replaces the substring that starts at index position and spans length characters with the string replaceWith.

Parameters

  • position Index of the first character to be replaced

  • length Number of characters to replace. You can pass InvalidPos to replace all characters until the end of the string.

  • replaceWith String that replaces the given substring.

public void replace(const String& searchFor,constString & replaceWith)

Replace all occurrences of a substring with a replacement string.

This function replaces all occurrences of searchFor in this string with the string replaceWith.

Parameters

  • searchFor The value being searched for

  • replaceWith The value that replaces found searchFor values

public String substring(std::size_t position,std::size_t length) const

Return a part of the string.

This function returns the substring that starts at index position and spans length characters.

Parameters

  • position Index of the first character

  • length Number of characters to include in the substring (if the string is shorter, as many characters as possible are included). InvalidPos can be used to include all characters until the end of the string.

Returns

String object containing a substring of this object

public const Uint32 * getData() const

Get a pointer to the C-style array of characters.

This functions provides a read-only access to a null-terminated C-style representation of the string. The returned pointer is temporary and is meant only for immediate use, thus it is not recommended to store it.

Returns

Read-only pointer to the array of characters

public Iterator begin()

Return an iterator to the beginning of the string.

Returns

Read-write iterator to the beginning of the string characters

See also: end

public ConstIterator begin() const

Return an iterator to the beginning of the string.

Returns

Read-only iterator to the beginning of the string characters

See also: end

public Iterator end()

Return an iterator to the end of the string.

The end iterator refers to 1 position past the last character; thus it represents an invalid character and should never be accessed.

Returns

Read-write iterator to the end of the string characters

See also: begin

public ConstIterator end() const

Return an iterator to the end of the string.

The end iterator refers to 1 position past the last character; thus it represents an invalid character and should never be accessed.

Returns

Read-only iterator to the end of the string characters

See also: begin

typedef Iterator

Iterator type.

Read-only iterator type.

class sf::Thread

class sf::Thread
  : private sf::NonCopyable

Utility class to manipulate threads.

Threads provide a way to run multiple parts of the code in parallel.

When you launch a new thread, the execution is split and both the new thread and the caller run in parallel.

To use a sf::Thread, you construct it directly with the function to execute as the entry point of the thread. sf::Thread has multiple template constructors, which means that you can use several types of entry points:

  • non-member functions with no argument

  • non-member functions with one argument of any type

  • functors with no argument (this one is particularly useful for compatibility with boost/std::bind)

  • functors with one argument of any type

  • member functions from any class with no argument

The function argument, if any, is copied in the sf::Thread instance, as well as the functor (if the corresponding constructor is used). Class instances, however, are passed by pointer so you must make sure that the object won't be destroyed while the thread is still using it.

The thread ends when its function is terminated. If the owner sf::Thread instance is destroyed before the thread is finished, the destructor will wait (see wait())

Usage examples:

// example 1: non member function with one argument

void threadFunc(int argument)
{
    ...
}

sf::Thread thread(&threadFunc, 5);
thread.launch(); // start the thread (internally calls threadFunc(5))
// example 2: member function

class Task
{
public:
    void run()
    {
        ...
    }
};

Task task;
sf::Thread thread(&Task::run, &task);
thread.launch(); // start the thread (internally calls task.run())
// example 3: functor

struct Task
{
    void operator()()
    {
        ...
    }
};

sf::Thread thread(Task());
thread.launch(); // start the thread (internally calls operator() on the Task instance)

Creating parallel threads of execution can be dangerous: all threads inside the same process share the same memory space, which means that you may end up accessing the same variable from multiple threads at the same time. To prevent this kind of situations, you can use mutexes (see sf::Mutex).

See also: sf::Mutex

Summary

Members Descriptions
public template<>
Thread(F function)
Construct the thread from a functor with no argument.
public template<>
Thread(F function,A argument)
Construct the thread from a functor with an argument.
public template<>
Thread(void(C::*)() function,C * object)
Construct the thread from a member function and an object.
public ~Thread() Destructor.
public void launch() Run the thread.
public void wait() Wait until the thread finishes.
public void terminate() Terminate the thread.

Members

public template<>
Thread(F function)

Construct the thread from a functor with no argument.

This constructor works for function objects, as well as free functions.

Use this constructor for this kind of function:

void function();

// --- or ----

struct Functor
{
    void operator()();
};

Note: this does not run the thread, use launch().

Parameters

  • function Functor or free function to use as the entry point of the thread

public template<>
Thread(F function,A argument)

Construct the thread from a functor with an argument.

This constructor works for function objects, as well as free functions. It is a template, which means that the argument can have any type (int, std::string, void*, Toto, ...).

Use this constructor for this kind of function:

void function(int arg);

// --- or ----

struct Functor
{
    void operator()(std::string arg);
};

Note: this does not run the thread, use launch().

Parameters

  • function Functor or free function to use as the entry point of the thread

  • argument argument to forward to the function

public template<>
Thread(void(C::*)() function,C * object)

Construct the thread from a member function and an object.

This constructor is a template, which means that you can use it with any class. Use this constructor for this kind of function:

class MyClass
{
public:

    void function();
};

Note: this does not run the thread, use launch().

Parameters

  • function Entry point of the thread

  • object Pointer to the object to use

public ~Thread()

Destructor.

This destructor calls wait(), so that the internal thread cannot survive after its sf::Thread instance is destroyed.

public void launch()

Run the thread.

This function starts the entry point passed to the thread's constructor, and returns immediately. After this function returns, the thread's function is running in parallel to the calling code.

public void wait()

Wait until the thread finishes.

This function will block the execution until the thread's function ends. Warning: if the thread function never ends, the calling thread will block forever. If this function is called from its owner thread, it returns without doing anything.

public void terminate()

Terminate the thread.

This function immediately stops the thread, without waiting for its function to finish. Terminating a thread with this function is not safe, and can lead to local variables not being destroyed on some operating systems. You should rather try to make the thread function terminate by itself.

class sf::ThreadLocal

class sf::ThreadLocal
  : private sf::NonCopyable

Defines variables with thread-local storage.

This class manipulates void* parameters and thus is not appropriate for strongly-typed variables.

You should rather use the sf::ThreadLocalPtr template class.

Summary

Members Descriptions
public ThreadLocal(void * value) Default constructor.
public ~ThreadLocal() Destructor.
public void setValue(void * value) Set the thread-specific value of the variable.
public void * getValue() const Retrieve the thread-specific value of the variable.

Members

public ThreadLocal(void * value)

Default constructor.

Parameters

  • value Optional value to initialize the variable

public ~ThreadLocal()

Destructor.

public void setValue(void * value)

Set the thread-specific value of the variable.

Parameters

  • value Value of the variable for the current thread

public void * getValue() const

Retrieve the thread-specific value of the variable.

Returns

Value of the variable for the current thread

class sf::ThreadLocalPtr

class sf::ThreadLocalPtr
  : private sf::ThreadLocal

Pointer to a thread-local variable.

sf::ThreadLocalPtr is a type-safe wrapper for storing pointers to thread-local variables.

A thread-local variable holds a different value for each different thread, unlike normal variables that are shared.

Its usage is completely transparent, so that it is similar to manipulating the raw pointer directly (like any smart pointer).

Usage example:

MyClass object1;
MyClass object2;
sf::ThreadLocalPtr<MyClass> objectPtr;

void thread1()
{
    objectPtr = &object1; // doesn't impact thread2
    ...
}

void thread2()
{
    objectPtr = &object2; // doesn't impact thread1
    ...
}

int main()
{
    // Create and launch the two threads
    sf::Thread t1(&thread1);
    sf::Thread t2(&thread2);
    t1.launch();
    t2.launch();

    return 0;
}

ThreadLocalPtr is designed for internal use; however you can use it if you feel like it fits well your implementation.

Summary

Members Descriptions
public ThreadLocalPtr(T * value) Default constructor.
public T & operator*() const Overload of unary operator *.
public T * operator->() const Overload of operator ->
public operator T*() const Conversion operator to implicitly convert the pointer to its raw pointer type (T*)
public ThreadLocalPtr< T > & operator=(T * value) Assignment operator for a raw pointer parameter.
public ThreadLocalPtr< T > & operator=(const ThreadLocalPtr< T > & right) Assignment operator for a ThreadLocalPtr parameter.

Members

public ThreadLocalPtr(T * value)

Default constructor.

Parameters

  • value Optional value to initialize the variable

public T & operator*() const

Overload of unary operator *.

Like raw pointers, applying the * operator returns a reference to the pointed-to object.

Returns

Reference to the thread-local variable

public T * operator->() const

Overload of operator ->

Similarly to raw pointers, applying the -> operator returns the pointed-to object.

Returns

Pointer to the thread-local variable

public operator T*() const

Conversion operator to implicitly convert the pointer to its raw pointer type (T*)

Returns

Pointer to the actual object

public ThreadLocalPtr< T > & operator=(T * value)

Assignment operator for a raw pointer parameter.

Parameters

  • value Pointer to assign

Returns

Reference to self

public ThreadLocalPtr< T > & operator=(const ThreadLocalPtr< T > & right)

Assignment operator for a ThreadLocalPtr parameter.

Parameters

Returns

Reference to self

class sf::Time

Represents a time value.

sf::Time encapsulates a time value in a flexible way.

It allows to define a time value either as a number of seconds, milliseconds or microseconds. It also works the other way round: you can read a time value as either a number of seconds, milliseconds or microseconds.

By using such a flexible interface, the API doesn't impose any fixed type or resolution for time values, and let the user choose its own favorite representation.

Time values support the usual mathematical operations: you can add or subtract two times, multiply or divide a time by a number, compare two times, etc.

Since they represent a time span and not an absolute time value, times can also be negative.

Usage example:

sf::Time t1 = sf::seconds(0.1f);
Int32 milli = t1.asMilliseconds(); // 100

sf::Time t2 = sf::milliseconds(30);
Int64 micro = t2.asMicroseconds(); // 30000

sf::Time t3 = sf::microseconds(-800000);
float sec = t3.asSeconds(); // -0.8
void update(sf::Time elapsed)
{
   position += speed * elapsed.asSeconds();
}

update(sf::milliseconds(100));

See also: sf::Clock

Summary

Members Descriptions
public Time() Default constructor.
public float asSeconds() const Return the time value as a number of seconds.
public Int32 asMilliseconds() const Return the time value as a number of milliseconds.
public Int64 asMicroseconds() const Return the time value as a number of microseconds.

Members

public Time()

Default constructor.

Sets the time value to zero.

public float asSeconds() const

Return the time value as a number of seconds.

Returns

Time in seconds

See also: asMilliseconds, asMicroseconds

public Int32 asMilliseconds() const

Return the time value as a number of milliseconds.

Returns

Time in milliseconds

See also: asSeconds, asMicroseconds

public Int64 asMicroseconds() const

Return the time value as a number of microseconds.

Returns

Time in microseconds

See also: asSeconds, asMilliseconds

class sf::Utf

Utility class providing generic functions for UTF conversions.

sf::Utf is a low-level, generic interface for counting, iterating, encoding and decoding Unicode characters and strings. It is able to handle ANSI, wide, latin-1, UTF-8, UTF-16 and UTF-32 encodings.

sf::Utf functions are all static, these classes are not meant to be instantiated. All the functions are template, so that you can use any character / string type for a given encoding.

It has 3 specializations:

Summary

Members Descriptions

Members

class sf::Vector2

Utility template class for manipulating 2-dimensional vectors.

sf::Vector2 is a simple class that defines a mathematical vector with two coordinates (x and y).

It can be used to represent anything that has two dimensions: a size, a point, a velocity, etc.

The template parameter T is the type of the coordinates. It can be any type that supports arithmetic operations (+, -, /, *) and comparisons (==, !=), for example int or float.

You generally don't have to care about the templated form (sf::Vector2), the most common specializations have special typedefs:

  • sf::Vector2 is sf::Vector2f

  • sf::Vector2 is sf::Vector2i

  • sf::Vector2 is sf::Vector2u

The sf::Vector2 class has a small and simple interface, its x and y members can be accessed directly (there are no accessors like setX(), getX()) and it contains no mathematical function like dot product, cross product, length, etc.

Usage example:

sf::Vector2f v1(16.5f, 24.f);
v1.x = 18.2f;
float y = v1.y;

sf::Vector2f v2 = v1 * 5.f;
sf::Vector2f v3;
v3 = v1 + v2;

bool different = (v2 != v3);

Note: for 3-dimensional vectors, see sf::Vector3.

Summary

Members Descriptions
public T x X coordinate of the vector.
public T y Y coordinate of the vector.
public Vector2() Default constructor.
public Vector2(T X,T Y) Construct the vector from its coordinates.
public template<>
explicitVector2(const Vector2< U > & vector)
Construct the vector from another type of vector.

Members

public T x

X coordinate of the vector.

public T y

Y coordinate of the vector.

public Vector2()

Default constructor.

Creates a Vector2(0, 0).

public Vector2(T X,T Y)

Construct the vector from its coordinates.

Parameters

  • X X coordinate

  • Y Y coordinate

public template<>
explicitVector2(const Vector2< U > & vector)

Construct the vector from another type of vector.

This constructor doesn't replace the copy constructor, it's called only when U != T. A call to this constructor will fail to compile if U is not convertible to T.

Parameters

  • vector Vector to convert

class sf::Vector3

Utility template class for manipulating 3-dimensional vectors.

sf::Vector3 is a simple class that defines a mathematical vector with three coordinates (x, y and z).

It can be used to represent anything that has three dimensions: a size, a point, a velocity, etc.

The template parameter T is the type of the coordinates. It can be any type that supports arithmetic operations (+, -, /, *) and comparisons (==, !=), for example int or float.

You generally don't have to care about the templated form (sf::Vector3), the most common specializations have special typedefs:

  • sf::Vector3 is sf::Vector3f

  • sf::Vector3 is sf::Vector3i

The sf::Vector3 class has a small and simple interface, its x and y members can be accessed directly (there are no accessors like setX(), getX()) and it contains no mathematical function like dot product, cross product, length, etc.

Usage example:

sf::Vector3f v1(16.5f, 24.f, -8.2f);
v1.x = 18.2f;
float y = v1.y;
float z = v1.z;

sf::Vector3f v2 = v1 * 5.f;
sf::Vector3f v3;
v3 = v1 + v2;

bool different = (v2 != v3);

Note: for 2-dimensional vectors, see sf::Vector2.

Summary

Members Descriptions
public T x X coordinate of the vector.
public T y Y coordinate of the vector.
public T z Z coordinate of the vector.
public Vector3() Default constructor.
public Vector3(T X,T Y,T Z) Construct the vector from its coordinates.
public template<>
explicitVector3(const Vector3< U > & vector)
Construct the vector from another type of vector.

Members

public T x

X coordinate of the vector.

public T y

Y coordinate of the vector.

public T z

Z coordinate of the vector.

public Vector3()

Default constructor.

Creates a Vector3(0, 0, 0).

public Vector3(T X,T Y,T Z)

Construct the vector from its coordinates.

Parameters

  • X X coordinate

  • Y Y coordinate

  • Z Z coordinate

public template<>
explicitVector3(const Vector3< U > & vector)

Construct the vector from another type of vector.

This constructor doesn't replace the copy constructor, it's called only when U != T. A call to this constructor will fail to compile if U is not convertible to T.

Parameters

  • vector Vector to convert
# Doxyfile 1.8.8
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a double hash (##) is considered a comment and is placed in
# front of the TAG it is preceding.
#
# All text after a single hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists, items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (\" \").
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
# This tag specifies the encoding used for all characters in the config file
# that follow. The default is UTF-8 which is also the encoding used for all text
# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
# built into libc) for the transcoding. See https://www.gnu.org/software/libiconv
# for the list of possible encodings.
# The default value is: UTF-8.
DOXYFILE_ENCODING = UTF-8
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
# double-quotes, unless you are using Doxywizard) that should identify the
# project for which the documentation is generated. This name is used in the
# title of most generated pages and in a few other places.
# The default value is: My Project.
PROJECT_NAME = SFML
# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER = @VERSION_MAJOR@.@VERSION_MINOR@.@VERSION_PATCH@
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
# quick idea about the purpose of the project. Keep the description short.
PROJECT_BRIEF =
# With the PROJECT_LOGO tag one can specify an logo or icon that is included in
# the documentation. The maximum height of the logo should not exceed 55 pixels
# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
# to the output directory.
PROJECT_LOGO =
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = DOX
# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
# directories (in 2 levels) under the output directory of each output format and
# will distribute the generated files over these directories. Enabling this
# option can be useful when feeding doxygen a huge amount of source files, where
# putting all generated files in the same directory would otherwise causes
# performance problems for the file system.
# The default value is: NO.
CREATE_SUBDIRS = NO
# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
# characters to appear in the names of generated files. If set to NO, non-ASCII
# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
# U+3044.
# The default value is: NO.
ALLOW_UNICODE_NAMES = NO
# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
# Ukrainian and Vietnamese.
# The default value is: English.
OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
# descriptions after the members that are listed in the file and class
# documentation (similar to Javadoc). Set to NO to disable this.
# The default value is: YES.
BRIEF_MEMBER_DESC = YES
# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
# description of a member or function before the detailed description
#
# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
# The default value is: YES.
REPEAT_BRIEF = YES
# This tag implements a quasi-intelligent brief description abbreviator that is
# used to form the text in various listings. Each string in this list, if found
# as the leading text of the brief description, will be stripped from the text
# and the result, after processing the whole list, is used as the annotated
# text. Otherwise, the brief description is used as-is. If left blank, the
# following values are used ($name is automatically replaced with the name of
# the entity):The $name class, The $name widget, The $name file, is, provides,
# specifies, contains, represents, a, an and the.
ABBREVIATE_BRIEF = "The $name class" \
"The $name widget" \
"The $name file" \
is \
provides \
specifies \
contains \
represents \
a \
an \
the
# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# doxygen will generate a detailed section even if there is only a brief
# description.
# The default value is: NO.
ALWAYS_DETAILED_SEC = YES
# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
# inherited members of a class in the documentation of that class as if those
# members were ordinary class members. Constructors, destructors and assignment
# operators of the base classes will not be shown.
# The default value is: NO.
INLINE_INHERITED_MEMB = YES
# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
# before files name in the file list and in the header files. If set to NO the
# shortest path that makes the file name unique will be used
# The default value is: YES.
FULL_PATH_NAMES = NO
# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
# Stripping is only done if one of the specified strings matches the left-hand
# part of the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the path to
# strip.
#
# Note that you can specify absolute paths here, but also relative paths, which
# will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES.
STRIP_FROM_PATH =
# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
# path mentioned in the documentation of a class, which tells the reader which
# header file to include in order to use a class. If left blank only the name of
# the header file containing the class definition is used. Otherwise one should
# specify the list of include paths that are normally passed to the compiler
# using the -I flag.
STRIP_FROM_INC_PATH =
# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
# less readable) file names. This can be useful is your file systems doesn't
# support long names like on DOS, Mac, or CD-ROM.
# The default value is: NO.
SHORT_NAMES = NO
# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
# first line (until the first dot) of a Javadoc-style comment as the brief
# description. If set to NO, the Javadoc-style will behave just like regular Qt-
# style comments (thus requiring an explicit @brief command for a brief
# description.)
# The default value is: NO.
JAVADOC_AUTOBRIEF = YES
# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
# line (until the first dot) of a Qt-style comment as the brief description. If
# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
# requiring an explicit \brief command for a brief description.)
# The default value is: NO.
QT_AUTOBRIEF = NO
# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
# a brief description. This used to be the default behavior. The new default is
# to treat a multi-line C++ comment block as a detailed description. Set this
# tag to YES if you prefer the old behavior instead.
#
# Note that setting this tag to YES also means that rational rose comments are
# not recognized any more.
# The default value is: NO.
MULTILINE_CPP_IS_BRIEF = NO
# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
# documentation from any documented member that it re-implements.
# The default value is: YES.
INHERIT_DOCS = YES
# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
# new page for each member. If set to NO, the documentation of a member will be
# part of the file/class/namespace that contains it.
# The default value is: NO.
SEPARATE_MEMBER_PAGES = NO
# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
# uses this value to replace tabs by spaces in code fragments.
# Minimum value: 1, maximum value: 16, default value: 4.
TAB_SIZE = 4
# This tag can be used to specify a number of aliases that act as commands in
# the documentation. An alias has the form:
# name=value
# For example adding
# "sideeffect=@par Side Effects:\n"
# will allow you to put the command \sideeffect (or @sideeffect) in the
# documentation, which will result in a user-defined paragraph with heading
# "Side Effects:". You can put \n's in the value part of an alias to insert
# newlines.
ALIASES =
# This tag can be used to specify a number of word-keyword mappings (TCL only).
# A mapping has the form "name=value". For example adding "class=itcl::class"
# will allow you to use the command class in the itcl::class meaning.
TCL_SUBST =
# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
# only. Doxygen will then generate output that is more tailored for C. For
# instance, some of the names that are used will be different. The list of all
# members will be omitted, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_FOR_C = NO
# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
# Python sources only. Doxygen will then generate output that is more tailored
# for that language. For instance, namespaces will be presented as packages,
# qualified scopes will look different, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_JAVA = NO
# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
# sources. Doxygen will then generate output that is tailored for Fortran.
# The default value is: NO.
OPTIMIZE_FOR_FORTRAN = NO
# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
# sources. Doxygen will then generate output that is tailored for VHDL.
# The default value is: NO.
OPTIMIZE_OUTPUT_VHDL = NO
# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given
# extension. Doxygen has a built-in mapping, but you can override or extend it
# using this tag. The format is ext=language, where ext is a file extension, and
# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
# Fortran. In the later case the parser tries to guess whether the code is fixed
# or free formatted code, this is the default for Fortran type files), VHDL. For
# instance to make doxygen treat .inc files as Fortran files (default is PHP),
# and .f files as C (default is Fortran), use: inc=Fortran f=C.
#
# Note For files without extension you can use no_extension as a placeholder.
#
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen.
EXTENSION_MAPPING =
# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable
# documentation. See https://daringfireball.net/projects/markdown/ for details.
# The output of markdown processing is further processed by doxygen, so you can
# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
# case of backward compatibilities issues.
# The default value is: YES.
MARKDOWN_SUPPORT = YES
# When enabled doxygen tries to link words that correspond to documented
# classes, or namespaces to their corresponding documentation. Such a link can
# be prevented in individual cases by by putting a % sign in front of the word
# or globally by setting AUTOLINK_SUPPORT to NO.
# The default value is: YES.
AUTOLINK_SUPPORT = YES
# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
# to include (a tag file for) the STL sources as input, then you should set this
# tag to YES in order to let doxygen match functions declarations and
# definitions whose arguments contain STL classes (e.g. func(std::string);
# versus func(std::string) {}). This also make the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate.
# The default value is: NO.
BUILTIN_STL_SUPPORT = NO
# If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support.
# The default value is: NO.
CPP_CLI_SUPPORT = NO
# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen
# will parse them like normal C++ but will assume all classes use public instead
# of private inheritance when no explicit protection keyword is present.
# The default value is: NO.
SIP_SUPPORT = NO
# For Microsoft's IDL there are propget and propput attributes to indicate
# getter and setter methods for a property. Setting this option to YES will make
# doxygen to replace the get and set methods by a property in the documentation.
# This will only work if the methods are indeed getting or setting a simple
# type. If this is not the case, or you want to show the methods anyway, you
# should set this option to NO.
# The default value is: YES.
IDL_PROPERTY_SUPPORT = YES
# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
# tag is set to YES, then doxygen will reuse the documentation of the first
# member in the group (if any) for the other members of the group. By default
# all members of a group must be documented explicitly.
# The default value is: NO.
DISTRIBUTE_GROUP_DOC = NO
# Set the SUBGROUPING tag to YES to allow class member groups of the same type
# (for instance a group of public functions) to be put as a subgroup of that
# type (e.g. under the Public Functions section). Set it to NO to prevent
# subgrouping. Alternatively, this can be done per class using the
# \nosubgrouping command.
# The default value is: YES.
SUBGROUPING = YES
# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
# are shown inside the group in which they are included (e.g. using \ingroup)
# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
# and RTF).
#
# Note that this feature does not work in combination with
# SEPARATE_MEMBER_PAGES.
# The default value is: NO.
INLINE_GROUPED_CLASSES = NO
# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
# with only public data fields or simple typedef fields will be shown inline in
# the documentation of the scope in which they are defined (i.e. file,
# namespace, or group documentation), provided this scope is documented. If set
# to NO, structs, classes, and unions are shown on a separate page (for HTML and
# Man pages) or section (for LaTeX and RTF).
# The default value is: NO.
INLINE_SIMPLE_STRUCTS = NO
# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
# enum is documented as struct, union, or enum with the name of the typedef. So
# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
# with name TypeT. When disabled the typedef will appear as a member of a file,
# namespace, or class. And the struct will be named TypeS. This can typically be
# useful for C code in case the coding convention dictates that all compound
# types are typedef'ed and only the typedef is referenced, never the tag name.
# The default value is: NO.
TYPEDEF_HIDES_STRUCT = NO
# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
# cache is used to resolve symbols given their name and scope. Since this can be
# an expensive process and often the same symbol appears multiple times in the
# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
# doxygen will become slower. If the cache is too large, memory is wasted. The
# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
# symbols. At the end of a run doxygen will report the cache usage and suggest
# the optimal cache size from a speed point of view.
# Minimum value: 0, maximum value: 9, default value: 0.
LOOKUP_CACHE_SIZE = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
# documentation are documented, even if no documentation was available. Private
# class members and static file members will be hidden unless the
# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
# Note: This will also disable the warnings about undocumented members that are
# normally produced when WARNINGS is set to YES.
# The default value is: NO.
EXTRACT_ALL = NO
# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
# be included in the documentation.
# The default value is: NO.
EXTRACT_PRIVATE = NO
# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
# scope will be included in the documentation.
# The default value is: NO.
EXTRACT_PACKAGE = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
# included in the documentation.
# The default value is: NO.
EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
# locally in source files will be included in the documentation. If set to NO
# only classes defined in header files are included. Does not have any effect
# for Java sources.
# The default value is: YES.
EXTRACT_LOCAL_CLASSES = YES
# This flag is only useful for Objective-C code. When set to YES local methods,
# which are defined in the implementation section but not in the interface are
# included in the documentation. If set to NO only methods in the interface are
# included.
# The default value is: NO.
EXTRACT_LOCAL_METHODS = NO
# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base name of
# the file that contains the anonymous namespace. By default anonymous namespace
# are hidden.
# The default value is: NO.
EXTRACT_ANON_NSPACES = NO
# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
# undocumented members inside documented classes or files. If set to NO these
# members will be included in the various overviews, but no documentation
# section is generated. This option has no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy. If set
# to NO these classes will be included in the various overviews. This option has
# no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_CLASSES = NO
# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
# (class|struct|union) declarations. If set to NO these declarations will be
# included in the documentation.
# The default value is: NO.
HIDE_FRIEND_COMPOUNDS = NO
# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
# documentation blocks found inside the body of a function. If set to NO these
# blocks will be appended to the function's detailed documentation block.
# The default value is: NO.
HIDE_IN_BODY_DOCS = NO
# The INTERNAL_DOCS tag determines if documentation that is typed after a
# \internal command is included. If the tag is set to NO then the documentation
# will be excluded. Set it to YES to include the internal documentation.
# The default value is: NO.
INTERNAL_DOCS = NO
# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
# names in lower-case letters. If set to YES upper-case letters are also
# allowed. This is useful if you have classes or files whose names only differ
# in case and if your file system supports case sensitive file names. Windows
# and Mac users are advised to set this option to NO.
# The default value is: system dependent.
CASE_SENSE_NAMES = YES
# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
# their full class and namespace scopes in the documentation. If set to YES the
# scope will be hidden.
# The default value is: NO.
HIDE_SCOPE_NAMES = NO
# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
# the files that are included by a file in the documentation of that file.
# The default value is: YES.
SHOW_INCLUDE_FILES = YES
# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
# grouped member an include statement to the documentation, telling the reader
# which file to include in order to use the member.
# The default value is: NO.
SHOW_GROUPED_MEMB_INC = NO
# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
# files with double quotes in the documentation rather than with sharp brackets.
# The default value is: NO.
FORCE_LOCAL_INCLUDES = NO
# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
# documentation for inline members.
# The default value is: YES.
INLINE_INFO = YES
# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
# (detailed) documentation of file and class members alphabetically by member
# name. If set to NO the members will appear in declaration order.
# The default value is: YES.
SORT_MEMBER_DOCS = YES
# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
# descriptions of file, namespace and class members alphabetically by member
# name. If set to NO the members will appear in declaration order. Note that
# this will also influence the order of the classes in the class list.
# The default value is: NO.
SORT_BRIEF_DOCS = NO
# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
# (brief and detailed) documentation of class members so that constructors and
# destructors are listed first. If set to NO the constructors will appear in the
# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
# member documentation.
# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
# detailed member documentation.
# The default value is: NO.
SORT_MEMBERS_CTORS_1ST = NO
# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
# of group names into alphabetical order. If set to NO the group names will
# appear in their defined order.
# The default value is: NO.
SORT_GROUP_NAMES = NO
# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
# fully-qualified names, including namespaces. If set to NO, the class list will
# be sorted only by class name, not including the namespace part.
# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
# Note: This option applies only to the class list, not to the alphabetical
# list.
# The default value is: NO.
SORT_BY_SCOPE_NAME = NO
# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
# type resolution of all parameters of a function it will reject a match between
# the prototype and the implementation of a member function even if there is
# only one candidate or it is obvious which candidate to choose by doing a
# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
# accept a match between prototype and implementation in such cases.
# The default value is: NO.
STRICT_PROTO_MATCHING = NO
# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
# todo list. This list is created by putting \todo commands in the
# documentation.
# The default value is: YES.
GENERATE_TODOLIST = YES
# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
# test list. This list is created by putting \test commands in the
# documentation.
# The default value is: YES.
GENERATE_TESTLIST = YES
# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
# list. This list is created by putting \bug commands in the documentation.
# The default value is: YES.
GENERATE_BUGLIST = YES
# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
# the deprecated list. This list is created by putting \deprecated commands in
# the documentation.
# The default value is: YES.
GENERATE_DEPRECATEDLIST= YES
# The ENABLED_SECTIONS tag can be used to enable conditional documentation
# sections, marked by \if <section_label> ... \endif and \cond <section_label>
# ... \endcond blocks.
ENABLED_SECTIONS =
# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
# initial value of a variable or macro / define can have for it to appear in the
# documentation. If the initializer consists of more lines than specified here
# it will be hidden. Use a value of 0 to hide initializers completely. The
# appearance of the value of individual variables and macros / defines can be
# controlled using \showinitializer or \hideinitializer command in the
# documentation regardless of this setting.
# Minimum value: 0, maximum value: 10000, default value: 30.
MAX_INITIALIZER_LINES = 30
# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
# the bottom of the documentation of classes and structs. If set to YES the list
# will mention the files that were used to generate the documentation.
# The default value is: YES.
SHOW_USED_FILES = YES
# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
# will remove the Files entry from the Quick Index and from the Folder Tree View
# (if specified).
# The default value is: YES.
SHOW_FILES = YES
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
# page. This will remove the Namespaces entry from the Quick Index and from the
# Folder Tree View (if specified).
# The default value is: YES.
SHOW_NAMESPACES = YES
# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
# the version control system). Doxygen will invoke the program by executing (via
# popen()) the command command input-file, where command is the value of the
# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
# by doxygen. Whatever the program writes to standard output is used as the file
# version. For an example see the documentation.
FILE_VERSION_FILTER =
# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
# by doxygen. The layout file controls the global structure of the generated
# output files in an output format independent way. To create the layout file
# that represents doxygen's defaults, run doxygen with the -l option. You can
# optionally specify a file name after the option, if omitted DoxygenLayout.xml
# will be used as the name of the layout file.
#
# Note that if you run doxygen from a directory containing a file called
# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
# tag is left empty.
LAYOUT_FILE =
# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
# the reference definitions. This must be a list of .bib files. The .bib
# extension is automatically appended if omitted. This requires the bibtex tool
# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.
# For LaTeX the style of the bibliography can be controlled using
# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
# search path. See also \cite for info how to create references.
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
#---------------------------------------------------------------------------
# The QUIET tag can be used to turn on/off the messages that are generated to
# standard output by doxygen. If QUIET is set to YES this implies that the
# messages are off.
# The default value is: NO.
QUIET = NO
# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
# this implies that the warnings are on.
#
# Tip: Turn warnings on while writing the documentation.
# The default value is: YES.
WARNINGS = YES
# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: YES.
WARN_IF_UNDOCUMENTED = YES
# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
# potential errors in the documentation, such as not documenting some parameters
# in a documented function, or documenting parameters that don't exist or using
# markup commands wrongly.
# The default value is: YES.
WARN_IF_DOC_ERROR = YES
# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
# are documented, but have no documentation for their parameters or return
# value. If set to NO doxygen will only warn about wrong or incomplete parameter
# documentation, but not about the absence of documentation.
# The default value is: NO.
WARN_NO_PARAMDOC = YES
# The WARN_FORMAT tag determines the format of the warning messages that doxygen
# can produce. The string should contain the $file, $line, and $text tags, which
# will be replaced by the file and line number from which the warning originated
# and the warning text. Optionally the format may contain $version, which will
# be replaced by the version of the file (if it could be obtained via
# FILE_VERSION_FILTER)
# The default value is: $file:$line: $text.
WARN_FORMAT = "$file:$line: $text"
# The WARN_LOGFILE tag can be used to specify a file to which warning and error
# messages should be written. If left blank the output is written to standard
# error (stderr).
WARN_LOGFILE =
#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------
# The INPUT tag is used to specify the files and/or directories that contain
# documented source files. You may enter file names like myfile.cpp or
# directories like /usr/src/myproject. Separate the files or directories with
# spaces.
# Note: If this tag is empty the current directory is searched.
INPUT = "SFML/include/SFML" \
"SFML/doc/mainpage.hpp"
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
# documentation (see: https://www.gnu.org/software/libiconv) for the list of
# possible encodings.
# The default value is: UTF-8.
INPUT_ENCODING = UTF-8
# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank the
# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
# *.qsf, *.as and *.js.
FILE_PATTERNS = *.hpp
# The RECURSIVE tag can be used to specify whether or not subdirectories should
# be searched for input files as well.
# The default value is: NO.
RECURSIVE = YES
# The EXCLUDE tag can be used to specify files and/or directories that should be
# excluded from the INPUT source files. This way you can easily exclude a
# subdirectory from a directory tree whose root is specified with the INPUT tag.
#
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE =
# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
# directories that are symbolic links (a Unix filesystem feature) are excluded
# from the input.
EXCLUDE_SYMLINKS = NO
# If the value of the INPUT tag contains directories, you can use the
# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
# certain files from those directories.
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/*
EXCLUDE_PATTERNS = .git \
extlibs \
src \
examples \
install \
build \
tools \
cmake
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# AClass::ANamespace, ANamespace::*Test
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/*
EXCLUDE_SYMBOLS = priv
# The EXAMPLE_PATH tag can be used to specify one or more files or directories
# that contain example code fragments that are included (see the \include
# command).
EXAMPLE_PATH =
# If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank all
# files are included.
EXAMPLE_PATTERNS = *
# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
# searched for input files to be used with the \include or \dontinclude commands
# irrespective of the value of the RECURSIVE tag.
# The default value is: NO.
EXAMPLE_RECURSIVE = NO
# The IMAGE_PATH tag can be used to specify one or more files or directories
# that contain images that are to be included in the documentation (see the
# \image command).
IMAGE_PATH =
# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command:
#
# <filter> <input-file>
#
# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
# name of an input file. Doxygen will then use the output that the filter
# program writes to standard output. If FILTER_PATTERNS is specified, this tag
# will be ignored.
#
# Note that the filter must not add or remove lines; it is applied before the
# code is scanned, but not when the output code is generated. If lines are added
# or removed, the anchors will not be placed correctly.
INPUT_FILTER =
# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
# basis. Doxygen will compare the file name with each pattern and apply the
# filter if there is a match. The filters are a list of the form: pattern=filter
# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
# patterns match the file name, INPUT_FILTER is applied.
FILTER_PATTERNS =
# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER ) will also be used to filter the input files that are used for
# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
# The default value is: NO.
FILTER_SOURCE_FILES = NO
# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
# it is also possible to disable source filtering for a specific pattern using
# *.ext= (so without naming a filter).
# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
FILTER_SOURCE_PATTERNS =
# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
# is part of the input, its contents will be placed on the main page
# (index.html). This can be useful if you have a project on for instance GitHub
# and want to reuse the introduction page also for the doxygen output.
USE_MDFILE_AS_MAINPAGE =
#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------
# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
# generated. Documented entities will be cross-referenced with these sources.
#
# Note: To get rid of all source code in the generated output, make sure that
# also VERBATIM_HEADERS is set to NO.
# The default value is: NO.
SOURCE_BROWSER = YES
# Setting the INLINE_SOURCES tag to YES will include the body of functions,
# classes and enums directly into the documentation.
# The default value is: NO.
INLINE_SOURCES = NO
# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
# special comment blocks from generated source code fragments. Normal C, C++ and
# Fortran comments will always remain visible.
# The default value is: YES.
STRIP_CODE_COMMENTS = YES
# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
# function all documented functions referencing it will be listed.
# The default value is: NO.
REFERENCED_BY_RELATION = NO
# If the REFERENCES_RELATION tag is set to YES then for each documented function
# all documented entities called/used by that function will be listed.
# The default value is: NO.
REFERENCES_RELATION = NO
# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
# link to the documentation.
# The default value is: YES.
REFERENCES_LINK_SOURCE = NO
# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
# source code will show a tooltip with additional information such as prototype,
# brief description and links to the definition and documentation. Since this
# will make the HTML file larger and loading of large files a bit slower, you
# can opt to disable this feature.
# The default value is: YES.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
SOURCE_TOOLTIPS = YES
# If the USE_HTAGS tag is set to YES then the references to source code will
# point to the HTML generated by the htags(1) tool instead of doxygen built-in
# source browser. The htags tool is part of GNU's global source tagging system
# (see https://www.gnu.org/software/global/global.html). You will need version
# 4.8.6 or higher.
#
# To use it do the following:
# - Install the latest version of global
# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
# - Make sure the INPUT points to the root of the source tree
# - Run doxygen as normal
#
# Doxygen will invoke htags (and that will in turn invoke gtags), so these
# tools must be available from the command line (i.e. in the search path).
#
# The result: instead of the source browser generated by doxygen, the links to
# source code will now point to the output of htags.
# The default value is: NO.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
USE_HTAGS = NO
# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
# verbatim copy of the header file for each class for which an include is
# specified. Set to NO to disable this.
# See also: Section \class.
# The default value is: YES.
VERBATIM_HEADERS = YES
# If the CLANG_ASSISTED_PARSING tag is set to YES, then doxygen will use the
# clang parser (see: https://clang.llvm.org/) for more accurate parsing at the
# cost of reduced performance. This can be particularly helpful with template
# rich C++ code for which doxygen's built-in parser lacks the necessary type
# information.
# Note: The availability of this option depends on whether or not doxygen was
# compiled with the --with-libclang option.
# The default value is: NO.
# Generates warnings with Clang
#CLANG_ASSISTED_PARSING = NO
# If clang assisted parsing is enabled you can provide the compiler with command
# line options that you would normally use when invoking the compiler. Note that
# the include paths will already be set by doxygen for the files and directories
# specified with INPUT and INCLUDE_PATH.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
# Generates warnings with Clang
#CLANG_OPTIONS =
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
# compounds will be generated. Enable this if the project contains a lot of
# classes, structs, unions or interfaces.
# The default value is: YES.
ALPHABETICAL_INDEX = YES
# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
# which the alphabetical index list will be split.
# Minimum value: 1, maximum value: 20, default value: 5.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
COLS_IN_ALPHA_INDEX = 5
# In case all classes in a project start with a common prefix, all classes will
# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
# can be used to specify a prefix (or a list of prefixes) that should be ignored
# while generating the index headers.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
# The default value is: YES.
GENERATE_HTML = NO
# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_OUTPUT = html
# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
# generated HTML page (for example: .htm, .php, .asp).
# The default value is: .html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FILE_EXTENSION = .html
# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
# each generated HTML page. If the tag is left blank doxygen will generate a
# standard header.
#
# To get valid HTML the header file that includes any scripts and style sheets
# that doxygen needs, which is dependent on the configuration options used (e.g.
# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
# default header using
# doxygen -w html new_header.html new_footer.html new_stylesheet.css
# YourConfigFile
# and then modify the file new_header.html. See also section "Doxygen usage"
# for information on how to generate the default header that doxygen normally
# uses.
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. For a description
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_HEADER =
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
# footer. See HTML_HEADER for more information on how to generate a default
# footer and what special commands can be used inside the footer. See also
# section "Doxygen usage" for information on how to generate the default footer
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FOOTER =
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
# the HTML output. If left blank doxygen will generate a default style sheet.
# See also section "Doxygen usage" for information on how to generate the style
# sheet that doxygen normally uses.
# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
# it is more robust and this tag (HTML_STYLESHEET) will in the future become
# obsolete.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_STYLESHEET =
# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
# files or namespaces will be aligned in HTML using tables. If set to
# NO a bullet list will be used.
# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# cascading style sheets that are included after the standard style sheets
# created by doxygen. Using this option one can overrule certain style aspects.
# This is preferred over using HTML_STYLESHEET since it does not replace the
# standard style sheet and is therefor more robust against future updates.
# Doxygen will copy the style sheet files to the output directory.
# Note: The order of the extra stylesheet files is of importance (e.g. the last
# stylesheet in the list overrules the setting of the previous ones in the
# list). For an example see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET =
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
# that these files will be copied to the base HTML output directory. Use the
# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_FILES =
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the stylesheet and background images according to
# this color. Hue is specified as an angle on a colorwheel, see
# https://en.wikipedia.org/wiki/Hue for more information. For instance the value
# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
# purple, and 360 is red again.
# Minimum value: 0, maximum value: 359, default value: 220.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_HUE = 220
# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
# in the HTML output. For a value of 0 the output will use grayscales only. A
# value of 255 will produce the most vivid colors.
# Minimum value: 0, maximum value: 255, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_SAT = 100
# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
# luminance component of the colors in the HTML output. Values below 100
# gradually make the output lighter, whereas values above 100 make the output
# darker. The value divided by 100 is the actual gamma applied, so 80 represents
# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
# change the gamma.
# Minimum value: 40, maximum value: 240, default value: 80.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting this
# to NO can help when comparing the output of multiple runs.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_TIMESTAMP = NO
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_SECTIONS = NO
# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
# shown in the various tree structured indices initially; the user can expand
# and collapse entries dynamically later on. Doxygen will expand the tree to
# such a level that at most the specified number of entries are visible (unless
# a fully collapsed tree already exceeds this amount). So setting the number of
# entries 1 will produce a full collapsed tree by default. 0 is a special value
# representing an infinite number of entries and will result in a full expanded
# tree by default.
# Minimum value: 0, maximum value: 9999, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_INDEX_NUM_ENTRIES = 100
# If the GENERATE_DOCSET tag is set to YES, additional index files will be
# generated that can be used as input for Apple's Xcode 3 integrated development
# environment (see: https://developer.apple.com/tools/xcode/), introduced with
# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
# Makefile in the HTML output directory. Running make will produce the docset in
# that directory and running make install will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
# startup. See https://developer.apple.com/tools/creatingdocsetswithdoxygen.html
# for more information.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_DOCSET = NO
# This tag determines the name of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# The default value is: Doxygen generated docs.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDNAME = "SFML Documentation"
# This tag specifies a string that should uniquely identify the documentation
# set bundle. This should be a reverse domain-name style string, e.g.
# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_BUNDLE_ID = org.sfml-dev.SFML
# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
# The default value is: org.doxygen.Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_ID = org.sfml-dev.SFML
# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
# The default value is: Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_NAME = SFML
# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on
# Windows.
#
# The HTML Help Workshop contains a compiler that can convert all HTML output
# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
# files are now used as the Windows 98 help format, and will replace the old
# Windows help format (.hlp) on all Windows platforms in the future. Compressed
# HTML files also contain an index, a table of contents, and you can search for
# words in the documentation. The HTML workshop also contains a viewer for
# compressed HTML files.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_HTMLHELP = NO
# The CHM_FILE tag can be used to specify the file name of the resulting .chm
# file. You can add a path in front of the file if the result should not be
# written to the html output directory.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_FILE = ../SFML.chm
# The HHC_LOCATION tag can be used to specify the location (absolute path
# including file name) of the HTML help compiler ( hhc.exe). If non-empty
# doxygen will try to run the HTML help compiler on the generated index.hhp.
# The file has to be specified with full path.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
HHC_LOCATION = "@DOXYGEN_HHC_PROGRAM@"
# The GENERATE_CHI flag controls if a separate .chi index file is generated (
# YES) or that it should be included in the master .chm file ( NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
GENERATE_CHI = NO
# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
# and project file content.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_INDEX_ENCODING =
# The BINARY_TOC flag controls whether a binary table of contents is generated (
# YES) or a normal table of contents ( NO) in the .chm file. Furthermore it
# enables the Previous and Next buttons.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
BINARY_TOC = NO
# The TOC_EXPAND flag can be set to YES to add extra items for group members to
# the table of contents of the HTML help documentation and to the tree view.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
TOC_EXPAND = NO
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
# (.qch) of the generated HTML documentation.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_QHP = NO
# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
# the file name of the resulting .qch file. The path specified is relative to
# the HTML output folder.
# This tag requires that the tag GENERATE_QHP is set to YES.
QCH_FILE =
# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
# Project output. For more information please see Qt Help Project / Namespace
# (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_NAMESPACE = org.doxygen.Project
# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
# Help Project output. For more information please see Qt Help Project / Virtual
# Folders (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).
# The default value is: doc.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_VIRTUAL_FOLDER = doc
# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
# filter to add. For more information please see Qt Help Project / Custom
# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_NAME =
# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
# custom filter to add. For more information please see Qt Help Project / Custom
# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_ATTRS =
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_SECT_FILTER_ATTRS =
# The QHG_LOCATION tag can be used to specify the location of Qt's
# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
# generated .qhp file.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHG_LOCATION =
# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
# generated, together with the HTML files, they form an Eclipse help plugin. To
# install this plugin and make it available under the help contents menu in
# Eclipse, the contents of the directory containing the HTML and XML files needs
# to be copied into the plugins directory of eclipse. The name of the directory
# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
# After copying Eclipse needs to be restarted before the help appears.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_ECLIPSEHELP = NO
# A unique identifier for the Eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have this
# name. Each documentation set should have its own identifier.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
ECLIPSE_DOC_ID = org.doxygen.Project
# If you want full control over the layout of the generated HTML pages it might
# be necessary to disable the index and replace it with your own. The
# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
# of each HTML page. A value of NO enables the index and the value YES disables
# it. Since the tabs in the index contain the same information as the navigation
# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
DISABLE_INDEX = NO
# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information. If the tag
# value is set to YES, a side panel will be generated containing a tree-like
# index structure (just like the one that is generated for HTML Help). For this
# to work a browser that supports JavaScript, DHTML, CSS and frames is required
# (i.e. any modern browser). Windows users are probably better off using the
# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
# further fine-tune the look of the index. As an example, the default style
# sheet generated by doxygen has an example that shows how to put an image at
# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
# the same information as the tab index, you could consider setting
# DISABLE_INDEX to YES when enabling this option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_TREEVIEW = NO
# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
# doxygen will group on one line in the generated HTML documentation.
#
# Note that a value of 0 will completely suppress the enum values from appearing
# in the overview section.
# Minimum value: 0, maximum value: 20, default value: 4.
# This tag requires that the tag GENERATE_HTML is set to YES.
ENUM_VALUES_PER_LINE = 4
# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
# to set the initial width (in pixels) of the frame in which the tree is shown.
# Minimum value: 0, maximum value: 1500, default value: 250.
# This tag requires that the tag GENERATE_HTML is set to YES.
TREEVIEW_WIDTH = 250
# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
# external symbols imported via tag files in a separate window.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
EXT_LINKS_IN_WINDOW = NO
# Use this tag to change the font size of LaTeX formulas included as images in
# the HTML documentation. When you change the font size after a successful
# doxygen run you need to manually remove any form_*.png images from the HTML
# output directory to force them to be regenerated.
# Minimum value: 8, maximum value: 50, default value: 10.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_FONTSIZE = 10
# Use the FORMULA_TRANPARENT tag to determine whether or not the images
# generated for formulas are transparent PNGs. Transparent PNGs are not
# supported properly for IE 6.0, but are supported on all modern browsers.
#
# Note that when changing this option you need to delete any form_*.png files in
# the HTML output directory before the changes have effect.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_TRANSPARENT = YES
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
# https://www.mathjax.org) which uses client side Javascript for the rendering
# instead of using prerendered bitmaps. Use this if you do not have LaTeX
# installed or if you want to formulas look prettier in the HTML output. When
# enabled you may also need to install MathJax separately and configure the path
# to it using the MATHJAX_RELPATH option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
USE_MATHJAX = NO
# When MathJax is enabled you can set the default output format to be used for
# the MathJax output. See the MathJax site (see:
# https://docs.mathjax.org/en/latest/output.html) for more details.
# Possible values are: HTML-CSS (which is slower, but has the best
# compatibility), NativeMML (i.e. MathML) and SVG.
# The default value is: HTML-CSS.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_FORMAT = HTML-CSS
# When MathJax is enabled you need to specify the location relative to the HTML
# output directory using the MATHJAX_RELPATH option. The destination directory
# should contain the MathJax.js script. For instance, if the mathjax directory
# is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
# Content Delivery Network so you can quickly see the result without installing
# MathJax. However, it is strongly recommended to install a local copy of
# MathJax from https://www.mathjax.org before deployment.
# The default value is: https://cdn.mathjax.org/mathjax/latest.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_RELPATH = https://cdn.mathjax.org/mathjax/latest
# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example
# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_EXTENSIONS =
# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
# of code that will be used on startup of the MathJax code. See the MathJax site
# (see: https://docs.mathjax.org/en/latest/output.html) for more details. For an
# example see the documentation.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_CODEFILE =
# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
# the HTML output. The underlying search engine uses javascript and DHTML and
# should work on any modern browser. Note that when using HTML help
# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
# there is already a search function so this one should typically be disabled.
# For large projects the javascript based search engine can be slow, then
# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
# search using the keyboard; to jump to the search box use <access key> + S
# (what the <access key> is depends on the OS and browser, but it is typically
# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
# key> to jump into the search results window, the results can be navigated
# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
# the search. The filter options can be selected when the cursor is inside the
# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
# to select a filter and <Enter> or <escape> to activate or cancel the filter
# option.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
SEARCHENGINE = NO
# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
# implemented using a web server instead of a web client using Javascript. There
# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
# setting. When disabled, doxygen will generate a PHP script for searching and
# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
# and searching needs to be provided by external tools. See the section
# "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
SERVER_BASED_SEARCH = NO
# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
# script for searching. Instead the search results are written to an XML file
# which needs to be processed by an external indexer. Doxygen will invoke an
# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
# search results.
#
# Doxygen ships with an example indexer ( doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see: https://xapian.org/).
#
# See the section "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH = NO
# The SEARCHENGINE_URL should point to a search engine hosted by a web server
# which will return the search results when EXTERNAL_SEARCH is enabled.
#
# Doxygen ships with an example indexer ( doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see: https://xapian.org/). See the section "External Indexing and
# Searching" for details.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHENGINE_URL =
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
# search data is written to a file for indexing by an external tool. With the
# SEARCHDATA_FILE tag the name of this file can be specified.
# The default file is: searchdata.xml.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHDATA_FILE = searchdata.xml
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
# projects and redirect the results back to the right project.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH_ID =
# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
# projects other than the one defined by this configuration file, but that are
# all added to the same external search index. Each project needs to have a
# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
# to a relative location where the documentation can be found. The format is:
# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.
# The default value is: YES.
GENERATE_LATEX = NO
# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_OUTPUT = latex
# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
# invoked.
#
# Note that when enabling USE_PDFLATEX this option is only used for generating
# bitmaps for formulas in the HTML output, but not in the Makefile that is
# written to the output directory.
# The default file is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_CMD_NAME = latex
# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
# index for LaTeX.
# The default file is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
MAKEINDEX_CMD_NAME = makeindex
# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
COMPACT_LATEX = NO
# The PAPER_TYPE tag can be used to set the paper type that is used by the
# printer.
# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
# 14 inches) and executive (7.25 x 10.5 inches).
# The default value is: a4.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PAPER_TYPE = a4
# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
# that should be included in the LaTeX output. To get the times font for
# instance you can specify
# EXTRA_PACKAGES=times
# If left blank no extra packages will be included.
# This tag requires that the tag GENERATE_LATEX is set to YES.
EXTRA_PACKAGES =
# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
# generated LaTeX document. The header should contain everything until the first
# chapter. If it is left blank doxygen will generate a standard header. See
# section "Doxygen usage" for information on how to let doxygen write the
# default header to a separate file.
#
# Note: Only use a user-defined header if you know what you are doing! The
# following commands have a special meaning inside the header: $title,
# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
# $projectbrief, $projectlogo. Doxygen will replace $title with the empy string,
# for the replacement values of the other commands the user is refered to
# HTML_HEADER.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HEADER =
# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
# generated LaTeX document. The footer should contain everything after the last
# chapter. If it is left blank doxygen will generate a standard footer. See
# LATEX_HEADER for more information on how to generate a default footer and what
# special commands can be used inside the footer.
#
# Note: Only use a user-defined footer if you know what you are doing!
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_FOOTER =
# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the LATEX_OUTPUT output
# directory. Note that the files will be copied as-is; there are no commands or
# markers available.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EXTRA_FILES =
# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
# contain links (just like the HTML output) instead of page references. This
# makes the output suitable for online browsing using a PDF viewer.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PDF_HYPERLINKS = YES
# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
# the PDF file directly from the LaTeX files. Set this option to YES to get a
# higher quality PDF documentation.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
USE_PDFLATEX = YES
# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
# command to the generated LaTeX files. This will instruct LaTeX to keep running
# if errors occur, instead of asking the user for help. This option is also used
# when generating formulas in HTML.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BATCHMODE = NO
# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
# index chapters (such as File Index, Compound Index, etc.) in the output.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HIDE_INDICES = NO
# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
# code with syntax highlighting in the LaTeX output.
#
# Note that which sources are shown also depends on other settings such as
# SOURCE_BROWSER.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_SOURCE_CODE = NO
# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
# bibliography, e.g. plainnat, or ieeetr. See
# https://en.wikipedia.org/wiki/BibTeX and \cite for more info.
# The default value is: plain.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BIB_STYLE = plain
#---------------------------------------------------------------------------
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The
# RTF output is optimized for Word 97 and may not look too pretty with other RTF
# readers/editors.
# The default value is: NO.
GENERATE_RTF = NO
# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: rtf.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_OUTPUT = rtf
# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
COMPACT_RTF = NO
# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
# contain hyperlink fields. The RTF file will contain links (just like the HTML
# output) instead of page references. This makes the output suitable for online
# browsing using Word or some other Word compatible readers that support those
# fields.
#
# Note: WordPad (write) and others do not support links.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_HYPERLINKS = NO
# Load stylesheet definitions from file. Syntax is similar to doxygen's config
# file, i.e. a series of assignments. You only have to provide replacements,
# missing definitions are set to their default value.
#
# See also section "Doxygen usage" for information on how to generate the
# default style sheet that doxygen normally uses.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_STYLESHEET_FILE =
# Set optional variables used in the generation of an RTF document. Syntax is
# similar to doxygen's config file. A template extensions file can be generated
# using doxygen -e rtf extensionFile.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# Configuration options related to the man page output
#---------------------------------------------------------------------------
# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for
# classes and files.
# The default value is: NO.
GENERATE_MAN = NO
# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it. A directory man3 will be created inside the directory specified by
# MAN_OUTPUT.
# The default directory is: man.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_OUTPUT = man
# The MAN_EXTENSION tag determines the extension that is added to the generated
# man pages. In case the manual section does not start with a number, the number
# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
# optional.
# The default value is: .3.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_EXTENSION = .3
# The MAN_SUBDIR tag determines the name of the directory created within
# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
# MAN_EXTENSION with the initial . removed.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_SUBDIR =
# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
# will generate one additional man file for each entity documented in the real
# man page(s). These additional files only source the real man page, but without
# them the man command would be unable to find the correct page.
# The default value is: NO.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_LINKS = NO
#---------------------------------------------------------------------------
# Configuration options related to the XML output
#---------------------------------------------------------------------------
# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that
# captures the structure of the code including all documentation.
# The default value is: NO.
GENERATE_XML = YES
# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: xml.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_OUTPUT = xml
# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
# listings (including syntax highlighting and cross-referencing information) to
# the XML output. Note that enabling this will significantly increase the size
# of the XML output.
# The default value is: YES.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_PROGRAMLISTING = YES
#---------------------------------------------------------------------------
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
# that can be used to generate PDF.
# The default value is: NO.
GENERATE_DOCBOOK = NO
# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
# front of it.
# The default directory is: docbook.
# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
DOCBOOK_OUTPUT = docbook
# If the DOCBOOK_PROGRAMLISTING tag is set to YES doxygen will include the
# program listings (including syntax highlighting and cross-referencing
# information) to the DOCBOOK output. Note that enabling this will significantly
# increase the size of the DOCBOOK output.
# The default value is: NO.
# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
DOCBOOK_PROGRAMLISTING = NO
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen
# Definitions (see http://autogen.sf.net) file that captures the structure of
# the code including all documentation. Note that this feature is still
# experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module
# file that captures the structure of the code including all documentation.
#
# Note that this feature is still experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_PERLMOD = NO
# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary
# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
# output from the Perl module output.
# The default value is: NO.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_LATEX = NO
# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely
# formatted so it can be parsed by a human reader. This is useful if you want to
# understand what is going on. On the other hand, if this tag is set to NO the
# size of the Perl module output will be much smaller and Perl will parse it
# just the same.
# The default value is: YES.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_PRETTY = YES
# The names of the make variables in the generated doxyrules.make file are
# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
# so different doxyrules.make files included by the same Makefile don't
# overwrite each other's variables.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all
# C-preprocessor directives found in the sources and include files.
# The default value is: YES.
ENABLE_PREPROCESSING = YES
# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names
# in the source code. If set to NO only conditional compilation will be
# performed. Macro expansion can be done in a controlled way by setting
# EXPAND_ONLY_PREDEF to YES.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
MACRO_EXPANSION = YES
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
# the macro expansion is limited to the macros specified with the PREDEFINED and
# EXPAND_AS_DEFINED tags.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_ONLY_PREDEF = YES
# If the SEARCH_INCLUDES tag is set to YES the includes files in the
# INCLUDE_PATH will be searched if a #include is found.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SEARCH_INCLUDES = YES
# The INCLUDE_PATH tag can be used to specify one or more directories that
# contain include files that are not input files but should be processed by the
# preprocessor.
# This tag requires that the tag SEARCH_INCLUDES is set to YES.
INCLUDE_PATH =
# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
# patterns (like *.h and *.hpp) to filter out the header-files in the
# directories. If left blank, the patterns specified with FILE_PATTERNS will be
# used.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
INCLUDE_FILE_PATTERNS =
# The PREDEFINED tag can be used to specify one or more macro names that are
# defined before the preprocessor is started (similar to the -D option of e.g.
# gcc). The argument of the tag is a list of macros of the form: name or
# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
# is assumed. To prevent a macro definition from being undefined via #undef or
# recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
PREDEFINED = SFML_SYSTEM_API \
SFML_NETWORK_API \
SFML_WINDOW_API \
SFML_AUDIO_API \
SFML_GRAPHICS_API \
SFML_DEPRECATED \
SFML_DOXYGEN
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The
# macro definition that is found in the sources will be used. Use the PREDEFINED
# tag if you want to use a different macro definition that overrules the
# definition found in the source code.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_AS_DEFINED =
# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
# remove all references to function-like macros that are alone on a line, have
# an all uppercase name, and do not end with a semicolon. Such function macros
# are typically used for boiler-plate code, and will confuse the parser if not
# removed.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration options related to external references
#---------------------------------------------------------------------------
# The TAGFILES tag can be used to specify one or more tag files. For each tag
# file the location of the external documentation should be added. The format of
# a tag file without this location is as follows:
# TAGFILES = file1 file2 ...
# Adding location for the tag files is done as follows:
# TAGFILES = file1=loc1 "file2 = loc2" ...
# where loc1 and loc2 can be relative or absolute paths or URLs. See the
# section "Linking to external documentation" for more information about the use
# of tag files.
# Note: Each tag file must have a unique name (where the name does NOT include
# the path). If a tag file is not located in the directory in which doxygen is
# run, you must also specify the path to the tagfile here.
TAGFILES =
# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
# tag file that is based on the input files it reads. See section "Linking to
# external documentation" for more information about the usage of tag files.
GENERATE_TAGFILE = @DOXYGEN_OUTPUT_DIR@/SFML.tag
# If the ALLEXTERNALS tag is set to YES all external class will be listed in the
# class index. If set to NO only the inherited external classes will be listed.
# The default value is: NO.
ALLEXTERNALS = NO
# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in
# the modules index. If set to NO, only the current project's groups will be
# listed.
# The default value is: YES.
EXTERNAL_GROUPS = YES
# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in
# the related pages index. If set to NO, only the current project's pages will
# be listed.
# The default value is: YES.
EXTERNAL_PAGES = YES
# The PERL_PATH should be the absolute path and name of the perl script
# interpreter (i.e. the result of 'which perl').
# The default file (with absolute path) is: /usr/bin/perl.
PERL_PATH = /usr/bin/perl
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram
# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
# NO turns the diagrams off. Note that this option also works with HAVE_DOT
# disabled, but it is recommended to install and use dot, since it yields more
# powerful graphs.
# The default value is: YES.
CLASS_DIAGRAMS = YES
# You can define message sequence charts within doxygen comments using the \msc
# command. Doxygen will then run the mscgen tool (see:
# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
# documentation. The MSCGEN_PATH tag allows you to specify the directory where
# the mscgen tool resides. If left empty the tool is assumed to be found in the
# default search path.
MSCGEN_PATH =
# You can include diagrams made with dia in doxygen documentation. Doxygen will
# then run dia to produce the diagram and insert it in the documentation. The
# DIA_PATH tag allows you to specify the directory where the dia binary resides.
# If left empty dia is assumed to be found in the default search path.
DIA_PATH =
# If set to YES, the inheritance and collaboration graphs will hide inheritance
# and usage relations if the target is undocumented or is not a class.
# The default value is: YES.
HIDE_UNDOC_RELATIONS = YES
# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz (see:
# https://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# Bell Labs. The other options in this section have no effect if this option is
# set to NO
# The default value is: NO.
HAVE_DOT = NO
# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
# to run in parallel. When set to 0 doxygen will base this on the number of
# processors available in the system. You can set it explicitly to a value
# larger than 0 to get control over the balance between CPU load and processing
# speed.
# Minimum value: 0, maximum value: 32, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_NUM_THREADS = 0
# When you want a differently looking font in the dot files that doxygen
# generates you can specify the font name using DOT_FONTNAME. You need to make
# sure dot is able to find the font, which can be done by putting it in a
# standard location or by setting the DOTFONTPATH environment variable or by
# setting DOT_FONTPATH to the directory containing the font.
# The default value is: Helvetica.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTNAME = Helvetica
# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
# dot graphs.
# Minimum value: 4, maximum value: 24, default value: 10.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTSIZE = 10
# By default doxygen will tell dot to use the default font as specified with
# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
# the path where dot can find it using this tag.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTPATH =
# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
# each documented class showing the direct and indirect inheritance relations.
# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
CLASS_GRAPH = YES
# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
# graph for each documented class showing the direct and indirect implementation
# dependencies (inheritance, containment, and class references variables) of the
# class with other documented classes.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
COLLABORATION_GRAPH = YES
# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
# groups, showing the direct groups dependencies.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GROUP_GRAPHS = YES
# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
# collaboration diagrams in a style similar to the OMG's Unified Modeling
# Language.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
UML_LOOK = NO
# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
# class node. If there are many fields or methods and many nodes the graph may
# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
# number of items for each type to make the size more manageable. Set this to 0
# for no limit. Note that the threshold may be exceeded by 50% before the limit
# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
# but if the number exceeds 15, the total amount of fields shown is limited to
# 10.
# Minimum value: 0, maximum value: 100, default value: 10.
# This tag requires that the tag HAVE_DOT is set to YES.
UML_LIMIT_NUM_FIELDS = 10
# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
# collaboration graphs will show the relations between templates and their
# instances.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
TEMPLATE_RELATIONS = NO
# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
# YES then doxygen will generate a graph for each documented file showing the
# direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDE_GRAPH = YES
# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
# set to YES then doxygen will generate a graph for each documented file showing
# the direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDED_BY_GRAPH = YES
# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable call graphs for selected
# functions only using the \callgraph command.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALL_GRAPH = NO
# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable caller graphs for selected
# functions only using the \callergraph command.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALLER_GRAPH = NO
# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
# hierarchy of all classes instead of a textual one.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GRAPHICAL_HIERARCHY = YES
# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
# dependencies a directory has on other directories in a graphical way. The
# dependency relations are determined by the #include relations between the
# files in the directories.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
DIRECTORY_GRAPH = YES
# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
# generated by dot.
# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
# to make the SVG files visible in IE 9+ (other browsers do not have this
# requirement).
# Possible values are: png, jpg, gif and svg.
# The default value is: png.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_IMAGE_FORMAT = png
# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
# enable generation of interactive SVG images that allow zooming and panning.
#
# Note that this requires a modern browser other than Internet Explorer. Tested
# and working are Firefox, Chrome, Safari, and Opera.
# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
# the SVG files visible. Older versions of IE do not have SVG support.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
INTERACTIVE_SVG = NO
# The DOT_PATH tag can be used to specify the path where the dot tool can be
# found. If left blank, it is assumed the dot tool can be found in the path.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_PATH =
# The DOTFILE_DIRS tag can be used to specify one or more directories that
# contain dot files that are included in the documentation (see the \dotfile
# command).
# This tag requires that the tag HAVE_DOT is set to YES.
DOTFILE_DIRS =
# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the \mscfile
# command).
MSCFILE_DIRS =
# The DIAFILE_DIRS tag can be used to specify one or more directories that
# contain dia files that are included in the documentation (see the \diafile
# command).
DIAFILE_DIRS =
# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
# path where java can find the plantuml.jar file. If left blank, it is assumed
# PlantUML is not used or called during a preprocessing step. Doxygen will
# generate a warning when it encounters a \startuml command in this case and
# will not generate output for the diagram.
# This tag requires that the tag HAVE_DOT is set to YES.
PLANTUML_JAR_PATH =
# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
# that will be shown in the graph. If the number of nodes in a graph becomes
# larger than this value, doxygen will truncate the graph, which is visualized
# by representing a node as a red box. Note that doxygen if the number of direct
# children of the root node in a graph is already larger than
# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
# Minimum value: 0, maximum value: 10000, default value: 50.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_GRAPH_MAX_NODES = 50
# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
# generated by dot. A depth value of 3 means that only nodes reachable from the
# root by following a path via at most 3 edges will be shown. Nodes that lay
# further from the root node will be omitted. Note that setting this option to 1
# or 2 may greatly reduce the computation time needed for large code bases. Also
# note that the size of a graph can be further restricted by
# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
# Minimum value: 0, maximum value: 1000, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
MAX_DOT_GRAPH_DEPTH = 0
# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
# background. This is disabled by default, because dot on Windows does not seem
# to support this out of the box.
#
# Warning: Depending on the platform used, enabling this option may lead to
# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
# read).
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_TRANSPARENT = NO
# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
# files in one run (i.e. multiple -o and -T options on the command line). This
# makes dot run faster, but since only newer versions of dot (>1.8.10) support
# this, this feature is disabled by default.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_MULTI_TARGETS = NO
# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
# explaining the meaning of the various boxes and arrows in the dot generated
# graphs.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GENERATE_LEGEND = YES
# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot
# files that are used to generate the various graphs.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_CLEANUP = YES
#---------------------------------------------------------------------------
# SFML specific aliases
#---------------------------------------------------------------------------
# sfplatform{platform(s)}
# sfplatform{platform(s), header}
#
# Warns the user that some specific class or function is only available on
# specific platforms.
#
# This shouldn't be used for incomplete implementations. It's meant for things
# that will never appear on another platform, e.g. Android's native activity.
#
# If a header is given, the user is informed, that this header must be included
# for the mentioned element to be defined.
ALIASES += sfplatform{1}="<dl class=\"attention\"><dt>Platform Limitation</dt><dd><b>This is only available on \1.</b></dd></dl>"
ALIASES += sfplatform{2}="<dl class=\"attention\"><dt>Platform Limitation</dt><dd><b>This is only available on \1</b> and to use it, you'll have to specifically include \2 in your code.</dd></dl>"

group window

Provides OpenGL-based windows, and abstractions for events and input handling.

Summary

Members Descriptions
enum @8 Enumeration of the window styles.
class sf::Clipboard Give access to the system clipboard.
class sf::Context Class holding a valid drawing context.
class sf::ContextSettings Structure defining the settings of the OpenGL context attached to a window.
class sf::Cursor Cursor defines the appearance of a system cursor.
class sf::Event Defines a system event and its parameters.
class sf::GlResource Base class for classes that require an OpenGL context.
class sf::Joystick Give access to the real-time state of the joysticks.
class sf::Keyboard Give access to the real-time state of the keyboard.
class sf::Mouse Give access to the real-time state of the mouse.
class sf::Sensor Give access to the real-time state of the sensors.
class sf::Touch Give access to the real-time state of the touches.
class sf::VideoMode VideoMode defines a video mode (width, height, bpp)
class sf::Window Window that serves as a target for OpenGL rendering.

Members

enum @8

Values Descriptions
None No border / title bar (this flag and all others are mutually exclusive)
Titlebar Title bar + fixed border.
Resize Title bar + resizable border + maximize button.
Close Title bar + close button.
Fullscreen Fullscreen mode (this flag and all others are mutually exclusive)
Default Default window style.

Enumeration of the window styles.

class sf::Clipboard

Give access to the system clipboard.

sf::Clipboard provides an interface for getting and setting the contents of the system clipboard.

Usage example:

// get the clipboard content as a string
sf::String string = sf::Clipboard::getString();

// or use it in the event loop
sf::Event event;
while(window.pollEvent(event))
{
    if(event.type == sf::Event::Closed)
        window.close();
    if(event.type == sf::Event::KeyPressed)
    {
        // Using Ctrl + V to paste a string into SFML
        if(event.key.control && event.key.code == sf::Keyboard::V)
            string = sf::Clipboard::getString();
    }
}

// set the clipboard to a string
sf::Clipboard::setString("Hello World!");

See also: sf::String, sf::Event

Summary

Members Descriptions

Members

class sf::Context

class sf::Context
  : private sf::GlResource
  : private sf::NonCopyable

Class holding a valid drawing context.

If you need to make OpenGL calls without having an active window (like in a thread), you can use an instance of this class to get a valid context.

Having a valid context is necessary for every OpenGL call.

Note that a context is only active in its current thread, if you create a new thread it will have no valid context by default.

To use a sf::Context instance, just construct it and let it live as long as you need a valid context. No explicit activation is needed, all it has to do is to exist. Its destructor will take care of deactivating and freeing all the attached resources.

Usage example:

void threadFunction(void*)
{
   sf::Context context;
   // from now on, you have a valid context

   // you can make OpenGL calls
   glClear(GL_DEPTH_BUFFER_BIT);
}
// the context is automatically deactivated and destroyed
// by the sf::Context destructor

Summary

Members Descriptions
public Context() Default constructor.
public ~Context() Destructor.
public bool setActive(bool active) Activate or deactivate explicitly the context.
public const ContextSettings&getSettings() const Get the settings of the context.
public Context(const ContextSettings & settings,unsigned int width,unsigned int height) Construct a in-memory context.

Members

public Context()

Default constructor.

The constructor creates and activates the context

public ~Context()

Destructor.

The destructor deactivates and destroys the context

public bool setActive(bool active)

Activate or deactivate explicitly the context.

Parameters

  • active True to activate, false to deactivate

Returns

True on success, false on failure

public const ContextSettings&getSettings() const

Get the settings of the context.

Note that these settings may be different than the ones passed to the constructor; they are indeed adjusted if the original settings are not directly supported by the system.

Returns

Structure containing the settings

public Context(const ContextSettings & settings,unsigned int width,unsigned int height)

Construct a in-memory context.

This constructor is for internal use, you don't need to bother with it.

Parameters

  • settings Creation parameters

  • width Back buffer width

  • height Back buffer height

class sf::ContextSettings

Structure defining the settings of the OpenGL context attached to a window.

ContextSettings allows to define several advanced settings of the OpenGL context attached to a window.

All these settings with the exception of the compatibility flag and anti-aliasing level have no impact on the regular SFML rendering (graphics module), so you may need to use this structure only if you're using SFML as a windowing system for custom OpenGL rendering.

The depthBits and stencilBits members define the number of bits per pixel requested for the (respectively) depth and stencil buffers.

antialiasingLevel represents the requested number of multisampling levels for anti-aliasing.

majorVersion and minorVersion define the version of the OpenGL context that you want. Only versions greater or equal to 3.0 are relevant; versions lesser than 3.0 are all handled the same way (i.e. you can use any version < 3.0 if you don't want an OpenGL 3 context).

When requesting a context with a version greater or equal to 3.2, you have the option of specifying whether the context should follow the core or compatibility profile of all newer (>= 3.2) OpenGL specifications. For versions 3.0 and 3.1 there is only the core profile. By default a compatibility context is created. You only need to specify the core flag if you want a core profile context to use with your own OpenGL rendering. Warning: The graphics module will not function if you request a core profile context. Make sure the attributes are set to Default if you want to use the graphics module.

Setting the debug attribute flag will request a context with additional debugging features enabled. Depending on the system, this might be required for advanced OpenGL debugging. OpenGL debugging is disabled by default.

Special Note for OS X: Apple only supports choosing between either a legacy context (OpenGL 2.1) or a core context (OpenGL version depends on the operating system version but is at least 3.2). Compatibility contexts are not supported. Further information is available on the OpenGL Capabilities Tables page. OS X also currently does not support debug contexts.

Please note that these values are only a hint. No failure will be reported if one or more of these values are not supported by the system; instead, SFML will try to find the closest valid match. You can then retrieve the settings that the window actually used to create its context, with Window::getSettings().

Summary

Members Descriptions
public unsigned int depthBits Bits of the depth buffer.
public unsigned int stencilBits Bits of the stencil buffer.
public unsigned int antialiasingLevel Level of antialiasing.
public unsigned int majorVersion Major number of the context version to create.
public unsigned int minorVersion Minor number of the context version to create.
public Uint32 attributeFlags The attribute flags to create the context with.
public bool sRgbCapable Whether the context framebuffer is sRGB capable.
public inline explicit ContextSettings(unsigned int depth,unsigned int stencil,unsigned int antialiasing,unsigned int major,unsigned int minor,unsigned int attributes,bool sRgb) Default constructor.
enum Attribute Enumeration of the context attribute flags.

Members

public unsigned int depthBits

Bits of the depth buffer.

public unsigned int stencilBits

Bits of the stencil buffer.

public unsigned int antialiasingLevel

Level of antialiasing.

public unsigned int majorVersion

Major number of the context version to create.

public unsigned int minorVersion

Minor number of the context version to create.

public Uint32 attributeFlags

The attribute flags to create the context with.

public bool sRgbCapable

Whether the context framebuffer is sRGB capable.

public inline explicit ContextSettings(unsigned int depth,unsigned int stencil,unsigned int antialiasing,unsigned int major,unsigned int minor,unsigned int attributes,bool sRgb)

Default constructor.

Parameters

  • depth Depth buffer bits

  • stencil Stencil buffer bits

  • antialiasing Antialiasing level

  • major Major number of the context version

  • minor Minor number of the context version

  • attributes Attribute flags of the context

  • sRgb sRGB capable framebuffer

Values Descriptions
Default Non-debug, compatibility context (this and the core attribute are mutually exclusive)
Core Core attribute.
Debug Debug attribute.

Enumeration of the context attribute flags.

class sf::Cursor

class sf::Cursor
  : private sf::NonCopyable

Cursor defines the appearance of a system cursor.

Features related to Cursor are not supported on iOS and Android.

This class abstracts the operating system resources associated with either a native system cursor or a custom cursor.

After loading the cursor the graphical appearance with either loadFromPixels() or loadFromSystem(), the cursor can be changed with sf::Window::setMouseCursor().

The behaviour is undefined if the cursor is destroyed while in use by the window.

Usage example:

sf::Window window;

// ... create window as usual ...

sf::Cursor cursor;
if (cursor.loadFromSystem(sf::Cursor::Hand))
    window.setMouseCursor(cursor);

See also: sf::Window::setMouseCursor

Summary

Members Descriptions
public Cursor() Default constructor.
public ~Cursor() Destructor.
public bool loadFromPixels(const Uint8 * pixels,Vector2u size,Vector2u hotspot) Create a cursor with the provided image.
public bool loadFromSystem(Type type) Create a native system cursor.
enum Type Enumeration of the native system cursor types.

Members

public Cursor()

Default constructor.

This constructor doesn't actually create the cursor; initially the new instance is invalid and must not be used until either loadFromPixels() or loadFromSystem() is called and successfully created a cursor.

public ~Cursor()

Destructor.

This destructor releases the system resources associated with this cursor, if any.

public bool loadFromPixels(const Uint8 * pixels,Vector2u size,Vector2u hotspot)

Create a cursor with the provided image.

pixels must be an array of width by height pixels in 32-bit RGBA format. If not, this will cause undefined behavior.

If pixels is null or either width or height are 0, the current cursor is left unchanged and the function will return false.

In addition to specifying the pixel data, you can also specify the location of the hotspot of the cursor. The hotspot is the pixel coordinate within the cursor image which will be located exactly where the mouse pointer position is. Any mouse actions that are performed will return the window/screen location of the hotspot.

On Unix, the pixels are mapped into a monochrome bitmap: pixels with an alpha channel to 0 are transparent, black if the RGB channel are close to zero, and white otherwise.

Parameters

  • pixels Array of pixels of the image

  • size Width and height of the image

  • hotspot (x,y) location of the hotspot

Returns

true if the cursor was successfully loaded; false otherwise

public bool loadFromSystem(Type type)

Create a native system cursor.

Refer to the list of cursor available on each system (see sf::Cursor::Type) to know whether a given cursor is expected to load successfully or is not supported by the operating system.

Parameters

  • type Native system cursor type

Returns

true if and only if the corresponding cursor is natively supported by the operating system; false otherwise

enum Type

Values Descriptions
Arrow Arrow cursor (default)
ArrowWait Busy arrow cursor.
Wait Busy cursor.
Text I-beam, cursor when hovering over a field allowing text entry.
Hand Pointing hand cursor.
SizeHorizontal Horizontal double arrow cursor.
SizeVertical Vertical double arrow cursor.
SizeTopLeftBottomRight Double arrow cursor going from top-left to bottom-right.
SizeBottomLeftTopRight Double arrow cursor going from bottom-left to top-right.
SizeAll Combination of SizeHorizontal and SizeVertical.
Cross Crosshair cursor.
Help Help cursor.
NotAllowed Action not allowed cursor.

Enumeration of the native system cursor types.

Refer to the following table to determine which cursor is available on which platform.

Type Linux Mac OS X Windows

*
sf::Cursor::Arrow yes yes yes
sf::Cursor::ArrowWait no no yes
sf::Cursor::Wait yes no yes
sf::Cursor::Text yes yes yes
sf::Cursor::Hand yes yes yes
sf::Cursor::SizeHorizontal yes yes yes
sf::Cursor::SizeVertical yes yes yes
sf::Cursor::SizeTopLeftBottomRight no no yes
sf::Cursor::SizeBottomLeftTopRight no no yes
sf::Cursor::SizeAll yes no yes
sf::Cursor::Cross yes yes yes
sf::Cursor::Help yes no yes
sf::Cursor::NotAllowed yes yes yes

class sf::Event

Defines a system event and its parameters.

sf::Event holds all the informations about a system event that just happened.

Events are retrieved using the sf::Window::pollEvent and sf::Window::waitEvent functions.

A sf::Event instance contains the type of the event (mouse moved, key pressed, window closed, ...) as well as the details about this particular event. Please note that the event parameters are defined in a union, which means that only the member matching the type of the event will be properly filled; all other members will have undefined values and must not be read if the type of the event doesn't match. For example, if you received a KeyPressed event, then you must read the event.key member, all other members such as event.mouseMove or event.text will have undefined values.

Usage example:

sf::Event event;
while (window.pollEvent(event))
{
    // Request for closing the window
    if (event.type == sf::Event::Closed)
        window.close();

    // The escape key was pressed
    if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
        window.close();

    // The window was resized
    if (event.type == sf::Event::Resized)
        doSomethingWithTheNewSize(event.size.width, event.size.height);

    // etc ...
}

Summary

Members Descriptions
public EventType type Type of the event.
public SizeEvent size Size event parameters (Event::Resized)
public KeyEvent key Key event parameters (Event::KeyPressed, Event::KeyReleased)
public TextEvent text Text event parameters (Event::TextEntered)
public MouseMoveEvent mouseMove Mouse move event parameters (Event::MouseMoved)
public MouseButtonEvent mouseButton Mouse button event parameters (Event::MouseButtonPressed, Event::MouseButtonReleased)
public MouseWheelEvent mouseWheel Mouse wheel event parameters (Event::MouseWheelMoved) (deprecated)
public MouseWheelScrollEvent mouseWheelScroll Mouse wheel event parameters (Event::MouseWheelScrolled)
public JoystickMoveEvent joystickMove Joystick move event parameters (Event::JoystickMoved)
public JoystickButtonEvent joystickButton Joystick button event parameters (Event::JoystickButtonPressed, Event::JoystickButtonReleased)
public JoystickConnectEvent joystickConnect Joystick (dis)connect event parameters (Event::JoystickConnected, Event::JoystickDisconnected)
public TouchEvent touch Touch events parameters (Event::TouchBegan, Event::TouchMoved, Event::TouchEnded)
public SensorEvent sensor Sensor event parameters (Event::SensorChanged)
public union sf::Event::@5 @6
enum EventType Enumeration of the different types of events.

Members

Type of the event.

Size event parameters (Event::Resized)

public KeyEvent key

Key event parameters (Event::KeyPressed, Event::KeyReleased)

Text event parameters (Event::TextEntered)

Mouse move event parameters (Event::MouseMoved)

Mouse button event parameters (Event::MouseButtonPressed, Event::MouseButtonReleased)

Mouse wheel event parameters (Event::MouseWheelMoved) (deprecated)

Mouse wheel event parameters (Event::MouseWheelScrolled)

Joystick move event parameters (Event::JoystickMoved)

Joystick button event parameters (Event::JoystickButtonPressed, Event::JoystickButtonReleased)

Joystick (dis)connect event parameters (Event::JoystickConnected, Event::JoystickDisconnected)

Touch events parameters (Event::TouchBegan, Event::TouchMoved, Event::TouchEnded)

Sensor event parameters (Event::SensorChanged)

public union sf::Event::@5 @6

Values Descriptions
Closed The window requested to be closed (no data)
Resized The window was resized (data in event.size)
LostFocus The window lost the focus (no data)
GainedFocus The window gained the focus (no data)
TextEntered A character was entered (data in event.text)
KeyPressed A key was pressed (data in event.key)
KeyReleased A key was released (data in event.key)
MouseWheelMoved The mouse wheel was scrolled (data in event.mouseWheel) (deprecated)
MouseWheelScrolled The mouse wheel was scrolled (data in event.mouseWheelScroll)
MouseButtonPressed A mouse button was pressed (data in event.mouseButton)
MouseButtonReleased A mouse button was released (data in event.mouseButton)
MouseMoved The mouse cursor moved (data in event.mouseMove)
MouseEntered The mouse cursor entered the area of the window (no data)
MouseLeft The mouse cursor left the area of the window (no data)
JoystickButtonPressed A joystick button was pressed (data in event.joystickButton)
JoystickButtonReleased A joystick button was released (data in event.joystickButton)
JoystickMoved The joystick moved along an axis (data in event.joystickMove)
JoystickConnected A joystick was connected (data in event.joystickConnect)
JoystickDisconnected A joystick was disconnected (data in event.joystickConnect)
TouchBegan A touch event began (data in event.touch)
TouchMoved A touch moved (data in event.touch)
TouchEnded A touch event ended (data in event.touch)
SensorChanged A sensor value changed (data in event.sensor)
Count Keep last the total number of event types.

Enumeration of the different types of events.

class sf::GlResource

Base class for classes that require an OpenGL context.

This class is for internal use only, it must be the base of every class that requires a valid OpenGL context in order to work.

Summary

Members Descriptions
protected GlResource() Default constructor.
protected ~GlResource() Destructor.

Members

protected GlResource()

Default constructor.

protected ~GlResource()

Destructor.

class sf::Joystick

Give access to the real-time state of the joysticks.

sf::Joystick provides an interface to the state of the joysticks.

It only contains static functions, so it's not meant to be instantiated. Instead, each joystick is identified by an index that is passed to the functions of this class.

This class allows users to query the state of joysticks at any time and directly, without having to deal with a window and its events. Compared to the JoystickMoved, JoystickButtonPressed and JoystickButtonReleased events, sf::Joystick can retrieve the state of axes and buttons of joysticks at any time (you don't need to store and update a boolean on your side in order to know if a button is pressed or released), and you always get the real state of joysticks, even if they are moved, pressed or released when your window is out of focus and no event is triggered.

SFML supports:

Unlike the keyboard or mouse, the state of joysticks is sometimes not directly available (depending on the OS), therefore an update() function must be called in order to update the current state of joysticks. When you have a window with event handling, this is done automatically, you don't need to call anything. But if you have no window, or if you want to check joysticks state before creating one, you must call sf::Joystick::update explicitly.

Usage example:

// Is joystick #0 connected?
bool connected = sf::Joystick::isConnected(0);

// How many buttons does joystick #0 support?
unsigned int buttons = sf::Joystick::getButtonCount(0);

// Does joystick #0 define a X axis?
bool hasX = sf::Joystick::hasAxis(0, sf::Joystick::X);

// Is button #2 pressed on joystick #0?
bool pressed = sf::Joystick::isButtonPressed(0, 2);

// What's the current position of the Y axis on joystick #0?
float position = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);

See also: sf::Keyboard, sf::Mouse

Summary

Members Descriptions
enum @7 Constants related to joysticks capabilities.
enum Axis Axes supported by SFML joysticks.

Members

enum @7

Values Descriptions
Count Maximum number of supported joysticks.
ButtonCount Maximum number of supported buttons.
AxisCount Maximum number of supported axes.

Constants related to joysticks capabilities.

enum Axis

Values Descriptions
X The X axis.
Y The Y axis.
Z The Z axis.
R The R axis.
U The U axis.
V The V axis.
PovX The X axis of the point-of-view hat.
PovY The Y axis of the point-of-view hat.

Axes supported by SFML joysticks.

class sf::Keyboard

Give access to the real-time state of the keyboard.

sf::Keyboard provides an interface to the state of the keyboard.

It only contains static functions (a single keyboard is assumed), so it's not meant to be instantiated.

This class allows users to query the keyboard state at any time and directly, without having to deal with a window and its events. Compared to the KeyPressed and KeyReleased events, sf::Keyboard can retrieve the state of a key at any time (you don't need to store and update a boolean on your side in order to know if a key is pressed or released), and you always get the real state of the keyboard, even if keys are pressed or released when your window is out of focus and no event is triggered.

Usage example:

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
    // move left...
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
    // move right...
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
    // quit...
}

See also: sf::Joystick, sf::Mouse, sf::Touch

Summary

Members Descriptions
enum Key Key codes.

Members

enum Key

Values Descriptions
Unknown Unhandled key.
A The A key.
B The B key.
C The C key.
D The D key.
E The E key.
F The F key.
G The G key.
H The H key.
I The I key.
J The J key.
K The K key.
L The L key.
M The M key.
N The N key.
O The O key.
P The P key.
Q The Q key.
R The R key.
S The S key.
T The T key.
U The U key.
V The V key.
W The W key.
X The X key.
Y The Y key.
Z The Z key.
Num0 The 0 key.
Num1 The 1 key.
Num2 The 2 key.
Num3 The 3 key.
Num4 The 4 key.
Num5 The 5 key.
Num6 The 6 key.
Num7 The 7 key.
Num8 The 8 key.
Num9 The 9 key.
Escape The Escape key.
LControl The left Control key.
LShift The left Shift key.
LAlt The left Alt key.
LSystem The left OS specific key: window (Windows and Linux), apple (MacOS X), ...
RControl The right Control key.
RShift The right Shift key.
RAlt The right Alt key.
RSystem The right OS specific key: window (Windows and Linux), apple (MacOS X), ...
Menu The Menu key.
LBracket The [ key.
RBracket The ] key.
Semicolon The ; key.
Comma The , key.
Period The . key.
Quote The ' key.
Slash The / key.
Backslash The \ key.
Tilde The ~ key.
Equal The = key.
Hyphen The - key (hyphen)
Space The Space key.
Enter The Enter/Return keys.
Backspace The Backspace key.
Tab The Tabulation key.
PageUp The Page up key.
PageDown The Page down key.
End The End key.
Home The Home key.
Insert The Insert key.
Delete The Delete key.
Add The + key.
Subtract The - key (minus, usually from numpad)
Multiply The * key.
Divide The / key.
Left Left arrow.
Right Right arrow.
Up Up arrow.
Down Down arrow.
Numpad0 The numpad 0 key.
Numpad1 The numpad 1 key.
Numpad2 The numpad 2 key.
Numpad3 The numpad 3 key.
Numpad4 The numpad 4 key.
Numpad5 The numpad 5 key.
Numpad6 The numpad 6 key.
Numpad7 The numpad 7 key.
Numpad8 The numpad 8 key.
Numpad9 The numpad 9 key.
F1 The F1 key.
F2 The F2 key.
F3 The F3 key.
F4 The F4 key.
F5 The F5 key.
F6 The F6 key.
F7 The F7 key.
F8 The F8 key.
F9 The F9 key.
F10 The F10 key.
F11 The F11 key.
F12 The F12 key.
F13 The F13 key.
F14 The F14 key.
F15 The F15 key.
Pause The Pause key.
KeyCount Keep last the total number of keyboard keys.
Dash > Deprecated: Use Hyphen instead
BackSpace > Deprecated: Use Backspace instead
BackSlash > Deprecated: Use Backslash instead
SemiColon > Deprecated: Use Semicolon instead
Return > Deprecated: Use Enter instead

Key codes.

class sf::Mouse

Give access to the real-time state of the mouse.

sf::Mouse provides an interface to the state of the mouse.

It only contains static functions (a single mouse is assumed), so it's not meant to be instantiated.

This class allows users to query the mouse state at any time and directly, without having to deal with a window and its events. Compared to the MouseMoved, MouseButtonPressed and MouseButtonReleased events, sf::Mouse can retrieve the state of the cursor and the buttons at any time (you don't need to store and update a boolean on your side in order to know if a button is pressed or released), and you always get the real state of the mouse, even if it is moved, pressed or released when your window is out of focus and no event is triggered.

The setPosition and getPosition functions can be used to change or retrieve the current position of the mouse pointer. There are two versions: one that operates in global coordinates (relative to the desktop) and one that operates in window coordinates (relative to a specific window).

Usage example:

if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
    // left click...
}

// get global mouse position
sf::Vector2i position = sf::Mouse::getPosition();

// set mouse position relative to a window
sf::Mouse::setPosition(sf::Vector2i(100, 200), window);

See also: sf::Joystick, sf::Keyboard, sf::Touch

Summary

Members Descriptions
enum Button Mouse buttons.
enum Wheel Mouse wheels.

Members

enum Button

Values Descriptions
Left The left mouse button.
Right The right mouse button.
Middle The middle (wheel) mouse button.
XButton1 The first extra mouse button.
XButton2 The second extra mouse button.
ButtonCount Keep last the total number of mouse buttons.

Mouse buttons.

enum Wheel

Values Descriptions
VerticalWheel The vertical mouse wheel.
HorizontalWheel The horizontal mouse wheel.

Mouse wheels.

class sf::Sensor

Give access to the real-time state of the sensors.

sf::Sensor provides an interface to the state of the various sensors that a device provides.

It only contains static functions, so it's not meant to be instantiated.

This class allows users to query the sensors values at any time and directly, without having to deal with a window and its events. Compared to the SensorChanged event, sf::Sensor can retrieve the state of a sensor at any time (you don't need to store and update its current value on your side).

Depending on the OS and hardware of the device (phone, tablet, ...), some sensor types may not be available. You should always check the availability of a sensor before trying to read it, with the sf::Sensor::isAvailable function.

You may wonder why some sensor types look so similar, for example Accelerometer and Gravity / UserAcceleration. The first one is the raw measurement of the acceleration, and takes into account both the earth gravity and the user movement. The others are more precise: they provide these components separately, which is usually more useful. In fact they are not direct sensors, they are computed internally based on the raw acceleration and other sensors. This is exactly the same for Gyroscope vs Orientation.

Because sensors consume a non-negligible amount of current, they are all disabled by default. You must call sf::Sensor::setEnabled for each sensor in which you are interested.

Usage example:

if (sf::Sensor::isAvailable(sf::Sensor::Gravity))
{
    // gravity sensor is available
}

// enable the gravity sensor
sf::Sensor::setEnabled(sf::Sensor::Gravity, true);

// get the current value of gravity
sf::Vector3f gravity = sf::Sensor::getValue(sf::Sensor::Gravity);

Summary

Members Descriptions
enum Type Sensor type.

Members

enum Type

Values Descriptions
Accelerometer Measures the raw acceleration (m/s^2)
Gyroscope Measures the raw rotation rates (degrees/s)
Magnetometer Measures the ambient magnetic field (micro-teslas)
Gravity Measures the direction and intensity of gravity, independent of device acceleration (m/s^2)
UserAcceleration Measures the direction and intensity of device acceleration, independent of the gravity (m/s^2)
Orientation Measures the absolute 3D orientation (degrees)
Count Keep last the total number of sensor types.

Sensor type.

class sf::Touch

Give access to the real-time state of the touches.

sf::Touch provides an interface to the state of the touches.

It only contains static functions, so it's not meant to be instantiated.

This class allows users to query the touches state at any time and directly, without having to deal with a window and its events. Compared to the TouchBegan, TouchMoved and TouchEnded events, sf::Touch can retrieve the state of the touches at any time (you don't need to store and update a boolean on your side in order to know if a touch is down), and you always get the real state of the touches, even if they happen when your window is out of focus and no event is triggered.

The getPosition function can be used to retrieve the current position of a touch. There are two versions: one that operates in global coordinates (relative to the desktop) and one that operates in window coordinates (relative to a specific window).

Touches are identified by an index (the "finger"), so that in multi-touch events, individual touches can be tracked correctly. As long as a finger touches the screen, it will keep the same index even if other fingers start or stop touching the screen in the meantime. As a consequence, active touch indices may not always be sequential (i.e. touch number 0 may be released while touch number 1 is still down).

Usage example:

if (sf::Touch::isDown(0))
{
    // touch 0 is down
}

// get global position of touch 1
sf::Vector2i globalPos = sf::Touch::getPosition(1);

// get position of touch 1 relative to a window
sf::Vector2i relativePos = sf::Touch::getPosition(1, window);

See also: sf::Joystick, sf::Keyboard, sf::Mouse

Summary

Members Descriptions

Members

class sf::VideoMode

VideoMode defines a video mode (width, height, bpp)

A video mode is defined by a width and a height (in pixels) and a depth (in bits per pixel).

Video modes are used to setup windows (sf::Window) at creation time.

The main usage of video modes is for fullscreen mode: indeed you must use one of the valid video modes allowed by the OS (which are defined by what the monitor and the graphics card support), otherwise your window creation will just fail.

sf::VideoMode provides a static function for retrieving the list of all the video modes supported by the system: getFullscreenModes().

A custom video mode can also be checked directly for fullscreen compatibility with its isValid() function.

Additionally, sf::VideoMode provides a static function to get the mode currently used by the desktop: getDesktopMode(). This allows to build windows with the same size or pixel depth as the current resolution.

Usage example:

// Display the list of all the video modes available for fullscreen
std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes();
for (std::size_t i = 0; i < modes.size(); ++i)
{
    sf::VideoMode mode = modes[i];
    std::cout << "Mode #" << i << ": "
              << mode.width << "x" << mode.height << " - "
              << mode.bitsPerPixel << " bpp" << std::endl;
}

// Create a window with the same pixel depth as the desktop
sf::VideoMode desktop = sf::VideoMode::getDesktopMode();
window.create(sf::VideoMode(1024, 768, desktop.bitsPerPixel), "SFML window");

Summary

Members Descriptions
public unsigned int width Video mode width, in pixels.
public unsigned int height Video mode height, in pixels.
public unsigned int bitsPerPixel Video mode pixel depth, in bits per pixels.
public VideoMode() Default constructor.
public VideoMode(unsigned int modeWidth,unsigned int modeHeight,unsigned int modeBitsPerPixel) Construct the video mode with its attributes.
public bool isValid() const Tell whether or not the video mode is valid.

Members

public unsigned int width

Video mode width, in pixels.

public unsigned int height

Video mode height, in pixels.

public unsigned int bitsPerPixel

Video mode pixel depth, in bits per pixels.

public VideoMode()

Default constructor.

This constructors initializes all members to 0.

public VideoMode(unsigned int modeWidth,unsigned int modeHeight,unsigned int modeBitsPerPixel)

Construct the video mode with its attributes.

Parameters

  • modeWidth Width in pixels

  • modeHeight Height in pixels

  • modeBitsPerPixel Pixel depths in bits per pixel

public bool isValid() const

Tell whether or not the video mode is valid.

The validity of video modes is only relevant when using fullscreen windows; otherwise any video mode can be used with no restriction.

Returns

True if the video mode is valid for fullscreen mode

class sf::Window

class sf::Window
  : private sf::GlResource
  : private sf::NonCopyable

Window that serves as a target for OpenGL rendering.

sf::Window is the main class of the Window module.

It defines an OS window that is able to receive an OpenGL rendering.

A sf::Window can create its own new window, or be embedded into an already existing control using the create(handle) function. This can be useful for embedding an OpenGL rendering area into a view which is part of a bigger GUI with existing windows, controls, etc. It can also serve as embedding an OpenGL rendering area into a window created by another (probably richer) GUI library like Qt or wxWidgets.

The sf::Window class provides a simple interface for manipulating the window: move, resize, show/hide, control mouse cursor, etc. It also provides event handling through its pollEvent() and waitEvent() functions.

Note that OpenGL experts can pass their own parameters (antialiasing level, bits for the depth and stencil buffers, etc.) to the OpenGL context attached to the window, with the sf::ContextSettings structure which is passed as an optional argument when creating the window.

Usage example:

// Declare and create a new window
sf::Window window(sf::VideoMode(800, 600), "SFML window");

// Limit the framerate to 60 frames per second (this step is optional)
window.setFramerateLimit(60);

// The main loop - ends as soon as the window is closed
while (window.isOpen())
{
   // Event processing
   sf::Event event;
   while (window.pollEvent(event))
   {
       // Request for closing the window
       if (event.type == sf::Event::Closed)
           window.close();
   }

   // Activate the window for OpenGL rendering
   window.setActive();

   // OpenGL drawing commands go here...

   // End the current frame and display its contents on screen
   window.display();
}

Summary

Members Descriptions
public Window() Default constructor.
public Window(VideoModemode,constString& title,Uint32 style,constContextSettings & settings) Construct a new window.
public explicit Window(WindowHandlehandle,constContextSettings & settings) Construct the window from an existing control.
public virtual ~Window() Destructor.
public void create(VideoModemode,constString& title,Uint32 style,constContextSettings & settings) Create (or recreate) the window.
public void create(WindowHandlehandle,constContextSettings & settings) Create (or recreate) the window from an existing control.
public void close() Close the window and destroy all the attached resources.
public bool isOpen() const Tell whether or not the window is open.
public const ContextSettings&getSettings() const Get the settings of the OpenGL context of the window.
public bool pollEvent(Event & event) Pop the event on top of the event queue, if any, and return it.
public bool waitEvent(Event & event) Wait for an event and return it.
public Vector2i getPosition() const Get the position of the window.
public void setPosition(const Vector2i & position) Change the position of the window on screen.
public Vector2u getSize() const Get the size of the rendering region of the window.
public void setSize(const Vector2u & size) Change the size of the rendering region of the window.
public void setTitle(const String & title) Change the title of the window.
public void setIcon(unsigned int width,unsigned int height,const Uint8 * pixels) Change the window's icon.
public void setVisible(bool visible) Show or hide the window.
public void setVerticalSyncEnabled(bool enabled) Enable or disable vertical synchronization.
public void setMouseCursorVisible(bool visible) Show or hide the mouse cursor.
public void setMouseCursorGrabbed(bool grabbed) Grab or release the mouse cursor.
public void setMouseCursor(const Cursor & cursor) Set the displayed cursor to a native system cursor.
public void setKeyRepeatEnabled(bool enabled) Enable or disable automatic key-repeat.
public void setFramerateLimit(unsigned int limit) Limit the framerate to a maximum fixed frequency.
public void setJoystickThreshold(float threshold) Change the joystick threshold.
public bool setActive(bool active) const Activate or deactivate the window as the current target for OpenGL rendering.
public void requestFocus() Request the current window to be made the active foreground window.
public bool hasFocus() const Check whether the window has the input focus.
public void display() Display on screen what has been rendered to the window so far.
public WindowHandle getSystemHandle() const Get the OS-specific handle of the window.
protected virtual void onCreate() Function called after the window has been created.
protected virtual void onResize() Function called after the window has been resized.

Members

public Window()

Default constructor.

This constructor doesn't actually create the window, use the other constructors or call create() to do so.

public Window(VideoModemode,constString& title,Uint32 style,constContextSettings & settings)

Construct a new window.

This constructor creates the window with the size and pixel depth defined in mode. An optional style can be passed to customize the look and behavior of the window (borders, title bar, resizable, closable, ...). If style contains Style::Fullscreen, then mode must be a valid video mode.

The fourth parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.

Parameters

  • mode Video mode to use (defines the width, height and depth of the rendering area of the window)

  • title Title of the window

  • style Window style, a bitwise OR combination of sf::Style enumerators

  • settings Additional settings for the underlying OpenGL context

public explicit Window(WindowHandlehandle,constContextSettings & settings)

Construct the window from an existing control.

Use this constructor if you want to create an OpenGL rendering area into an already existing control.

The second parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.

Parameters

  • handle Platform-specific handle of the control

  • settings Additional settings for the underlying OpenGL context

public virtual ~Window()

Destructor.

Closes the window and frees all the resources attached to it.

public void create(VideoModemode,constString& title,Uint32 style,constContextSettings & settings)

Create (or recreate) the window.

If the window was already created, it closes it first. If style contains Style::Fullscreen, then mode must be a valid video mode.

The fourth parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.

Parameters

  • mode Video mode to use (defines the width, height and depth of the rendering area of the window)

  • title Title of the window

  • style Window style, a bitwise OR combination of sf::Style enumerators

  • settings Additional settings for the underlying OpenGL context

public void create(WindowHandlehandle,constContextSettings & settings)

Create (or recreate) the window from an existing control.

Use this function if you want to create an OpenGL rendering area into an already existing control. If the window was already created, it closes it first.

The second parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.

Parameters

  • handle Platform-specific handle of the control

  • settings Additional settings for the underlying OpenGL context

public void close()

Close the window and destroy all the attached resources.

After calling this function, the sf::Window instance remains valid and you can call create() to recreate the window. All other functions such as pollEvent() or display() will still work (i.e. you don't have to test isOpen() every time), and will have no effect on closed windows.

public bool isOpen() const

Tell whether or not the window is open.

This function returns whether or not the window exists. Note that a hidden window (setVisible(false)) is open (therefore this function would return true).

Returns

True if the window is open, false if it has been closed

public const ContextSettings&getSettings() const

Get the settings of the OpenGL context of the window.

Note that these settings may be different from what was passed to the constructor or the create() function, if one or more settings were not supported. In this case, SFML chose the closest match.

Returns

Structure containing the OpenGL context settings

public bool pollEvent(Event & event)

Pop the event on top of the event queue, if any, and return it.

This function is not blocking: if there's no pending event then it will return false and leave event unmodified. Note that more than one event may be present in the event queue, thus you should always call this function in a loop to make sure that you process every pending event.

sf::Event event;
while (window.pollEvent(event))
{
   // process event...
}

Parameters

  • event Event to be returned

Returns

True if an event was returned, or false if the event queue was empty

See also: waitEvent

public bool waitEvent(Event & event)

Wait for an event and return it.

This function is blocking: if there's no pending event then it will wait until an event is received. After this function returns (and no error occurred), the event object is always valid and filled properly. This function is typically used when you have a thread that is dedicated to events handling: you want to make this thread sleep as long as no new event is received.

sf::Event event;
if (window.waitEvent(event))
{
   // process event...
}

Parameters

  • event Event to be returned

Returns

False if any error occurred

See also: pollEvent

public Vector2i getPosition() const

Get the position of

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment